CGridView and AjaxForm Connect

  1. Scenario
  2. Try and error
  3. How-To Do It

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!;-)

1 0
10 followers
Viewed: 24 200 times
Version: 1.1
Category: How-tos
Written by: PinkBrainPlan
Last updated by: PinkBrainPlan
Created on: Mar 13, 2011
Last updated: 8 years ago
Update Article

Revisions

View all history

Related Articles