Error:You must use the "set" method to update an entry

Asked

Viewed 58 times

0

Hello, all right ?

I’m having trouble sending data to my database. I’m trying to enter data into the BD but, error occurs on this line :

$categoriaModel->set('nomecatego', $this->request->getPost('nomecatego'));

My Model Class :

        <?php namespace App\Models;
    
    use CodeIgniter\Model;
    
    class CategoriaModel extends Model{
        protected $table = 'categoria';
        protected $primaryKey = 'id';
        protected $allowedFields = ['nome'];
        protected $returnType = 'object';
    }
?>

My Controller class :

        <?php namespace App\Controllers;
    
    
    class CategoriaController extends BaseController{
    
        
        public function index(){
            //bla bla
        }
    
        public function inserir(){
            $data['titulo'] = 'Inserir nova categoria';
            $data['acao'] = 'cadastrar';
            $data['msg'] = '';
    
            if($this->request->getMethod() === 'post'){
                $categoriaModel = new \App\Models\CategoriaModel();
                $categoriaModel->set('nomecatego', $this->request->getPost('nomecatego'));
    
                if($categoriaModel->insert()){
                    $data['msg'] = "Cadastro feito com sucesso!";
                }
                else{
                    $data['msg'] = "Cadastro não realizado!";
                }
        }
            echo View('categoria_view', $data);
        }
    
    
    }
?>

1 answer

0

I just had a similar mistake and what happened was the lack of the field in $allowedFields.

Try to put

protected $allowedFields = ['nomecatego'];

According to the documentation of Codeigniter 4:

$allowedFields

This array should be updated with the field Names that can be set During save, Insert, or update methods. Any field Names other than These will be discarded. This helps to Protect Against just taking input from a form and Throwing it all at the model, Resulting in potential mass assignment vulnerabilities.

Then, the fields passed in that variable will be the ones allowed to perform the actions of Insert, update, etc.

I hope I’ve helped

Browser other questions tagged

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