Welcome Guest, Not a member yet? Register   Sign In
Form validation in model
#1

I am following the News tutorial and now I try to move the validation from the News controller/create() to the  News model. 
Controller: 
PHP Code:
<?php namespace App\Controllers;
use 
App\Models\NewsModel;
use 
CodeIgniter\Controller;

class 
News extends Controller
{    
    
public function create()
    {
        helper('form');
        $model = new NewsModel();

        if ($model->save([
                'title' => $this->request->getVar('title'),
                'slug'  => url_title($this->request->getVar('title')),
                'body'  => $this->request->getVar('body'),
            ]) === false)
        {
            echo view('templates/header', ['title' => 'Create a news item']);
            echo view('news/create', ['errors' => $model->errors()]);
            echo view('templates/footer');
        }
        else
        {
            echo view('news/success');
        }
    }

News Model:
PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model// Loads database library etc

class NewsModel extends Model
{
    protected $table 'news'
    protected $returnType 'object';
    protected $allowedFields = ['title''slug''body'];

    protected $validationRules    = [
        'title' => 'required|min_length[3]|max_length[255]',
        'body'  => 'required'
    ];

    protected $validationMessages = [
        'body'        => [
            'required' => 'Can not be empty!'
        ]
    ];
    

I expected the validation rules stated in $validaiotnRules to kick in on $model->save().
The actual result is that I get the "Whoops" error when calling News/create()
Reply


Messages In This Thread
Form validation in model - by muuucho - 12-20-2019, 05:35 AM
RE: Form validation in model - by MGatner - 12-20-2019, 06:57 AM
RE: Form validation in model - by muuucho - 12-20-2019, 08:02 AM
RE: Form validation in model - by Myster - 12-20-2019, 09:07 AM
RE: Form validation in model - by muuucho - 12-20-2019, 11:35 AM



Theme © iAndrew 2016 - Forum software by © MyBB