Welcome Guest, Not a member yet? Register   Sign In
How to extend the default model
#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


Messages In This Thread
How to extend the default model - by Zeff - 05-27-2021, 12:04 AM
RE: How to extend the default model - by InsiteFX - 05-27-2021, 01:14 AM
RE: How to extend the default model - by Zeff - 05-27-2021, 01:55 AM



Theme © iAndrew 2016 - Forum software by © MyBB