mercoledì, febbraio 13, 2013

Yii: click on a link, post your request

In a RESTful application written with Yii, I have an action that fixes some data in the db (like, for instance, the width and the height of an image), by checking some extra sources (the file). I needed to show a link that, when clicked, fired a POST request, and not a GET one. The obvious solution was to find out how to do it with some ajax call, but I wanted to see what Yii gave me.

I was happy to find out that Yii's CHtml::link() function already has everything needed. In particular, just adding 'submit'=>true in the $htmlOptions array, like in

<p><?php echo CHtml::link(
    'Fix picture',
      'submit' => $url,
      'title' => 'Check real size and type and fix data base entries',

is enough to produce a nice unobtrusive javascript code, like the following:
(in the body)

<p><a title="Check real size and type and fix data base entries" href="/yii/photoalbum/index.php?r=picture/fix&amp;id=6" id="yt0">Fix picture </a></p>

(in the jquery code produced, at the end of the page)

jQuery('body').on('click','#yt0',function(){jQuery.yii.submitForm(this,'/yii/photoalbum/index.php?r=picture/fix&id=6',{'YII_CSRF_TOKEN':'168375210910867a3dfab3db8750c4ad5f5aee2a'});return false;});

I needed to set csrf to true because my main config file has CRSF protection enabled.
I wanted the application to work even if javascript is disabled (Progressive Enhancement), so I prepared a fix.php view anyway, with a standard form containing only the submit button, like here:
<?php $form=$this->beginWidget('CActiveForm'); ?>
    <div class="row submit">
        <?php echo CHtml::submitButton('Fix'); ?>
<?php $this->endWidget(); ?>
The form won't be shown if users have their javascript enabled.

Nessun commento:

Posta un commento