HOW TO change field validation type "on fly"?

Discuss everything related to ApPHP Durecty CMF. All versions. Any questions related to the Directy CMF developing or using should be posted to this forum.

Moderators: alexandrleonenko, alexmst

administrator
Site Admin
Site Admin
Posts: 6169
Joined: Jan 7th, '09, 23:18
Contact:

HOW TO change field validation type "on fly"?

Postby administrator » Mar 11th, '17, 11:37

The are some ways to change field's validation type "on fly".
Here some of them:

1. You may use _beforeSave() method of appropriate model and add there yuor own code, that makes all needed validations.

2. If you use CDataForm widget, we recommend to do it in a following way.
Let's see how it's released with example of Ban Lists.
You have an "item_type" field that may be "email_address", "email_domain", "ip_address" etc.
For each item type we need different validation.

2.1 In Controller receive and pass to the View "item_type" value:

Code: Select all

/**
 * Add new action handler
 */
public function addAction()
{
   // Block access if admin has no active privilege to add ban lists
   Website::prepareBackendAction('edit', 'ban_lists', 'banLists/manage');

   $this->_view->itemType = A::app()->getRequest()->getPost('item_type');
   $this->_view->render('banLists/add');
}


2.2 In the View file create field declaration according to "item_type" value:

Code: Select all

if($itemType == 'email_address'){
   $fields['item_value'] = array('type'=>'textbox', 'title'=>A::t('app', 'Item'), 'tooltip'=>'', 'default'=>'', 'validation'=>array('required'=>true, 'type'=>'email', 'maxLength'=>'100'), 'htmlOptions'=>array('maxLength'=>'100', 'class'=>'normal'));
}else if($itemType == 'email_domain'){
   $fields['item_value'] = array('type'=>'textbox', 'title'=>A::t('app', 'Item'), 'tooltip'=>'', 'default'=>'', 'validation'=>array('required'=>true, 'type'=>'text', 'maxLength'=>'100'), 'htmlOptions'=>array('maxLength'=>'100', 'class'=>'normal'));
}else if($itemType == 'username'){
   $fields['item_value'] = array('type'=>'textbox', 'title'=>A::t('app', 'Item'), 'tooltip'=>'', 'default'=>'', 'validation'=>array('required'=>true, 'type'=>'mixed', 'maxLength'=>'40'), 'htmlOptions'=>array('maxLength'=>'40', 'class'=>'normal'));
}else{
   $fields['item_value'] = array('type'=>'textbox', 'title'=>A::t('app', 'Item'), 'tooltip'=>'', 'default'=>'', 'validation'=>array('required'=>true, 'type'=>'ip', 'maxLength'=>'15'), 'htmlOptions'=>array('maxLength'=>'15', 'class'=>'normal'));
}


That's All!
Now CDataForm widget will handle "item_value" field with appropriate validation type (according to selected "item_type")

Code: Select all

echo CWidget::create('CDataForm', array(
   'model'            => 'BanLists',
   ..
   'fields'         => $fields,
   ...
));


You may find the full working example in Directy CMF code.

Return to “ApPHP Directy CMF {developers/users}”