CodeIgniter Forums
How to extend the default model - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to extend the default model (/showthread.php?tid=79315)



How to extend the default model - Zeff - 05-27-2021

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


RE: How to extend the default model - InsiteFX - 05-27-2021

Just create your own Model that extends the CI Model add your methods to it then extend your new Model
where you use Model.


RE: How to extend the default model - Zeff - 05-27-2021

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);
    }