Welcome Guest, Not a member yet? Register   Sign In
How to extend the default model
#1

Hi friends,

For a specific App, I want to add some extra functionality (a createDropdown() method) to the default model (System\Model - which extends the BaseModel in the same location) so I can use it in all my models. Does someone has a neat / best practise solution for this?

Thanks!

Zeff
Reply
#2

Just create your own Model that extends the CI Model add your methods to it then extend your new Model
where you use Model.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3
Sad 
(This post was last modified: 05-27-2021, 05:11 AM by Zeff.)

Thanks InsiteFX!

It's that simple... I still have to get used to the new way of coding in CI4.
I've shared my code for my 'BaseModel' in App\Models, maybe I can be helpfull for others...

PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model;

class 
BaseModel extends Model
{
    /**
     * Produces array to generate form elements easily, eg. SELECT elements (key/id => value pairs), RADIO or CHECKBOX iterations
     * 
     * @param string $field      # Which field to use as value (primary key is used as key)
     * @param bool $addHeader    # Add a first array element with empty key and a '__Please select' value
     * @param string $headerText # custom header text (if you do not want to use the custom '__Please select)
     * @return array
     */
    
public function dropdown(string $fieldbool $addHeader=TRUEstring $headerText=null)
    {

        
$fieldnames $this->getFieldNames($this->table); // array
        
        
if(!isset($field) || !in_array($field$fieldnames))
                    throw new \
Exception("The field `".$field."` does not exist in table `".$this->table."`");
        
        
$types $this->select($this->primaryKey$field)->asArray()->findAll();
        
        
$keys array_column($types$this->primaryKey);
        
$values array_column($types$field);

        
// Add empty row ad beginning
        
if($addHeader===TRUE)
        {
            
array_unshift($keys'');
            
$headerText = (is_null($headerText)) ?  '__Please select...' '__'.$headerText;
            
array_unshift($values$headerText);
        }
        
        return 
array_combine($keys$values);
    }

Reply




Theme © iAndrew 2016 - Forum software by © MyBB