Richard
Richard

Reputation: 5890

CakePHP 3, Very Basic Save Not Working

For some reason the automated conversion of $this->request->data to an entity is not working. I created a very basic save in order to test it.

$users = TableRegistry::get('VendorName/Users.Users');
$this->request->data = ['username' => 'someting', 'password' => 'somethingelse'];
$user = $users->newEntity($this->request->data);
if ($users->save($user)) { }

This is the SQL that that produces::

INSERT INTO users (created, modified, id) VALUES (:c0, :c1, :c2)

I've tried making $this->request->data as a function, eg. $this->request->data()

I've tried explicitly adding the entity value. Eg. $user->username = 'someting'; and it works when I do this. But of course, I don't want to explicitly state every single field in every single save function, so why isn't $this->request->data converting automatically?

This is the what $user looks like

object(VendorName\Users\Model\Entity\User) {

    '[new]' => true,
    '[accessible]' => [],
    '[dirty]' => [],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'VendorName/Users.Users'

}

Upvotes: 0

Views: 629

Answers (1)

Dakota
Dakota

Reputation: 458

The problem is that you've specified that no fields in the Entity are allowed to be mass assigned (See http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment), by having protected $_accessible = []; in your Entity class (VendorName\Users\Model\Entity\User).

It sounds like you want all properties to be mass assignable, so what you probably want is protected $_accessible = ['*' => true];.

Just note that this is dangerous as it can allow anybody to alter their form slightly and then modify any other entity. A better setting is protected $_accessible = ['id' => false, '*' => true];

Upvotes: 2

Related Questions