Skip to content

[BUG]: allowEmpty for form validation does not work correctly when an entity is bound #15491

@wurst-hans

Description

@wurst-hans

Using Phalcon 4.1.2 on PHP 7.4.18. Took me a while to figure it out.

Having a simple form:

$form = new Form();
$form->add(
    (new Text('name'))->addValidators([
        new Validation\Validator\Alnum([
            'message' => 'Invalid value'
            'allowEmpty' => true,
        ]),
    ])
);
$company = new Company();
$form->bind($_POST, $company);
if ($form->isValid()) {
    // do something
}

No matter if $_POST contains a value for name or not, all is fine.
But I can't use allowEmpty=true in my projects, because this is also true for string value 0, which is wrong IMHO. To not skip any validations, I have to use allowEmpty=[null, ''] instead. When modifying the above code to:

$form = new Form();
$form->add(
    (new Text('name'))->addValidators([
        new Validation\Validator\Alnum([
            'message' => 'Invalid value'
            'allowEmpty' => [null,''],
        ]),
    ])
);
$form->bind($_POST, $company);
if ($form->isValid()) {
    // is not reached for all cases
}

the form validation for Alnum gives following results now:

  • $_POST['name'] = 'Acme'; = success
  • $_POST['name'] = ''; = success
  • $_POST['name'] = null; = fails
  • having name absent from $_POST = fails

When the form is not bound to the model, the validation does not fail for the previously mentioned cases. When var_dump()ing the validation object, I can see, that the property of the model is not null but &null. There seems to be any internal references. Maybe that's the reason why comparing allowEmpty values (see here) fails.

I expect, that allowEmpty = [null, ''] works for bound entities on forms too, even when the related property in entity is null.

Update: Found something. When replacing

$form->bind($_POST, $company);
if ($form->isValid()) {}

with

if ($form->isValid($_POST, $company)) {}

The error seems to be gone. What's the difference when using bind() explicitely?

Metadata

Metadata

Assignees

Labels

5.0The issues we want to solve in the 5.0 releasebugA bug reportstatus: mediumMedium

Type

No type
No fields configured for issues without a type.

Projects

Status
Released

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions