i am getting started with zend framework.I have encountered this problem with forms. when opening localhost/item/create in browser, only the hello is shown, form isn't rendered.
what i did:
i created a controller in my project with zf.sh create controller item
then zf.sh create action create item
.
Inside library folder, created App->forms->ItemEditor.php
<?php
class App_forms_ItemEditor extends Zend_Form
{
public function __construct()
{
$email = $this->createElement('text', 'email');
$email->setLabel('Your email address:');
$email->setRequired(TRUE);
$email->addValidator(new Zend_Validate_EmailAddress());
$email->addFilters(array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower()
));
$email->setAttrib('size', 40);
$this->addElement($email);
}
}
declared its namespace in application.ini file
autoloaderNamespaces[] = "App_"
Inside views->scripts->item->create.phtml did this:
hello
<?php
echo $this->form->render();
?>
and then inside ItemController.php :
public function createAction()
{
$this->view-&g开发者_运维百科t;form=new App_forms_ItemEditor();
}
only the hello is shown in the browser, rest of the form isnt shown. can anyone point out what i'm doing wrong. thanks
I think the reason is that you overwriting Zend_Form::__constructor(). Forms that extend Zend_Form should use init()
function to initialize their elements, not __constructor()
.
The best place to create your form elements is to override the init()
method, eg
class App_forms_ItemEditor extends Zend_Form
{
public function init()
{
$email = $this->createElement('text', 'email');
$email->setLabel('Your email address:');
$email->setRequired(TRUE);
$email->addValidator(new Zend_Validate_EmailAddress());
$email->addFilters(array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower()
));
$email->setAttrib('size', 40);
$this->addElement($email);
}
}
If you hijack Zend_Form::__construct()
, you should at least accept the same arguments and pass them on using parent::__construct()
Also, I'm a little unsure about the lowercase "f" in your class name's "form" part. From memory, the module autoloader translates a "Form" name part to a "forms" directory in your module.
I do note however that you're not using the module autoloader (or at least, you haven't shown that you are)
Regarding module autoloaders...
The bootstrap process registers a module autoloader using the configured appnamespace
value (usually "Application") with base path "application".
A module autoloader automatically registers some class name / path mappings for classes starting with the configured namespace (eg "Application_"). This includes forms.
Basically, it means you can create forms under application/forms/MyForm.php
with classname Application_Form_MyForm
and the autoloader will find it.
Open up `Zend_Application_Module_Autoloader" to see the full list.
精彩评论