Pergunta

I can't figure out how to get filtered values from a form.

For example in controller I'm just creating a form and check if it's valid or not:

$editPersonFormObject->setData($this->getRequest()->getPost());
if ($editPersonFormObject->isValid()) {
    // saving logic
}

The form contains "name" element:

$nameObject = new Text('name');
$nameObject->setValue($personRowObject->name);

and implements the "getInputFilter" method:

$this->filter = new InputFilter();

$this->filter->add(
        array(
            'name' => 'name',
            'required' => true,
            'filters' => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim')
            ),
   ...
return parent::getInputFilter();

And it's ok for validating: a validator gets filtered value without spaces, tags and etc, but when I try to save the value in my model:

$personRowObject->name = $formObject->get('name')->getValue();

I'm getting the unfiltered value with spaces. Even when I'm trying to get the value via FormInput Filter:

$formObject->getInputFilter()->getValues();

I get an array of empty values:

array(1) {
    ["name"] => string(0) ""
}

What am I doing wrong?

Foi útil?

Solução

The correct way to retrieve data from a form is by using $form->getData()

That will either be an array of values or an object, depending on how your form is set up. The function getData() furthermore can only be called, after a form has been validated using $form->isValid(). The values you return will be filtered, too. As filtering happens before validation.

Outras dicas

You could have the object bound with the form:

$form->bind($personRowObject);

if ($form->isValid()) {
    // this returns an object already populated with the form values, filtered
    $person = $form->getData();
}

Your person object needs to have a method exchangeArray($data) where you set the desired object properties from the form data.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top