Yii CActiveForm examples

Last updated:

Simple Default Form

Assuming you have sent a variable called $model (with one attribute called name) from your controller to this view when you rendered it:

<?php $form=$this->beginWidget('CActiveForm', [
    'id'=>'my-form',
    'enableAjaxValidation'=>true,
    'clientOptions'=>[
        'validateOnSubmit'=>true
    ]
]); ?>
    <p class="note">Fields with <span class="required">*</span> are required.</p>
    <?php echo $form->errorSummary($model); ?>
    <div class="row">
        <?php echo $form->labelEx($model,'name'); ?>
        <?php echo $form->textField($model,'name'); ?>
        <?php echo $form->error($model,'name'); ?>
    </div>
    <br />
    <?php echo CHtml::submitButton('Save Changes'); ?>
<?php $this->endWidget(); ?>

Focus on an Element

<?php $form=$this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>true,
    'clientOptions'=>[
        'validateOnSubmit'=>true
    ],
    'focus'=>[$model,'name'],
)); ?>
//...form elements
<?php $this->endWidget(); ?>

Default Selected Item in DropDownList Element

To have the second option on a DropDownList selected by default, you need something like this: (wildly useful IMO)

<?php
    echo $form->dropDownList(
        $model, 
        'language', 
        CHtml::listData( Language::model()->findAll(),'id','name' ), 
        [
            'class' => 'my-drop-down',
            'options' => [
                '2' => [ 'selected' => true ]
            ]
        ]);
?>

DatePicker Element for date Attribute in a Form

<?php $this->widget('zii.widgets.jui.CJuiDatePicker', 
    [
        'model'=>$model,
        'attribute'=>'start_date',
        'options'=>[
            'showAnim'=>'fold',
            'autoSize'=>true,
            'dateFormat'=>'dd/mm/yy',
            'defaultDate'=>'10/12/2011',
        ],
        'htmlOptions'=>[
            'value'=>date_format(new DateTime,'d/m/Y'),
        ],
    ]); 
?>

P.S.: Note that you may need to convert dates from one type to another before saving it to your database. Use PHP's date_format function for that.

See also:

Dialogue & Discussion