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', [
]); ?>
    <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'); ?>
    <br />
    <?php echo CHtml::submitButton('Save Changes'); ?>
<?php $this->endWidget(); ?>

Focus on an Element

<?php $form=$this->beginWidget('CActiveForm', array(
)); ?>
//...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)

    echo $form->dropDownList(
        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', 
            '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