Form doesn't have access to its values. Is this normal?
This is the first time I notice this and it's surprised me a bit.
I have a zend_form with a simple text element.
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name');
$this->addElement($name);
The strange thing is that when I submit the form and try to read the value in the form itself (I'm doing some debugging there not in the controlle开发者_开发问答r), $name->getValue()
doesn't work but the direct $_POST works.
echo $name->getValue(); //gives blank
echo $_POST['name']; //gives the right value
Is this normal? How does the form not have its values? I thought it's better to read them with $field->getValue() than to access the $_POST values directly.
The second question is, to read the value in the form, is there a better way than accessing directly from $_POST?
You need to pass the data explicitly to the form, because ZF has no idea where to get it from:
if ($form->isValid($_POST)) { // access values }
or
if ($form->isValid($request->getPost())) { // access values }
No. Stick to using $_POST
and $_GET
. Honestly I don't see why you're using Zend to create and fetch data from a form, when it's much easier to do this with straight PHP.
<?php if( !isset( $_POST['name'] ) ): ?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<label for="name">Name:</label> <input type="text" name="name" id="name" />
</form>
<?php else: ?>
Value = <?= $_POST['name'] ?>
<?php endif; ?>
I guess it's all in your style of coding. I would prefer the above, but if you want to separate logic from HTML, then Zend is certainly an option.
精彩评论