cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Form validation and appendMessage

Open MickaelViaud opened this issue 12 years ago • 4 comments

I want to do some custom validations in my form without creating custom validators.

So I override isValid() function in my form class, which extends Phalcon\Forms\Form. In the issue #1766 it was writen that the function appendMessage is in 1.3.1 branch (see #2173).

But the function is missing and the documentation doesn't mention the function appendMessage (http://docs.phalconphp.com/en/latest/api/Phalcon_Forms_Form.html). If I implement by myself the code given in #1766 it's work.

The function appendMessage exist in Element (http://docs.phalconphp.com/en/latest/api/Phalcon_Forms_Element.html) but when i'm trying to use it, I can't display the error with $form->getMessagesFor('field_name');

I think that custom validation need a big explanation and maybe a complete tutorial to being understandable.

MickaelViaud avatar May 20 '14 14:05 MickaelViaud

It was actually merged into 1.3.2 afaik, so you have to wait for that feature.

naNuke avatar May 20 '14 23:05 naNuke

Ok thanks. Do you know why I can't use getMessageFor if I use Elements::appendMessage ?

MickaelViaud avatar May 21 '14 08:05 MickaelViaud

Because that method fetches messages from the form object and not from elements object. If you append message into element and bypass the form then the form has no way to retrieve messages.

I use this code in my application:

// TODO: !1.3.2 - remove this class, appendMessage will be implemented by framework.
class Form extends PhalconForm {

    /**
     * Appends custom message into form.
     *
     * @param   mixed   $message
     * @param   string  $field
     * @param   string  $type
     * @return  void
     * @throws  \Phalcon\Forms\Exception
     */
    public function appendMessage($message, $field, $type = null)
    {
        if ( is_string($message) )
        {
            $message = new Message($message, $field, $type);
        }

        if ( $message instanceof Message || $message instanceof ModelMessage )
        {
            // Check if there is a group for the field already.
            if ( ! is_null($this->_messages) && array_key_exists($field, $this->_messages) )
            {
                $this->_messages[$field]->appendMessage($message);
            }
            else
            {
                $this->_messages[$field] = new MessageGroup(array($message));
            }
        }
        else
        {
            throw new Exception("Can't append message into the form, invalid type.");
        }
    }

}

naNuke avatar May 21 '14 23:05 naNuke

Ok, thanks a lot. Very usefull !

MickaelViaud avatar May 22 '14 08:05 MickaelViaud