Save int, but display text

Asked

Viewed 41 times

1

I’m studying Cake and I have a question, have some way to display a list, but save a number in the comic?

For example, permission levels:

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

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

  • I believe that this part of the documentation can help you better, https://book.cakephp.org/3.0/en/views/helpers/form.html#options-for-select-checkbox-and-radio-Controls

  • Thank you for the answer. So, do you have how to do this on the model, facilitating maintenance afterwards?

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 value in string, transforms it into number and saves the data in the database field, and a getter takes the database number and returns the string.

It would be something like that:

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];
    }
}
  • Just remember to check there in the variable $dicionario if the Dice exists, if not, can give the error undefiend index

Browser other questions tagged

You are not signed in. Login or sign up in order to post.