Welcome Guest, Not a member yet? Register   Sign In
Validation in the Model not working
#1

Hi all,
I am trying to perform data validation in my Model class, following along with the instruction/practices mentioned in the docs here. I am getting the error: 
PHP Code:
Call to a member function setRules() on null 
 
Here is my code:
My form has this code:
PHP Code:
<?=$this->extend("layouts/base");?>

<?=$this->section("title");?>
<?=$page_title
;?>
<?=$this
->endSection();?>

<?=$this->section("content");?>
<div class="container-login">
<?php if (! empty($errors)) : ?>
    <div class="alert alert-danger">
    <?php foreach ($errors as $field => $error) : ?>
        <p><?= $error ?></p>
    <?php endforeach; ?>
    </div>
<?php endif; ?>
<div class="container">
<div class="row align-items-center justify-content-center">
<?=form_open(base_url('/walks/create'), ['class' => "shadow p-3 mb-5 bg-white rounded"]);?>
<div class="form-group">
<?=form_label('Day of Walk''day_walked');?>
<?=form_input
(['name' => 'day_walked''type' => 'date''id' => 'day_walked''class' => 'form-control''value' => set_value('day_walked''')]);?>
<span class="invalidFeedback" id="day_walked_span">
</span>
</div>
<div class="form-group">
<?=form_label('Calories Burned''cal_burned');?>
<?=form_input
(['name' => 'cal_burned''class' => 'form-control''type' => 'number''step' => '0.01''id' => 'cal_burned''value' => set_value('cal_burned''')]);?>
<span class="invalidFeedback" id="cal_burned_span">
</span>
</div>
<div class="form-group">
<?=form_label('Distance of Walk''miles_walked');?>
<?=form_input
(['name' => 'miles_walked''class' => 'form-control''type' => 'number''step' => '0.01''id' => 'miles_walked''value' => set_value('miles_walked''')]);?>
<span class="invalidFeedback" id="miles_walked_span">
</span>
</div>
<div class="form-group">
<?=form_label('Duration of Walk''duration');?>
<?=form_input
(['name' => 'duration''class' => 'form-control''type' => 'text''id' => 'duration''placeholder' => 'HH:MM:SS''value' => set_value('duration''')]);?>
<span class="invalidFeedback" id="duration_span">
</span>
</div>
<div class="form-group">
<?=form_label('Pace''mph');?>
<?=form_input
(['name' => 'mph''class' => 'form-control''type' => 'number''step' => '0.01''id' => 'mph''value' => set_value('mph''')]);?>
<span class="invalidFeedback" id="mph_span">
</span>
</div>
<div class="form-group">
<?=form_label('Shoe Worn''shoe_id');?>
<?=form_dropdown
('shoe_id'$shoes, ['id' => 'shoe_id']);?>
<span class="invalidFeedback" id="shoe_id_span">
</span>
</div>
<div class="row">
<div class="col offset-1">
<?=anchor(base_url('/walks'), 'Cancel', ['class' => 'btn btn-primary''role' => 'button']);?>
</div>
<div class="col offset-2">
<?=form_submit('walk_add_btn''Add Walk', ['id' => 'walk_add_btn''class' => 'btn btn-primary']);?>
</div>
</div>
<?=form_close();?>
</div>
</div>
</div>
<?=$this->endSection();?>

Here is the controller and method I am using to process the form data:
PHP Code:
<?php
namespace App\Controllers;

use 
App\Models\WalkModel;
use 
App\Models\ShoeModel;

class 
Walks extends BaseController
{

    public $walk_model;
    public $shoe_model;
    public $shoes;
    
    
public function __construct() {
    $this->walk_model = new WalkModel();
    $this->shoe_model = new ShoeModel();
        $this->shoes $this->shoe_model->findAll();
    }

    public function index() {
    $data = [
    'page_title' => 'All Walks',
    'walks' => $this->walk_model->getAllWalks(),
    'shoes' => $this->shoes,
            'errors' => NULL,
    ];

    return view('walks/w_index'$data);
    }

    public function create() {
        //Creating a $shoes array for the dropdown where they are needed
        foreach ($this->shoes as $shoe) {
            $shoes[$shoe->shoe_id] = $shoe->brand_name;
        }
        //default ordering of shoes by brand_name ASC
        array_multisort($shoesSORT_ASC);

        $data = [
            'page_title' => 'Add A Walk',
            'shoes' => $shoes,
            'errors' => NULL
        
];

        if ($this->request->getMethod() == 'post') {
            
            $walk_data 
= [
                'day_walked' => $this->request->getVar('day_walked'FILTER_SANITIZE_STRING),
                'cal_burned' => $this->request->getVar('cal_burned'FILTER_SANITIZE_STRING),
                'miles_walked' => $this->request->getVar('miles_walked'FILTER_SANITIZE_STRING),
                'duration' => $this->request->getVar('duration'FILTER_SANITIZE_STRING),
                'mph' => $this->request->getVar('mph'FILTER_SANITIZE_STRING),
                'shoe_id' => $this->request->getVar('shoe_id'FILTER_SANITIZE_STRING
            ];

            if ($this->walk_model->insert($walk_data) === false) {
                $data['errors'] = $this->walk_model->errors();
            } else {
                return redirect()->to(base_url('walks'));
            }
            
        
}// post request method ends here

        return view('walks/create'$data);
    //create method ends here

    public function update() {
    //not implemented
    }

    public function delete() {
    //not implemented
    }

And here is my Model class that I am trying to use for the validation:
PHP Code:
<?php
namespace App\Models;

use 
CodeIgniter\Model;

class 
WalkModel extends Model
{
protected 
$table      'walking_stats';
protected 
$primaryKey 'day_walked';
protected 
$returnType    'object';
protected 
$allowedFields = ['day_walked''cal_burned''miles_walked''duration''mph''shoe_id'];
protected 
$db;
protected 
$builder;

protected 
$validationRules = [
'day_walked' => 'required|is_unique[walking_stats.day_walked]',
'cal_burned' => 'required|decimal|greater_than[0]',
'miles_walked' => 'required|decimal|greater_than[0]',
'duration' => 'required|exact_length[8]',
'mph' => 'required|decimal|greater_than[0]',
'shoe_id' => 'required|integer'
  ];

  protected $validationMessages = [
  'day_walked' => [
  'required' => 'Must choose a date value',
  'is_unique' => 'A walk has already been recorded for date {param}',
  ],
  'cal_burned' => [
  'required' => 'Calories burned value is required',
  'decimal' => 'Calories burned must be in decimal number format',
  'greater_than' => 'Calories burned value must be greater than 0 (zero)',
  ],
  'miles_walked' => [
 
'required' => 'A distance walked value is required',
  'decimal' => 'The distance walked value must be in decimal number format',
  'greater_than' => 'The distance walked value must be greater than 0 (zero)',
  ],
  'duration' => [
  'required' => 'A duration value is required',
  'exact_length' => 'Format error - Not enough values. Duration value must be in HH:MM:SS format',
  ],
  'mph' => [
  'required' => 'The pace of the walk value is required',
  'decimal' => 'The pace of the walk value must be in decimal number format',
  'greater_than' => 'The pace of the walk value must be greater than 0 (zero)'
  ],
  'shoe_id' => [
  'required' => 'Must choose from the drop-down selection of shoes',
  'integer' => 'Only choices from the drop-down selection are allowed'
  ]
  ];

  protected $skipValidation    false;

public function 
__construct() {
$this->db      = \Config\Database::connect();
$this->builder $this->db->table($this->table); 
}

public function 
getAllWalks() {
$this->builder->select('day_walked, cal_burned, miles_walked, duration, mph, brand_name')
->
join('shoes_worn''walking_stats.shoe_id = shoes_worn.shoe_id');
return 
$this->builder->get()->getResult();
}


I am new at CI4 and not really sure where I am going wrong with this.
I am able to
Code:
var_dump($walk_data)
in the controller so I am getting the values from the form without any issues.
Any help, suggestions, or ideas is most appreciated.
Thanks all,
Reply
#2

(This post was last modified: 01-25-2021, 01:30 PM by Corsari.)

sorry , entered text in the wrong thread - deleted
Reply
#3

(01-17-2021, 08:55 AM)Corsari Wrote: Hello friends

I have found the solution

The problem for me was to make the right use of alias for columns

Easy task for experienced coders ... but I'm not and experienced coder so ..

For others newbies I write what I have found as solution

PHP Code:
$data $ticketModel ->select('ticket.id, ticket.name as t_name, ticket.date, dept.name')
                     ->where('ticket.dept_id''52')
                     ->join('dept''ticket.dept_id = dept.id')
                     ->orderBy('ticket.date''desc')
                     ->findAll();

dd($data); 

kind regards
Hi,
Not sure how this applies to my specific question.
Should I alias the columns in the
Code:
getAllWalks()
method in my Model?
Thanks
Reply
#4

(01-17-2021, 06:13 AM)josh2112o Wrote: Hi all,
I am trying to perform data validation in my Model class, following along with the instruction/practices mentioned in the docs here. I am getting the error: 
PHP Code:
Call to a member function setRules() on null 
 

You have overridden the model constructor.
The model constructor already defines the $db property. And you can get access to QueryBuilder by calling the $this->builder() method.
If you still need a class constructor, then call the parent's constructor.
Reply
#5

(01-17-2021, 11:32 AM)iRedds Wrote:
(01-17-2021, 06:13 AM)josh2112o Wrote: Hi all,
I am trying to perform data validation in my Model class, following along with the instruction/practices mentioned in the docs here. I am getting the error: 
PHP Code:
Call to a member function setRules() on null 
 

You have overridden the model constructor.
The model constructor already defines the $db property. And you can get access to QueryBuilder by calling the $this->builder() method.
If you still need a class constructor, then call the parent's constructor.
OMG!! It works! Thanks so much!!!
Reply
#6

Sorry i dont really understand, Do you mean that the error is here :

protected $table = 'walking_stats';
protected $primaryKey = 'day_walked';
protected $returnType = 'object';
protected $allowedFields = ['day_walked', 'cal_burned', 'miles_walked', 'duration', 'mph', 'shoe_id'];
protected $db; ===> HERE ?
protected $builder;
Reply
#7

(01-18-2021, 11:06 AM)neoneeco Wrote: Sorry i dont really understand, Do you mean that the error is here :

protected $table      = 'walking_stats';
protected $primaryKey = 'day_walked';
protected $returnType    = 'object';
protected $allowedFields = ['day_walked', 'cal_burned', 'miles_walked', 'duration', 'mph', 'shoe_id'];
protected $db;  ===> HERE ?
protected $builder;
Hi,
No my error was due to having overwritten the default Model constructor.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB