Skip to content

[BUG]: form entity isn't passed to validator #15567

Closed
@stijn1989

Description

@stijn1989

When setting an entity to a form on construction and calling isValid($data), the entity isn't passed to the validator. The only entity that is passed, is the entity that is passed with isValid($data, $entity). But you shouldn't do this, because you already pass this entity to the form on construction.

To Reproduce

Steps to reproduce the behavior:

Person.php

<?php
class Person extends \Phalcon\Mvc\Model
{
    public $name;

    public function validation(): bool
    {
        return $this-validate(new PersonValidator());
    }
}

PersonValidator.php

<?php
class PersonValidator extends \Phalcon\Validation
{

    public function __construct()
    {
        parent::__construct([
            'name' => [
                new \Phalcon\Validation\Validator\Uniqueness(['message' => "Person name must be unique!"])
            ]
        ]);
    }

}

PersonForm.php

<?php
class PersonForm extends \Phalcon\Forms\Form
{

    public function initalize($entity = null, $options = []): 
    {
        $name = new \Phalcon\Forms\Element\Text('name');
        $name->setLabel('Name');

        $this->add($name);
        $this->setValidation(new PersonValidator());
    }

}

Provide minimal script to reproduce the issue

PersonController.php

<?php
class PersonController extends \Phalcon\Mvc\Controller
{

    public function editAction($name)
    {
        $person = Person::findByName($name);
        $form = new PersonForm($person);

        if($this->request->isPost()) {
            if($form->isValid($this->request->getPost()) {
                $person->save();
                $this->flash->success('Person saved!');
            } else {
                $this->flash->error( implode('<br>', $form->getMessages());
            }
        }

        $this->view->form = $form;
    }

}

Expected behavior
If you run this edit action and just hit save and don't change anything. It should produce the success message Person saved!.
But it doesn't. It gives the error message Person name must be unique!.

If you change the isValid() line to the line below, it works.

....
if($form->isValid($this->request->getPost(), $person) {
....

Details

  • Phalcon version: 4.1
  • PHP Version: 7.4
  • Operating System: Debian
  • Installation type: Installing from PECL.
  • Zephir version (if any):
  • Server: Nginx

Metadata

Metadata

Assignees

No one assigned

    Labels

    5.0The issues we want to solve in the 5.0 releasebugA bug report

    Type

    No type

    Projects

    Status

    Released

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions