How to render form elements in view?
I have created a form like this:
class Form_Login extends Zend_Form {
public function __construct() {
$this->setMethod('post');
$elements = array();
// username
$element = $this->addElement('text', 'username', array('label' => 'Username') );
$elements[] = $element;
// password
$element = $this->addElement('password', 'password', array('label' => 'Password'));
$elements[] = $element;
// submit
$element = $this->addElement('submit', 'submit', array('label' => 'Login'));
$elements[] = $element;
$this->addElements( $elements );
$this->addDecorator('ViewHelper');
$this->setDecorators(array(array('ViewScript', array('viewScript' => 'authentication/login-form.phtml' ))));
}
}
Now in login-form.phtml file I render elements like thi开发者_JAVA百科s:
<form action='submitlogin' method='post' id='loginform'>
Login Form
<?= $this->form->getElement('username'); ?>
<?= $this->form->getElement('password'); ?>
</form>
It gives me following error:
Fatal error: Call to a member function getElement() on a non-object in
/var/www/student/application/views/scripts/authentication/login-form.phtml on line 5
How to render elements in external script...
You can call elements from the view scripts like this:
<?= $this->element->username ?>
For specific element components you can use the next things:
<? $el = $this->element->username; ?>
<label><?= $el->getLabel() ?></label>
<?= $this->formText($el->getName(), $el->getValue(), $el->getAttribs()) ?>
Here is my complete solution:
Form Class in Login.php:
class Form_Login extends Zend_Form {
/**
* Constructor
*/
public function __construct( $options = null ) {
parent::__construct( $options );
// Set the method for the display form to POST
$this->setMethod('post');
$elements = array();
$element = $this->CreateElement('text', 'username');
$element->setLabel('Username');
$elements[] = $element;
$element = $this->CreateElement('password', 'password');
$element->setLabel('Password');
$elements[] = $element;
$element = $this->CreateElement('submit', 'submit');
$element->setLabel('Login');
$elements[] = $element;
$this->addElements( $elements );
$this->setElementDecorators( array( 'ViewHelper' ) );
$this->setDecorators( array( array( 'ViewScript', array( 'viewScript' => 'authentication/login-form.phtml' ) ) ) );
} // end construct
} // end class
login-form.phtml
<form action=<?= $this->element->getAction() ?> method=<?= $this->element->getMethod() ?> >
<table>
<tr>
<td><label><?= $this->element->username->getLabel() ?></label></td>
<td><?= $this->element->username; ?></td>
</tr>
<tr>
<td><label><?= $this->element->password->getLabel() ?></label></td>
<td><?= $this->element->password; ?></td>
</tr>
</table>
</form>
精彩评论