Hi,
I’m currently using code that lets users create new form fields, then set them as either as required or not required. The problem I’m having is that as this is a component, and not in the model, I can’t add it to the rules if validation is equal to 1 in the db.
How do I go about dynamically adding values to the rules? or at least adding errors to these fields. Ie. Adding a validator to all attr with the value of required field 1
This dynamic form data doesgo into the user type variable model as the name, but that model seems to be purely working for the form to input the data rather than handling the dynamic data. This data also needs passed through with the user model when the user form is created
class DynamicForm extends CWidget {
public $attributes = array();
public $id = null;
public $enctype = null;
public $target = null;
public $action = null;
public $model_name = '';
public $method = 'post';
public function init() {
parent::init();
}
public function run() {
foreach ($this->attributes as $attr) {
$attr['formname'] = $this->model_name . '_' . $attr['name'];
$attr['htmlOptions'] = array('class' => 'span5', 'placeholder' => $attr['name']);
$attr['htmlOptions']['class'] .= ' form-control';
if ($attr['required'] === 1){
$attr['requiredfields'] = array('required' => true);
}else{
$attr['requiredfields'] = '';
}
if ($attr['type'] == 'text') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],$attr['requiredfields']);
echo CHtml::textField($attr['formname'], $attr['value'], $attr['htmlOptions']);
echo '</div>';
}
elseif ($attr['type'] == 'radio') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],$attr['requiredfields']);
echo CHtml::radioButton($attr['formname'],$attr['requiredfields']);
echo '</div>';
}
elseif ($attr['type'] == 'textarea') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],$attr['requiredfields']);
echo CHtml::textArea($attr['formname'], $attr['value'], $attr['htmlOptions']);
echo '</div>';
}
elseif ($attr['type'] == 'select') {
$items = explode(',', $attr['options']);
echo CHtml::label($attr['name'], $attr['formname'],$attr['requiredfields']);
//echo CHtml::dropDownList($attr['formname'], $attr['value'], array($items));
echo CHtml::dropDownList($attr['formname'], $attr['value'], $items, array('class'=>'form-control','prompt'=>'Please Choose'));
echo '</div>';
}
elseif ($attr['type'] == 'boolean') {
echo '<div class="form-group">';
echo CHtml::label($attr['name'], $attr['formname'],$attr['requiredfields']);
echo CHtml::radioButtonList($attr['formname'], $attr['value'], array('No' => 0, 'Yes' => 1));
echo '</div>';
}
}
}
}
The user form
<div class="clearfix"></div>
<?php
$varform = new DynamicForm();
$varform->attributes = $user->getDynamicFormConfig();
$varform->model_name = 'user';
echo $varform->run();
?>