Save int, but display texts

1

I'm studying Cake and I'm having a question, is there any way I can display a list, but save a number in BD?

For example, permission levels:

0 - admin
1 - vendas
2 - Edição
3 - Financeiro

In all views should only appear the text, but when saving save the number.

    
asked by anonymous 24.08.2017 / 16:15

1 answer

1

You can use the Entity for this, through a virtual field. Leave your field (which is saved in the bank) as hidden, and create a new field (with another name) as virtual.

Dai creates a setter that takes the string value, transforms it into a number and saves the data in the bank field, and a getter takes the bank number and returns the string.

It would look something like this:

class User extends Entity
{
    protected $_hidden = ['permissoes'];
    protected $_virtual = ['cargo'];

    protected function _getCargo()
    {
        $dicionario = [
            0 => 'admin', 
            1 => 'vendas', 
            2 => 'Edição',
            3 => 'Financeiro'
        ];
        return $dicionario[$this->_properties['permissoes']];
    }
    protected function _setCargo($cargo)
    {
        $dicionario = [
            'admin' => 0, 
            'vendas' => 1, 
            'Edição' => 2,
            'Financeiro' => 3
        ];
        return $dicionario[$cargo];
    }
}
    
25.08.2017 / 16:12