Jonnny
Jonnny

Reputation: 5039

Correct way to render a form in a modal or bootbox in Yii

I'm having some trouble trying to work out how to render a form within a modal box within Yii.

Currently I have the following code, in which I've just worked in getting a link to display a modal box.

CHtml::link(' Email this Gift', '#', array( 

        'id' => 'giftModal',
        'onclick'=>'js:bootbox.confirm("hello world")',
            )
        );

I really need to render a form within the modal box. How do I do that, I have actually spent quite a while looking at how to accomplish this, but I've clearly been searching incorrectly, so would appreciate any guidance.

Thank you

Upvotes: 0

Views: 6031

Answers (1)

Telvin Nguyen
Telvin Nguyen

Reputation: 3559

Put what you want into hidden div, in this case I put my form into other view for convenience.

    <!-- dialog contents on hidden div -->   

   <div id="modal-content" class="hide">
    <div id="modal-body">
<!-- put whatever you want to show up on bootbox here -->
    <?php
        //example
        $model = Category::model()->findByPk(1);
        $this->renderPartial('//test/child-view', array('model'=>$model)) ?>
    </div>
</div>

Then pass message into bootbox with above content

<script>
    $(function(){
        bootbox.confirm($('#modal-body').html());
</script>

When you are working with form, the button of modal box is outside your form, you have to customize a bit to make your form working properly.

Example when click button "OK" of bootbox you call submit your form by script

$('my-form-selector').submit();

Important: Because in this code I got HTML from hidden div, so there would have two forms (one on bootbox, one on hidden div). You have to add class bootbox as prefix of form element to indicate the form which you manipulate on bootbox instead (in my case, bootbox is just generated class by its self library and is the parent of content on modal box, my-form-selector could be #form-id, .form-class-name, etc)

 bootbox.confirm($('#modal-body').html(), function(result){
            if(result){
                console.log($('.bootbox my-form-selector').parent().parent()); //<--it should print the object of modal bootbox, it ensures the form is in modal box, not one on hidden div-->
                $('.bootbox my-form-selector').submit();
            }});

I think you should use dialog instead of confirm, because there you can fully customize your modal box

Upvotes: 2

Related Questions