We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon Form get Filtered Value

Hi,

Having recently delved into the world of Phalcon from a background using Zend Framework, I'm really impressed with Phalcon so far - great work!

I'm looking for a method to return filtered values when using filters with Phalcon\Forms\Form.

I have a form that makes use of filters to validate the data (lowercase and trim the value):

public function initialize()
{
    ...
    $guid = new Text('guid');
    $guid->setFilters(array('lower', 'trim'));
    $this->add($guid);
    ...
}

However I'm unable to get the filtered values, using $form->getValue('guid') in my controller returns the raw value, not filtered, however it seems that the validation is carried out on the filtered values (as expected).

$form = new Application();
if ($this->request->isPost()) {
    $data = $this->request->getPost();
    if ($form->isValid($data)) {
        echo $form->getValue('guid'); // Raw value
    }
}

I've been scanning the documentation, github issues and this forum but unable to determine if this is possible or I'm doing something wrong.

The only mention in the docs is here, but there are no examples or additional info on getting filtered values.

Can anybody point me in the right direction of what I should be doing to get the filtered values?

Many thanks.

Steve



33.8k

I think this is what you're looking for https://docs.phalcon.io/es/latest/reference/filter.html#sanitizing-data (if I understood well).



1.0k

That's not quite what I was after no, here's a little more information on what I'm trying to achieve.

If the current default behavior of Phalcon\Forms\Form->getValue() is to return an unfiltered value, despite having filters applied to elements in the form class, then I am looking to retrieve to the filtered values.

This can be achieved by writing my own function in a base form class and extending this, for example:

public function getFilteredValue($key)
    {
     // Get the raw value...
    $value = $this->getValue($key);
     // Lookup filters for this element...
    $filters = $this->get($key)->getFilters();
     // Apply any filters...
    foreach ($filters AS $filter) {
        $value = $this->filter->sanitize($value, $filter);
    }
     // Return the filtered value...
    return $value;
}

It seems odd that there is no interface for retrieving the filtered value, so either I'm looking in the wrong place or this feature has not been implemented.



33.8k

Then I think you'll need to implement it, either in a new function or in an event callback ( https://docs.phalcon.io/en/latest/reference/forms.html#event-callbacks ). I also think that the feature isn't implemented from what I founded.