Back to Form class

Method filter

public mixed
filter
(mixed $data, mixed $group = null)
Method to filter the form data.
Parameters
  • array $data An array of field values to filter.
  • string $group The dot-separated form group path on which to filter the fields.
Returns
  • mixed Array or false.
Since
  • 4.0.0
Class: Form
Project: Joomla

Method filter - Source code

/**
 * Method to filter the form data.
 *
 * @param   array   $data   An array of field values to filter.
 * @param   string  $group  The dot-separated form group path on which to filter the fields.
 *
 * @return  mixed  Array or false.
 *
 * @since   4.0.0
 */
public function filter($data, $group = null)
{
    // Make sure there is a valid Form XML document.
    if (!$this->xml instanceof \SimpleXMLElement) {
        throw new \UnexpectedValueException(sprintf('%s::%s `xml` is not an instance of SimpleXMLElement', \get_class($this), __METHOD__));
    }
    $input = new Registry($data);
    $output = new Registry();
    // Get the fields for which to filter the data.
    $fields = $this->findFieldsByGroup($group);
    if (!$fields) {
        // PANIC!
        return false;
    }
    // Filter the fields.
    foreach ($fields as $field) {
        $name = (string) $field['name'];
        // Get the field groups for the element.
        $attrs = $field->xpath('ancestor::fields[@name]/@name');
        $groups = array_map('strval', $attrs ?: []);
        $attrGroup = implode('.', $groups);
        $key = $attrGroup ? $attrGroup . '.' . $name : $name;
        // Filter the value if it exists.
        if ($input->exists($key)) {
            $fieldObj = $this->loadField($field, $group);
            // Only set into the output if the field was supposed to render on the page (i.e. setup returned true)
            if ($fieldObj) {
                $output->set($key, $fieldObj->filter($input->get($key, (string) $field['default']), $group, $input));
            }
        }
    }
    return $output->toArray();
}