Error saving a record with a new role

good morning guys, a cordial greeting.
I am writing to you for the following.
I have a table of roles, which only saves an id, since the roles are managed as environment variables and not from the database.
I want to store a new role that it creates, but it won’t let me do that. I have no idea why. I share part of the code:

public function new(){

        $this->set('title', __('New'));
        $this->viewBuilder()->setLayout('admin');

        $user = $this->Users->newEntity();

        $role = $this->request->getQuery('role');

        if ($role == 'kippero_nocertf') {
            $role_id = Configure::read('ROLES.KIPPERO_NOCERTF');
            $title_msg = 'kippero sin certificar';
        }

        if ($this->request->is('post')){
            //debug($this->request->data);
            $user = $this->Users->patchEntity($user, $this->request->data());

            $user->role_id = $role_id;

            if($this->Users->save($user)){
                $this->Flash->success(__('Save'));
                //return $this->redirect(['controller' => 'Users', 'action' => 'index']);
            }else{
                $this->Flash->error(__(Error'));
            }
        }

        $central = $this->Users->Central->find('list', ['limit' => 200])->order(['name' => 'asc']);

        $cities = $this->Users->Cities->find('list', ['limit' => 200])->order(['name' => 'asc']);

        $roles = $this->Users->Roles->find('list', ['limit' => 200])->order(['name' => 'asc']);

        $this->set(compact('user', 'central', 'cities', 'roles'));

    }

thanks in advance

Have you looked at $user->getErrors() after the save fails? That should give you a good idea of what’s going wrong. May be related to the fact that you’re not setting $role_id except in one particular case?

Maybe you need to add role_id to the accesible array for mass assignment in Users entity
https://book.cakephp.org/4/en/orm/saving-data.html#converting-request-data-into-entities
https://book.cakephp.org/4/en/orm/entities.html#mass-assignment