How to design Admin settings Module and code in Web Application

 We are going to discuss in this blog post one important feature most of the web applications will have. We are talking about Admin Settings/Config Settings/Admin Options in whatever name they will be called but mostly all web applications will have this. Here we will also discuss how the DB design and how it can be coded in YII Framework(Best and Easy PHP Framework). 

To make better usage of memory and speed purposes we will load them initially so they can be accessed in all of the web application. Even though we are showing how to do it in YII framework the same structure and same design can be implemented in any other language. Please free feel to share your experiences in the comment sections how it was designed by you in your web application.

Database Table Structure Of the Admin Settings

  Fields List

    * name : Backend setting name (field name) which is used in the application.

    * label : Frontend label name of the settings which is used to display in the application .

    * group : Settings are categorized into multiple groups 

Ex: Email settings,Site settings etc. 

 Specify to which group particular setting is belongs to.

    * type : Field type setting whether it is text,password, dropdown, textarea, multiselect, image, checkbox

    * validations: Validations for the particular settings is sepecified backend itself , we may have multiple validation rules which will be checked while saving the records from the front end (Ex: Required,Integer,String,…).

    * options : Option values of the  created settings is listed here if the created settings have select/multiselect field type.

    * values : Final value of the settings which will be using in the application.

    * default_values : Settings which are multiselect / dropdown  field type will be having default value (Yes/no) which will be using in the application.

    * status : Status of the settings Active/Inactive only active records are used in the application.

 Input Validations to the settings :

Retrieving Validation Rules :

 Yii 1.0 :

Created a model which is used for the validation of the fields by passing the fields as an array.          

  $criteria = new CDbCriteria();
            $criteria->condition = "is_required=" . self::IS_REQUIRED;
            $requiredFields = SettingsModelName::model()->findAll($criteria);
      //Which returns all the required fields in the table
            $criteria = new CDbCriteria();
            $criteria->condition = "integer_type=" . self::INTEGER_TYPE;
            $integerFields = SettingsModelName::model()->findAll($criteria);
     //Which returns all the integer fields in the table
            $model = new DynamicModelForValidation($fieldNames, $integerType);
            //Sending as params to the new dynamic model which is used to validate the       fields.
             CActiveForm::validate($model);
       //Ajax Validation
              DynamicModelForValidation model which we created for validating fields
            
                  // Constructor for the assiging validation fields to the public variables.
             public function __construct($requiredFields, $integerFields)
        {
            foreach ($requiredFields as $keys) {
                $this->_requiredAttributes[] = $keys[‘name’];
            }
            foreach ($integerFields as $keys) {
                $this->_integer[] = $keys[‘name’];
            }
                      }
        public function rules()
        {
            $required = implode(‘,’, array_values($this->_requiredAttributes));
            $integerValidation = implode(‘,’, array_values($this->_integer));
            
                                 return array(
             
          array($required, ‘required’, ‘message’ => ‘Please Fill {attribute}’),
    //All the attributes which are required fields
    array($integerValidation, ‘match’, ‘pattern’ => ‘/^(?=.*\d)\d*(?:\.\d*)?$/’, ‘message’ => ‘{attribute} Must Be Formatted as a Number’), // /^[0-9.\s]{1,}$/         /^\d+(\.\d{1,2})?$/
    //All the integer type validation. and also we can add custom validation rules which can used fields dependency.
             
            );
        }

 Yii 2.0 :

 By using “Dynamic model”  is a model class primarily used to support  data validation.

DynamicModel implements  data validation for the  “dynamic attributes”. It basically allows an attribute to be defined dynamically through its constructor or defineAttribute().

Validation Syntax :

DynamicModel->addRule(Fields which are need to be validated, Rule name which need to applicable for the fields);

Ex:
    DynamicModel->addRule($requiredFields, ‘required’);

          DynamicModel->addRule($integerFields, ‘integer’);

          DynamicModel->addRule($emailFields, ’email’);

          DynamicModeladdRule($file, ‘file’,[‘extensions’=>’jpg, gif, png’]);

 All the dynamic attributes are stored in the database table,those attributes are passed to the dynamic model to perform validations based on the valdiation rule which we defined for that field in the validation column.

    $adminSettings = SettingsModelName::find()->where([‘status’ => AdminSettingsConfig::ACTIVE])->all();
    //Retriving all the fields which are in active state.
    $validations = explode(‘,’,$adminSettings[‘validations’]);
    //Getting all the validations rules which are assigned to particular fields
     if(in_array(‘required’, $validations)){
      $requiredFields[]=$adminSettingsValue->name;
      //Building all the required fields in to single array
      }
      if(in_array(‘integer’, $validations)){
    $integerFields[]=$adminSettingsValue->name;
    //Building all the integer fields into an array
      }
       if(in_array(’email’, $validations)){
           $emailFields[]=$adminSettingsValue->name;
    //Building all the email validation fields into an array
        }
        if($adminSettingsValue->type == ‘image’){
                  $file[]=$adminSettingsValue->name;
    //Building file input type validation for images.
         }
        $adminSettingsModel = new \yii\base\DynamicModel($allFields,$labels);
       // Yii2 Dynamic model is used for validation of the fields.Fields are passed as an     array for the validation purpose.
                    $adminSettingsModel->addRule($requiredFields, ‘required’);
    //Adding Required validation rule for the attributes by passing all the required fields
                    $adminSettingsModel->addRule($integerFields, ‘integer’);
    //Adding Integer validation rule for the attributes by passing all the Integer fields
                    $adminSettingsModel->addRule($emailFields, ’email’);
    //Adding Email validation rule for the attributes by passing all the Email fields
                    $adminSettingsModel->addRule($file, ‘file’,[‘extensions’=>’jpg, gif, png’]);
    //Adding Image validation rule for the attributes by passing all the Image fields and applying type of images which are supported
                    
    Displaying Fields with dynamic field type in the front end for update the settings
    $adminSettingsValue//Settings  model loading
                    $type=$adminSettingsValue->type;
    //Field type which could be text,password, image, …
                    $name=$adminSettingsValue->name;
    //Name of the setting
                    $dropDownList=json_decode($adminSettingsValue->options, true);
     //converting the $adminSettingsValue->options into an array if the type is dropdown or multiselect
                   
     switch ($type) {//Swtich case is used to render the fields in the front end based on the fields type which are stored for the fields
                            case ‘text’: 
    echo $form->field($adminSettingsModel, $adminSettingsValue->name)->textInput([‘maxlength’ => true,]);
                                    break;
                            case ‘password’: 
             echo $form->field($adminSettingsModel, $adminSettingsValue->name)->PasswordInput([‘maxlength’ => true,]);
                                    break;
                            case ‘dropdown’: 
     echo $form->field($adminSettingsModel, $adminSettingsValue->name)->dropDownList($dropDownList,[‘rows’ => ‘6’]);
                                    break;
                            case ‘textarea’:
           echo  $form->field($adminSettingsModel, $adminSettingsValue->name)->widget(CKEditor::className(), [
                        ‘options’ => [‘rows’ => 6],
                        ‘preset’ => ‘basic’/*’custom,basic,full,standard’*/
                    ]);
                                    break;
                            case ‘multiselect’: 
    //converting the comma separated $adminSettingsModel->$name fields into an array
         $adminSettingsModel->$name=explode(",",$adminSettingsModel->$name);
    echo $form->field($adminSettingsModel, $adminSettingsValue->name)->dropDownList($dropDownList,[‘multiple’ => true]);
                                    break;
                            case ‘image’: 
                                    $initialPreview=”;
                                    if (!empty($adminSettingsModel->$name)) { 
     $initialPreview = Html::img(Url::To(‘/upload’).’/’.$adminSettingsModel->$name, [‘class’ => ‘file-preview-image’]);
                            }
     echo $form->field($adminSettingsModel, $adminSettingsValue->name)->widget(FileInput::classname(), [
                            ‘options’ => [‘accept’ => ‘image/*’],
                            ‘pluginOptions’ => [
                                ‘showRemove’ => true,
                                                    ‘removeClass’ => ‘btn btn-default file_remove’,
                                ‘showUpload’ => false,
                                ‘initialPreview’ => $initialPreview,
                            ]
                        ]); 
                                    break;
                            case ‘checkbox’: 
     echo $form->field($adminSettingsModel, $adminSettingsValue->name)->checkBox();
                                    break;
                            default:
    echo $form->field($adminSettingsModel, $adminSettingsValue->name)->$type([‘maxlength’ => true,]);
                    }

        //Based on the field type which is stored in the database particular field is displayed in the front end.

Create Settings :

Settings which are used globally through out the application are inserted in to the database manually by using insert command with the fields which mentioned above.

Saving Settings :

After all the fields are validated based on the validation rules those particular value is stored into the database table in the values columns.which is used globally to get the settings value.

Settings Usage :

Once settings are saved , They are loaded initially while loading the application , store them in the cache and used globally through out the application.When those settings are required those can be fetched if they are available in cache it will be returned else fetched from the database.

Fetch Syntax :            

    $adminSettings = Yii::$app->getSettings();

      adminSettings contains all the settings information by using setting name we can use the particluar value.