Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How Merge a Model Validation with Forms Validation

Hi,

I'm having problems to put and merge model with forms validation.

In my first attempt, I create a method on form called "mergeValidation", with message parameters, something like this code below:

// in form public function mergeValidation($messages) { foreach($messages as $message) {

$field = $this->get($message->getField());
if(/* verify if field exists and it has a "appendMessage" method -- returns true*/)
$field->appendMessage($message->getMessage());

}

}

// in controller

if($model->save()) { $form->mergeValidation($model->getMessages()); } $this->view->form = $form;

But it's not work and the Exception returns something like: "Method appendmessage in a non-object" (appendmessage all in lowercase)

If someone has another solution... Thanks

edited Jun '15

Hi, use this approach in controller:

$form = new myForm();
$model = new myModel();

if ($form->isValid($this->request->getPost()) != false) {
    if(!$model->save()) {
        $modelMessages = [];
        foreach($model->getMessages() as $message) {
            $modelMessages[] = new \Phalcon\Validation\Message($message)
        }
        $form->getMessagesFor('anyfieldname')->appendMessages($modelMessages);
    }
}

You can capsulate this functionality in an Base form class and use it with assiciated entity of form.

// in form method

public function mergeValidation() {
    $messages = $this->getEntity()->getMessages();
    $messagePlaceholder = $this->getMessagedFor('entity_specific_messages');
    foreach($messages as $message) {
        messagePlaceholder->appendMessage(new \Phalcon\Validation\Message($message)); 
    }
}

I did not test the second approach , but It should works.

Regards.



4.0k
Accepted
answer

@webalissoncs: $model->getMessages() return Phalcon\Mvc\Model\MessageInterface[] type. Form elements function appendMessage() expects Phalcon\Validation\MessageInterface type. Then your function mergeValidation() can be like this:

public function mergeValidation($messages)
{
    foreach ($messages as $message) {
        if($this->has($message->getField())) {
            $this->getMessagesFor($message->getField())
                ->appendMessage(
                    new \Phalcon\Validation\Message(
                        $message->getMessage(),
                        $message->getField(),
                        $message->getType()
                    )
                );
        }
    }
}