Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fuel fieldset: populate / repopulate widgets
<?php
class Fieldset extends \Fuel\Core\Fieldset {
/**
*
* @param \Fuel\Core\Fieldset_Field $field A field instance
* @return \Fuel\Core\Fieldset_Field
*/
public function add_field(\Fuel\Core\Fieldset_Field $field) {
$name = $field->name;
if (empty($name))
{
throw new \InvalidArgumentException('Cannot create field without name.');
}
// Check if it exists already, if so: return and give notice
if ($existing = static::field($name))
{
\Error::notice('Field with this name exists already, cannot be overwritten through add().');
return $existing;
}
// Make sure fieldset is current
if ($field->fieldset != $this) {
\Error::notice('A field added through add() must have the correct parent fieldset.');
return false;
}
$this->fields[$name] = $field;
return $field;
}
/**
* Override default populate() to allow widgets populate themselves
* @param array|object The whole input array
* @param bool Also repopulate?
* @return Fieldset this, to allow chaining
*/
public function populate($input, $repopulate = false) {
foreach ($this->fields as $f) {
if (substr(strtolower(\Inflector::denamespace(get_class($f))), 0, 6) == 'widget') {
$f->populate($input);
}
}
return parent::populate($input, $repopulate);
}
/**
* Override default repopulate() to allow widgets populate themselves
*
* @param array|object input for initial population of fields, this is deprecated - you should use populate() instea
* @return Fieldset this, to allow chaining
*/
public function repopulate($repopulate = false) {
$input = strtolower($this->form()->get_attribute('method', 'post')) == 'get' ? \Input::get() : \Input::post();
foreach ($this->fields as $f) {
// Don't repopulate the CSRF field
if ($f->name === \Config::get('security.csrf_token_key', 'fuel_csrf_token'))
{
continue;
}
if (substr(strtolower(\Inflector::denamespace(get_class($f))), 0, 6) == 'widget')
{
// Widgets populates themselves
$f->repopulate($input);
}
}
return parent::populate($input, $repopulate);
}
/**
* Get populated values
*
* @param string null to fetch an array of all
* @return array|false returns false when field wasn't found
*/
public function value($name = null) {
if ($name === null)
{
$values = array();
foreach ($this->fields as $f)
{
$values[$f->name] = $f->value;
}
return $values;
}
return $this->field($name)->value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment