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

Validation::bind() actually does NOT assign data to entity.

Phalcon\Validation:bind($entity, $data) actually does NOT assign data to entity - in opposite to what the docs here informs us.


/**
     * Assigns the data to an entity
     * The entity is used to obtain the validation values
     *
     * @param object entity
     * @param array|object data
     * @return \Phalcon\Validation
     */
public function bind(entity, data) -> <Validation>
{
// ... 
}

According to the docs I am expecting something like this:

$_GET = [
'lat' => 12.121212,
'lon' => 22.222222,
];

$validation = new PositionValidation();
$position = new Position(); //empty object with "lat", "lon" properties; setters and getters are there

$validation->bind($position, $_GET();
$validation->validate();

var_dump($position); //data are valid so I would like to properties within $position object to be populated by $validation object.

The problem is it does not happen.

The example here is with 2x properties but my case is an API call with about 15 properties. What I was expecting that using Phalcon I can populate the entity object with data from the array so that I don't need to write lot of setting lines.

My questions:

(1) Is this expected behaviour?

(2) Is there a way I can achieve my goal which is easly populate an entity with many properties from $_GET array after data are being validated?

Thanks in advance!

1) Yes it is expected behaviour. 2) Assign data to model, not to data.

If there is an entity the data to validate is got from entity. Since you didnt set data to entity it is all nulls.



577

@Jurigag Thanks!

If the data to validate are taken from the entity so why is that the bind method requires both entity and data to be passed? Why is that the validate() method looks for both data and entity?

What sense does it make?

public Phalcon\Validation\Message\Group validate ([array | object $data], [object $entity]); //both optional
public Phalcon\Validation bind (object $entity, array | object $data); //both mandatory
edited Dec '16

https://github.com/phalcon/cphalcon/blob/master/phalcon/validation.zep#L451

There you have source code. Tbh - i cant really answer your question why it's mandatory. Just dont use bind method. You could create issue for this.

edited Dec '16

I also hit the wall with this method recently, while trying to supply $_FILES as entity for FileValidator.

It's nature is very unclear and not useful to be present in public API.

Description looks good though:

* Assigns the data to an entity
* The entity is used to obtain the validation values

:S