sab0t
sab0t

Reputation: 137

Loading a Zend Form via Ajax Call

I have a requirement to load a form into a page dynamically, with the potential for multiple instances of this form. Validating and saving is not a problem, but I cannot seem to pass back the actual form content / mark-up from the Controller. When testing with simple values (id: 1) I can return the data successfully, but the actual form is always returned as undefined if the datatype is not set, or [Object object].

Controller:

public function addPermissionFormAction()
{
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout->disableLayout();
    //data from ajax call is successfully received
    $username = $this->getRequest()->getParam('user');
    //...Code to get $pages...
    $form = new Pds_Wizard_SubForm_Externals($pages);

    if(!isset($form)) $form = false;
    //I have run XDebug to here and confirmed that the form is built successfully.
    echo Zend_Json::encode(array('form' => $form));
}

My Ajax Call:

$('#get-player-permissions').click(function() {
    if($('#test-test').val().length > 0) {
        $.ajax({
        url: '/pds/external-user/add-permission-form',
        data: { user: $('#test-test').val() },
        dataType: 'json',
        contentType: "application/json",
        success: function(data){
            alert(data.form); // [Object object]
            $("#wizardContainer").html(data.form); //empty, no form content
        }
    })
    } 
});

I have tried this without even adding the dataType or contentType fields for sending simple values, and have no issue getting those through. With the form, however, I will get a null or undefined in this case.

Any advice is appreciated, including more ideal methods of dynamically loading a form. I do not use Ajax calls very often, so if this is a simple mistake I apologize. Thank you in advance!

Upvotes: 2

Views: 2962

Answers (1)

sdespont
sdespont

Reputation: 14025

You can't set "no render" in this case. You need to have a view "add-permission-form.phtml" (or another view specified) to format and display the HTML code

Controller :

public function addPermissionFormAction()
{
    $this->_helper->layout->disableLayout();

    //data from ajax call is successfully received
    $username = $this->getRequest()->getParam('user');
    //...Code to get $pages...
    $form = new Pds_Wizard_SubForm_Externals($pages);

    if(!isset($form)) $form = false;
    //I have run XDebug to here and confirmed that the form is built successfully.
    echo Zend_Json::encode(array('form' => $form));

    //Assign the form to a variable view
    $this->view->form = $form;
}

View : add-permission-form.phtml :

<?php echo $this->form ;?>

Ajax call :

No comment, your code look cool

Upvotes: 3

Related Questions