CJuiDialog to update a model

Hey all,

i have some trouble with the correct use of CJuiDialog.

I have a page where i edit company data.

Each company has several offices, which i want to make editable (create new office, edit office, delete office) via ajax.

I managed to accomplish the create part with CJuiDialog:




	$this->beginWidget('zii.widgets.jui.CJuiDialog', array(

    	'id'=>'niederlassung_neu',

    	'options'=>array(

        	'title'=>'Niederlassung hinzufügen',

        	'autoOpen'=>false,

    	),

	));


	$niederlassung = new Niederlassungen;

	$parent_id = Yii::app()->getRequest()->getQuery('id');


	echo CHtml::beginForm('','post',array('id'=>'add-nl-form')).'

	';

	echo CHtml::activeHiddenField($niederlassung, 'vermittler_id', array('value'=>$parent_id)).'

	';

	echo CHtml::activeLabelEx($niederlassung, 'firma2').'

	';

	echo CHtml::activeTextField($niederlassung, 'firma2').'

	';


	// ... some other form fields


	echo '<p>'.CHtml::ajaxSubmitButton('Speichern',

               						CController::createUrl('niederlassungenManager/ajaxCreate'),

               						array('success'=>'js: function(data) {

                                                        	$("#nl-list").replaceWith(data);

                                                        	$("#niederlassung_neu").dialog("close");

                                                    	}'

                                        	)

               						).'</p>

	';


	echo CHtml::endForm().'

	';


	$this->endWidget('zii.widgets.jui.CJuiDialog');



i am calling the dialog with




echo CHtml::imageButton(Yii::app()->request->baseUrl.'/images/icons_16x16/add.png', array(

   'onclick'=>'$("#niederlassung_neu").dialog("open"); return false;',

   'title'=>'Niederlassung hinzufügen',

));



the model is created and the list of offices is updated afterwards. so far so good.

now comes the tricky part:

i have an edit-button for each office in the list, and i want to open a dialog with the model data, change the data, save and update the list.

i just don’t know how to get the model id of each office into the dialog, so i can fetch the appropriate data to populate the form.




	$niederlassung = new Niederlassungen;

	$nl_id = ?; // get the office id and load the model data

	$niederlassung->loadModel($nl_id);


	echo CHtml::beginForm('','post',array('id'=>'add-nl-form')).'

	';

	echo CHtml::activeHiddenField($niederlassung, 'id', array('value'=>$nl_id));



or do i have to create a CJuiDialog for each office and populate it at page render? that wouldn’t be very elegant, or would it.

any hint is appreciated, thanks.

Were you able to figure this out? I’m having the same issue. I followed

http://www.yiiframework.com/wiki/145/cjuidialog-for-create-new-model and was able to get a dialog for creating a model just fine.

Now, I can’t figure out how to dynamically create the update URL in my function to include the ID, as the php script is server side and the javascript is client side… this doesn’t work.




<script type="text/javascript">

function updateCustomer(HowToGetJavaScriptVariableHere)

{

   

    <?php echo CHtml::ajax(array(

        

            'url'=>array('customers/update?id='.HowToGetJavaScriptVariableHere),

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)

            {

                if (data.status == 'failure')

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    $('#dialogUpdateCustomer div.divForForm form').submit(updateCustomer);

                }

                else

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    setTimeout(\"$('#dialogUpdateCustomer').dialog('close') \",3000);

                    js:location.reload(true);

                }


            } ",

            ))?>;

    return false;


}

</script>



Any help would be greatly appreciated!

I attempted to just take the jquery.ajax output and put it in another function to see if I could get it to work outside of yii. My function is:


function updateCustomer(varid)

{

        jQuery.ajax({'url':'/customers/update?id='+varid','data':$(this).serialize(),'type':'post','dataType':'json','success':function(data)

            {

                if (data.status == 'failure')

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                          // Here is the trick: on submit-> once again this function!

                    $('#dialogUpdateCustomer div.divForForm form').submit(updateCustomer);

                }

                else

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    setTimeout("$('#dialogUpdateCustomer').dialog('close') ",3000);

                    js:location.reload(true);

                }

 

            } ,'cache':false});;

        return false;

}

This actually updates the form fields, but I am unable to submit as


$('#dialogUpdateCustomer div.divForForm form').submit(updateCustomer); 

calls the function without giving a parameter. I tried for example to give .submit(updateCustomer(varid)) and the form continually refreshes and doesn’t allow input or submission.

Anyone have any ideas?

So I got it to work with a noobish hack. As it didn’t like me setting the variable via a parameter, I made a global variable with a setter function above my updateCustomer function:


var globalvarid = 0;

function setGlobalVarId(gvarid)

{

    globalvarid = gvarid;

}

Then on the click, I call the setGlobalVarId to set the ID before calling my updateCustomer function.


"onclick"=> "{setGlobalVarId($data->CustomerID); updateCustomer(); $(\'#dialogUpdateCustomer\').dialog(\'open\'); }"

Then I changed my updateCustomer() to not have a parameter but reference the global variable, and look like this:


function updateCustomer()

{

        jQuery.ajax({'url':'/customers/update?id='+globalvarid','data':$(this).serialize(),'type':'post','dataType':'json','success':function(data)

            {

                if (data.status == 'failure')

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                          // Here is the trick: on submit-> once again this function!

                    $('#dialogUpdateCustomer div.divForForm form').submit(updateCustomer);

                }

                else

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    setTimeout("$('#dialogUpdateCustomer').dialog('close') ",3000);

                    js:location.reload(true);

                }


            } ,'cache':false});;

        return false;

}

I’m happy I was able to finally get this to work, however I would appreciate if there is a better way to do this.

Is very easy, just do like that:


'url'=>array('customers/update', 'id'=>$model->id),

So, the complete function result as:




<script type="text/javascript">

function updateCustomer(HowToGetJavaScriptVariableHere)

{

   

    <?php echo CHtml::ajax(array(

        

            'url'=>array('customers/update', 'id'=>$model->id),

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)

            {

                if (data.status == 'failure')

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    $('#dialogUpdateCustomer div.divForForm form').submit(updateCustomer);

                }

                else

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    setTimeout(\"$('#dialogUpdateCustomer').dialog('close') \",3000);

                    js:location.reload(true);

                }


            } ",

            ))?>;

    return false;


}

</script>




The CHtml::ajax is a php function wich writes down js code. You can use phpVariables here and the result will be in js code.

[quote=“zaccaria, post:5, topic:35923”]

Is very easy, just do like that:


'url'=>array('customers/update', 'id'=>$model->id),

This is ok if you have only one model, but it doesn’t work if you have a grid with several rows, because you have a different id for each one and you have to create the url dynamically with the id from selected row

You can use ‘js:var’ on url param of CHtml::ajax to access to jscript vars, and it’s possible to pass params to submit eventhandler of the form using the syntax




.submit({'url':url},function(e){updateCustomer(e.data.url)});



So, you can try something like this:




<script type="text/javascript">


function updateCustomer(id)


	url='<?php echo Yii::app()->createUrl('/customers/update');?>&id='+id;

	showCustomer(url);

        $('#dialogClassroom').dialog('open');


}


function showCustomer(url)

{

   

    <?php echo CHtml::ajax(array(

        

            'url'=>'js:url',

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)

            {

                if (data.status == 'failure')

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    $('#dialogUpdateCustomer div.divForForm form').submit({'url':url},function(e){updateCustomer(e.data.url)});

                }

                else

                {

                    $('#dialogUpdateCustomer div.divForForm').html(data.div);

                    setTimeout(\"$('#dialogUpdateCustomer').dialog('close') \",3000);

                    js:location.reload(true);

                }


            } ",

            ))?>;

    return false;


}

</script>



Very helpful, but for some reason using $data->Id breaks the dialog.

This works


array(

	'class'=>'CButtonColumn',

	'template'=>'{open}',

	'buttons'=>array(

		'open'=>array(

		      'label'=>'view',

		      'click'=>'js:function(data){urlProject(1); $("#dialogProject").dialog("open");}',

	        ),

        ),

),

but this doesn’t. (The dialog won’t open)


array(

	'class'=>'CButtonColumn',

	'template'=>'{open}',

	'buttons'=>array(

		'open'=>array(

		      'label'=>'view',

		      'click'=>'js:function(data){urlProject($data->Id); $("#dialogProject").dialog("open");}',

		),

	),

),

I’m using cecilio’s suggestion.

Any ideas?