Yii 1.1: CGridView and AjaxForm Connect

10 followers

Scenario

As I'm new to the framework (2 weeks) - I tried to build a functionallity I already use a lot in my old framework (PRADO). This means combining a GridView with a form. And this in one page, what allows you to select a record from the grid and view the values in the same page without jumping to a new page.

Try and error

I started to dig arround and came to a point where I used renderPartial to update the form, the problem is, that using this function, I destroy the jQuery id's which disallows me to use widgets like CAutocomplete... And I don't wanna miss the funcionallity.

How-To Do It

views

<div id="mySubView">
 
<?php
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $dataprovider,
    'id'=>'recipient_table',
        'selectionChanged'=>'updateEditForm',
    'columns' => array(
        'rec_id',
                'org.nachname',
                'org.vorname',
                'org_id',
                array(
                    'class'=>'CButtonColumn',
                    'template'=>'{delete}',
                    'deleteButtonUrl'=>'Yii::app()->createUrl("//recipient/delete", array("id" => $data[\'rec_id\']))',
                ),
          ));
 
?>
 
    <div id="mySubViewForm">
 
    <?php $this->renderPartial('//recipient/_form', array('model'=>$submodel)); ?>
 
    </div>
 
</div>

And to later update the values in the form, we need the following javascript update

<script type="text/javascript">
 
function updateEditForm(target_id){
 
    var id =$.fn.yiiGridView.getSelection(target_id);
 
    $('#save_btn').attr('disabled', (id > 0 ? false : true));
 
    $.getJSON('<?php echo Yii::app()->createUrl("//recipient/subviewload");?>'+'&id='+id,
            function(data) {
                $('#sub_org_id').val(data.nachname);
                                $('#Recipient_org_id').val(data.org_id);
                                $('#Recipient_kom_id').val(data.kom_id);
                                $('#Recipient_rec_id').val(data.rec_id);
                                $('#Recipient_report_id').val(data.report_id);
            });
 
}
 
</script>

views _form

In the detail form we need the following code -> attention!!! I use the extension.ajaxform which is needed for the functionallity!

<div class="form">
 
<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'recipient-form',
    'enableAjaxValidation'=>true,
)); ?>
 
    <p>&nbsp;</p>
 
    <fieldset class="box">
        <legend>Recipient</legend>
    <?php echo $form->errorSummary($model); ?>
 
        <table>
            <tr class="row">
                <td>
                    <?php echo $form->labelEx($model,'org_id'); ?>
                </td>
                <td>
                    <?php
 
                    $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
                       //'model'=>$model,
                       'name'=>'sub_org_id',
                       'value'=>CHtml::encode(Organisation::model()->findByPK($model->org_id)->nachname),
                       'source' => $this->createUrl('Organisation/autocompleteOrganisation'),
                       'options' => array(
                            'minLength'=>'2',
                            'select'=>"js:function(event,ui){
                                $('#".CHtml::activeId($model,'org_id')."').val(ui.item.id);
                            }",
                       ),
                    ));
 
                    ?>
                    <?php echo $form->hiddenField($model,'org_id'); ?>
                    <?php echo $form->error($model,'org_id'); ?>
                </td>
                <td>
                    <?php echo $form->textField($model,'kom_id'); ?>
                    <?php echo $form->error($model,'kom_id'); ?>
                    <?php echo $form->hiddenField($model,'rec_id'); ?>
                </td>
                <td>
                    <?php echo CHtml::ajaxButton($model->isNewRecord ? 'Create' : 'Update',
                            CHtml::normalizeUrl(array('//recipient/subviewedit')),
                            array(
                                'type'=>'POST',
                                'success'=>'function(responseText,statusText) {
                                                $.fn.yiiGridView.update(\'recipient_table\');
                                            }',
                            ),
                            array('class'=>'button','id'=>'rec_save_button'));
                    ?>
                </td>
            </tr>
        </table>
 
        <?php echo $form->hiddenField($model,'report_id'); ?>
        <?php echo $form->error($model,'report_id'); ?>
 
   </fieldset>
    <p class="note">Fields with <span class="required">*</span> are required.</p>
 
<?php $this->endWidget(); ?>
 
</div><!-- form -->
 
<?php
$this->widget('ext.ajaxform.JAjaxForm',array(
    'formId'=>'recipient-form',
    'options'=>array(
        'dataType'=>'json',      
    ),
));
?>

controller To get it working, you should add the following code to your controller

public function actionSubViewEdit()
    {
                if(isset($_POST['Recipient']['rec_id'])){
                    $model=$this->loadModel($_POST['Recipient']['rec_id']);
                }else{
                    $model = new Recipient();
                }
 
                // Uncomment the following line if AJAX validation is needed
        //$this->performAjaxValidation($model);
 
        if(isset($_POST['Recipient']))
        {
            $model->attributes=$_POST['Recipient'];
            $model->save();
        }
 
    }
 
        public function actionSubViewLoad($id)
    {
 
                $criteria=new CDbCriteria(
                    array(
                        'condition'=>'rec_id = '.$id,
                        'with'=> array('org'),
                ));
 
                $model=Recipient::model()->find($criteria);
 
                $res = array(
                    'rec_id'=>$model->rec_id,
                    'org_id'=>$model->org_id,
                    'kom_id'=>$model->kom_id,
                    'nachname'=>$model->org->nachname,
                    'report_id'=>$model->report_id
                );
 
                echo CJSON::encode($res);
 
    }

I hope this helps, if it can be done smarter, pls tell me!;-)

Total 2 comments

#3261 report it
horizons at 2011/03/30 04:26am
I have some problems with this code (remark)

Guess it would help if you also post your actionAdmin function of your controller. I guess you also call actionSubViewEdit() in this function to have that ajax validation you mentioned. But still I don't understand the purpose of ext.ajaxform.JAjaxForm?

#3260 report it
horizons at 2011/03/30 04:10am
I have some problems with this code
  1. for what reason do you use ext.ajaxform.JAjaxForm? (can you explain?)
  2. you render the first view of your _form with $submodel where does this come from? is it just a new model? cause then you never get the button to 'update' via $model->isNewRecord. Maybe you also post the code of your action in the controller.
  3. you use the id 'save_btn' in your javascript code $('#save_btn').attr('disabled', (id > 0 ? false : true)); but in your _form its 'rec_save_button'.
  4. how does ajax validation works? for me its not working the form makes an ajax call to my actionAdmin which renders the gridview.

Leave a comment

Please to leave your comment.

Write new article