简体   繁体   中英

Zend Framework 2, form

I'm trying to create a form for editing. Сontroller:

$someValue = $this->someMapper->someMethod()
(someMethod returns Hydrator object)

$form->bind($someValue);

But it`s not working. Values are not added to Form. If I add to Controller this:

$form->setData($this->someMapper->extract($someValue);

That is all to the form normally added. I do not understand what the problem is.

Hydrator Object:

object(Admin\\Entity\\Article)#331 (13) { ["id":protected]=> string(2) "16" ["heading":protected]=> string(85) "fsdgsdgsdgsdg" ["subHeading":protected]=> string(3) "fdddgdgdg" ["imgDescription":protected]=> string(4) "jghj" ["text":protected]=> string(15) " ghjghj

" ["category":protected]=> string(4) "category" ["commentation":protected]=> string(1) "0" ["importance":protected]=> string(1) "0" ["path":protected]=> string(48) "fgdfgdgdg-fgdfhwt-gf" ["comments":protected]=> NULL ["views":protected]=> NULL ["date":protected]=> string(19) "2016-06-06 11:23:05" ["img":protected]=> string(11) "1492546.jpg" }

View.phtml

<?php
 $form = $this->form;

 $form->prepare();

 $form->get('submit')->setValue('Update Post');

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

 echo $this->formCollection($form);

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

You need to create an object Entity with properties like this:

<?php
class Article
{
    private $id; /* $_POST['id] */
    private $headline; /* $_POST['headline']*/
    private $author; /* $_POST['author']*/
    private $comments; /* $_POST['comments']*/
}

Properties in this object must be equal with POST variables. And you can bind this entity to a form and set a hydrator.

Or you can use an object ArrayObject instead Entity .

$request = $this->getRequest(); /* An request object in Controller */

$form->bind(new Article()); /* bind entity */
// $form->bind(new ArrayObject()); /* or bind ArrayObject */
$form->setHydrator(new ObjectProperty()); /* Add a data to properties of an Entity */
$form->setData($request->getPost()); /* Set a POST data to form */

After validation you can get Entity with valid data from a form.

if ($form->isValid()) {
    $entity = $form->getObject(); /* Entity or ArrayObject */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM