Sunday, September 21, 2014

3.0: Entity get/set mutators

i have several tables with an `active` column, and the Admin should be able to de/activate records to determine whether they & related records are available in the application.

Instead of constantly converting T/F or 1/0 to "Active"/"Inactive", i wrote an Entity getter:

protected function _getActive($active) {
    return $active ? 'Active' : 'Inactive';
}

That's been working pretty well. The Entity->active property always provides the string.

The problem is updating the data:

SomeTableController gets a request like /some_table/active/2/1 to set ID 2 "active" (1):

public function active($id, $active) {
    $entity = $this->SomeTable->get($id);
    $entity->active = $active;

    if ($this->SomeTable->save($entity)) {
        // Success!
    }
    else {
        // Fail!
    }
}


The problem: save() reports a successful save, but the database isn't updated. Scratch that: the `modified` column is updated, but not the `active` flag.

If i kill _getActive() the update works, but i lose the convenience of the string representation.

My guess is, i need a setter to handle the switch, but i'm not sure exactly how they work. The documentation (http://book.cakephp.org/3.0/en/orm/entities.html#Cake\ORM\Entity::set) for set mutators shows an example of setting some other entity property ('slug') using the 'title' property. But there's no example for mutating the property being called, and i don't know if that even makes sense...

Along with no _setActive mutator, i also tried the following:

protected function _setActive($active) {
    // $this->set('active', $active); <-- Created loop condition & fatal error.

    $this->_properties['active'] = $active;
    return $active;
}

No luck. It does the same as no setter: updates the entity (with updated active & modified properties), but save() doesn't write the changed active property to the database.

Any help? Thanks.
-joe t.

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: