Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Zend_Form::getValues() not return expected values outside MVC?

I am using Zend_Form (full library on include_path) but not using MVC. $_POST values are as expected, but $form->getValues() returns null for key that contain correct strings in $_POST. I expected $form->getValues() to return a valid string for 'fullname' key. Here is the form:

class MyForm extends Zend_Form {

    public function init() {
        $this->setName('myform')
            ->setAction($_SERVER['PHP_SELF'])
            ->setMethod('post');

        $fullname = $this->createElement('text', 'fullname')
            ->setLabel('What is your name?');

        $this->addElement($fullname);
        $this->addElement('submit', 'submit');
    }

}

Here is the HTML that is generated for the form:

<form id="myform" name="myform" enctype="application/x-www-form-urlencoded" action="/classes_test/index.php" method="post">
    <dl class="zend_form">
    <dt id="fullname-label">
        <label for="fullname" class="optional">What is your name?</label>
    </dt>
    <dd id="fullname-element">
        <input type="text" name="fullname" id="fullname" value="">
    </dd>
    <dt id="submit-label">&#160;
    </dt>
    <dd id="submit-element">
        <input type="submit" name="submit" id="submit" value="submit">
    </dd>
    </dl>
</form>

Here's the processing:

$request = new Zend_Controller_Request_Http();
$form = new MyForm;
$form->setView(new Zend_View);
if ($request->isPost()) {
    var_dump($_POST);
    $data = $form->getValues();
    var_dump($data);
    if ($form->isValid($request->getPost()) {
        ...
    }
}

Here is a var_dump of $_POST:

array
  'fullname' => string 'My Name' (length=7)
  'submit' => string 'submit' (length=6)

Here is a var_dump of $data:

array
  'fullname' => null

Why is 'fullname' null?

like image 848
Owen Avatar asked Mar 17 '26 18:03

Owen


1 Answers

Zend_Form doesn't access data from $_POST directly, you have to pass the data in. One of the ways this is done is by the isValid() call. So the answer to your question is - fullname is null because there isn't any data in the form object yet.

If you try this instead:

if ($request->isPost()) {
    var_dump($_POST);

    if ($form->isValid($request->getPost()) {
        $data = $form->getValues();
        var_dump($data);
    }
}

you will get the result you are expecting.

like image 78
Tim Fountain Avatar answered Mar 21 '26 11:03

Tim Fountain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!