Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you show dynamic code based on a dropdown in a persistent way with yii?

Tags:

jquery

ajax

yii

I render some form elements when a dropdown is changed in yii, like so:

$form->dropdownListRow($model, 'type', array('item1','item2','etc') ,
    array('ajax'=>array(
        'type'=>'POST',
        'url'=>CController::createUrl('ProfileFieldRule/showAttributes'),
        'update'=>'#showAttributes',                        
    ))
));

ProfileFieldRule/showAttributes uses CHtml to render form elements, which leads to my first problem - I have to use opentag, etc and repeat work that's done in the form.

echo CHtml::openTag('div', array('class' => 'control-group '));
echo CHtml::activeLabel($attr, $name, array('class' => 'control-label'));
etc

The second problem is: if there is no change event (eg the forms submitted with errors) the dynamic content doesn't load.

I'm currently passing a model and checking if it's null, and otherwise doing the same rendering as in ProfileFieldRule/showAttributes eg:

   <div id="showAttributes">
    <?php if (isset($attr)) {
        //do the same rendering as in showAttributes
        $vars = get_class_vars(get_class($attr));
             foreach ($vars as $name => $value) {
                 //etc...
    ?>
    </div>

It would be ideal if I could just call the above code onload, onchange, and still have access to the $form.

I'm open to anything, so what's the best (or a good) solution to showing and persisting dynamic content as described above?

Thanks in advance for any advice.

edit

Here's an image of what's happening http://imgur.com/cZjRZ note, the rendered elements aren't showing ajax validation (highlighting in red/green) because I'm bad with ajax and still figuring

I should note, that another solution I've considered is getting rid of showAttributes, continuing to pass two models to the form, and just calling the create action again on change. This however gets rid of previous ajax validation when the dropdown is changed, as the entire form is redrawn.

like image 586
cnorris Avatar asked Dec 19 '12 01:12

cnorris


1 Answers

I had this problem before as well.

The problem lies in the .bind('change'), you should use .live('change') instead, In jQuery 1.7 this is solved by using the .on() function that does both live and normal binds. Unforgettably Yii doesnt have the latest jQuery. For some projects i updated jQuery manually but keep in mid you will have to extend base classes to fix jQuery errors you'll get. For a more direct and one time solution you could write a bit of js, that unbinds your events on the elements and then re-bind them with the .live() function. But its all a bit hacky to say the least.

like image 126
DarkMukke Avatar answered Nov 06 '22 01:11

DarkMukke