2009年2月24日星期二

Re: [fw-mvc] Zend Forms and Filters

-- PHPScriptor <contact@phpscriptor.com> wrote
(on Tuesday, 24 February 2009, 03:03 AM -0800):
> I've a little question how I could deal with Forms and Filters.
>
> Lets say, I put a filter on an element that will change my input value.
> Only, I find it always strange that, from the moment I do getPost I get the
> unfiltered values.
>
> What I do know, after the getPost I do:
> $formData['day'] = Zend_Filter_MyFilter::filter($formData['day']);
>
> In my opinion, I have to do 2 times the filter just to get the correct
> value. In this example I only have to do it once, but what if I have 7
> Filters in a form, it becomes a lot of work and code.
> Isn't there a way to set the filter on the formelements, en get the filtered
> values in the controller?

addFilter, addFilters, and setFilters all allow you to manipulate the
filter chain of an individual element -- and I see you doing that
correctly below.

However, please remember that filtering is done on the value stored in
the element -- you need to assign a value to the element first. When you
then retrieve the value from the element, you get the filtered value.

So, as an example from your action controller:

$request = $this->getRequest();
if ($request->isPost() && $form->isValid($request->getPost())) {
// success...
$values = $form->getValues(); // Now you have filtered values
}

Note the getValues() call -- this pulls all elements of the form --
and those values will have been passed through the filter chains
attached to each element. The values in $_POST are _not_ filtered -- you
filter via the form and form elements.

>
> // form
> $formElements[]= self::createElement('text','day')
> ->addValidator('int')
> ->addFilter(new Zend_Filter_MyFilter())
> ->addValidator('Between',false, array(0,24));
>
> // controller
> if ($this->_request->isPost()) {
> $formData = $this->_request->getPost();
> if ($form->isValid($formData)) {
> ... // submit value to db
> }
> }

--
Matthew Weier O'Phinney
Software Architect | matthew@zend.com
Zend Framework | http://framework.zend.com/

没有评论: