Search code examples
entitycakephp-3.0

cakePHP3: Change Entity membername before render


Is there a elegant way to change an entity membername before it is passed to a view? In my example I have an entity product. My product has a member application_id. I output it to json. Now my Frontend Developer would like to recieve this value as applicationId (no underscore).

As I'm returning a rather complex structure with objects, containing other objects and so on, I won't like to iterate over the whole resultset and change membernames in a loop. So I looked into the entity and hoped to find something like a $_map where I could map membernames to custom names, but I didn't find anything.

Is there a way to do that without using a loop in beforeRender?


Solution

  • The manual says

    When converting an entity to an JSON the virtual & hidden field lists are applied. Entities are recursively converted to JSON as well. This means that if you eager loaded entities and their associations CakePHP will correctly handle converting the associated data into the correct format.

    So you can create a virtual property in your Entoty this way

    protected $_virtual = ['ApplicationId'];
    
    protected function _getapplicationId()
    {
        return $this->application_id;
    }
    

    seems a little bit against cake naming conventions but it works