cakephp: New entity should not bypass validation

This is a (multiple allowed):

  • bug

  • enhancement

  • feature-discussion (RFC)

  • CakePHP Version: latest master 3.5.x

What you did

Somewhere in the code was a left over

$data = [
    ...
];
$modulesTable->saveOrFail($modulesTable->newEntity());

What happened

Stored in DB as entity of content:

		'id' => (int) 2,
		'name' => '',
		'version' => '',

It silently saved it without all the validation triggered, which is defined as

        $validator
            ->requirePresence('name', 'create')
            ->add('name', 'unique', ['rule' => ['validateUnique', ['scope' => ['name', 'type']]], 'provider' => 'table'])
            ->notEmpty('name');

        $validator
            ->requirePresence('version', 'create')
            ->notEmpty('version');

What you expected to happen

This should not allow to be saved with the constraints here not respected (in this case name and version being not empty).

What could be done here for the code to be less error prone (by accident) and make sure the entities are not persisted like this when accidentally forgetting to pass the $data?

Doesn’t newEntity() patch just as patchEntity() does? And therefore does not accept this state?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 24 (22 by maintainers)

Most upvoted comments

We now have two methods at least - for most cases this could suffice. So I will close this for now.

Making the first argument required is not a bad idea, we could explore that

Validation would be triggered only if you pass $data argument to newEntity(), which isn’t in your example. Since no data is passed there’s nothing to validate.