phpzend-frameworksocialengine

What is the best way to add a form from within a Zend controller?


I want to add a form that I have created inside my controller. But the page does not show anything.

This is the form code:

class Advancedsms_Form_ChangePassword extends  Engine_Form {
    //put your code here
    public function init() {
        parent::init();

        $this->setTitle(Zend_Registry::get('Zend_Translate')->_('Change Password'))
                ->setDescription(Zend_Registry::get('Zend_Translate')->_('Enter your new password'))
                -> setAttrib('id', 'change_password')
                -> setAttrib('enctype', 'multipart/form-data')
                ->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble([]));

        $this->addElement('Password', 'password', [
            'label'=> Zend_Registry::get('Zend_Translate')->_('New Password'),
            'description' => Zend_Registry::get('Zend_Translate')->_('Enter your new password'),
            'required' => true,            
        ]);

        $this->addElement('Password', 'password_confirm', [
            'label' => Zend_Registry::get('Zend_Translate')->_('Confirm your new password'),
            'description' => Zend_Registry::get('Zend_Translate')->_('Confirm your new password'),
            'required' => true,
        ]);

        $this->addElement('submit', 'submit', [
                'label'=> Zend_Registry::get('Zend_Translate')->_('Submit'),
            'required' => true,
                ]
                );

        $this->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array('controller' => 'api', 'action' => 'changepassword'), 'change_password'));
    }
}

The route I use is http://example.com/advancedsms/api/changepassword defined as follows:

'change_password' => [
    'route' => 'advancedsms/:controller/:action/*',
    'defaults' => [
        'module' => 'advancedsms',
        'controller' => 'api',
        'action' => 'changepassword',
    ],
    'reqs' => [
        'controller' => '\D+',
        'action' => '\D+',
    ]
], 

My action code inside controller class:

class Advancedsms_ApiController extends Core_Controller_Action_Standard {
    /**
     * This handles password change
     */
    public function changepasswordAction() {
    }

}

How can I insert a form from within a controller?


Solution

  • Pass form object to view, and render there.

    [controller: inside action]

    $this->view->form = $form = new Advancedsms_Form_ChangePassword();
    
    if(!$this->getRequest()->isPost()) { //ends action() flow, and renders view.
      return;
    }
    
    if($form->isValid($this->getRequest()->getPost())) { // rules added in form definition gets validated here.
      // process the post data here.
    
    }
    

    [view]

    echo $this->form->render();