2

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?

4

2 回答 2

6

从表单中检索数据的正确方法是使用$form->getData()

这将是一个值数组或一个对象,具体取决于您的表单的设置方式。此外,该函数getData()只能在使用 验证表单$form->isValid()才能调用。您返回的值也将被过滤。由于过滤发生在验证之前

于 2013-09-13T06:48:10.927 回答
0

您可以将对象与表单绑定:

$form->bind($personRowObject);

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

您的人员对象需要有一个方法exchangeArray($data),您可以在其中从表单数据中设置所需的对象属性。

于 2013-09-13T08:18:12.350 回答