zendframework 2 Doctrine 2我的帖子表单没有返回值

时间:2014-01-24 15:39:53

标签: forms zend-framework2

我对此感到有点困惑;

我的帖子表单没有填充从返回的帖子值收到的值;我怀疑问题是由我的jobsort类值中的 getJobId()引起的;

以下是我的表格:

public function jobSortAction()
    {

         $form = new CreateJobSortForm($this->getEntityManager());

         $jobSort = new JobSort();

         $form->setInputFilter($jobSort->getInputFilter());

         $id= 11;
         $jobSort->setId($id);

         $form->bind($jobSort);

         if ($this->request->isPost()) {
  //$post     = $this->request->getPost();      
             $form->setData($this->request->getPost());
  //var_dump($post);
  //var_dump($jobSort);               

             if ($form->isValid()) {


                  $this->getEntityManager()->persist($jobSort);
                 $this->getEntityManager()->flush();
             }
         }
         return array('form' => $form);
    } 

下面是'return post values'和Jobsort()对象的var_dumped值。您将注意到返回的帖子值包含Id和JobId

的值
object(Zend\Stdlib\Parameters)[168]
  public 'JobSort' => 
    array (size=2)
      'jobId' => string '5' (length=1)
      'id' => string '11' (length=2)
  public 'submit' => string 'Submit' (length=6)

object(Workers\Entity\JobSort)[394]
  protected 'inputFilter' => null
  protected 'id' => int 11
  protected 'jobId' => null
  protected 'workerservicelist' => null

然而,当我填充值时,它似乎没有记录jobId的值

下面是我的jobort实体类:

class JobSort  
{
   protected $inputFilter;

    /**
     * @ORM\Id
     * 
     * @ORM\Column(name="user_id", type="integer")
     */
    protected $id;

    /**
     * @ORM\Column(name="jobId", type="integer")
     */
    protected $jobId;


 public function setId($id)
    {
        return $this->id = $id;
    }


    public function getId()
    {
        return $this->id;
    }

    public function setJobId($jobId)
    {
        return $this->jobId = $jobId;
    }

    public function getJobId( )
    {
        return $this->jobId;
    }

是否有任何建议或建议我需要做些什么来找出未填充值的原因

热烈的问候

Andreea

顺便说一下; 当我将CLASS作业的Id设置为  @ORM \ GeneratedValue(策略= “AUTO”)

当我把它取出并将其设置为手动

时问题就开始了

再次问好

这是我的表格:

这是我收到的错误消息;

An exception occurred while executing 'INSERT INTO worker_main_jobsort (user_id, jobId) VALUES (?, ?)' with params [11, null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'jobId' cannot be null

这是我的表单:

use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
use Workers\Form\Fieldset\JobSortFieldset;

class CreateJobSortForm extends Form
{
    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('create-Job-post-form');

        // The form will hydrate an object of type "BlogPost"
        $this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'));

        // Add the user fieldset, and set it as the base fieldset
        $JobSortFieldset = new JobSortFieldset($objectManager);
        $JobSortFieldset->setUseAsBaseFieldset(true);
        $this->add($JobSortFieldset);


        // Optionally set your validation group here


        // … add CSRF and submit elements …

        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Submit',
                'id' => 'submitbutton',
            ),
        )); 

        // Optionally set your validation group here
    }
}

,这是字段集类:

class JobSortFieldset extends Fieldset 
{
    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('JobSort');
        $id= 10;
        $this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'))
             ->setObject(new JobSort());


        }
}

此添加是对rafaame解决方案的回应;

我按照建议修改了我的表格;但它仍然无法正常工作。我认为现在的问题是Rafaame解决方案是关于zendDB 保存方法,但我使用的是doctrine persis ** t和** flush 方法。因此我得到以下错误信息;

调用未定义的方法Workers \ Entity \ JobSort :: save()

以下是我的修改表格:

public function jobSortAction()
    {
         $form = new CreateJobSortForm($this->getEntityManager() );

         $jobSort = new JobSort();

         if($this->request->isPost())
        {
             $form->setData($this->request->getPost());

             if ($form->isValid())
             {
                $entity = $form->getData();
                $model = new JobSort();
                $model->save($entity);

               // $this->getEntityManager()->persist( $model);
             //   $this->getEntityManager()->flush();
             }
         }
         return array('form' => $form);
    } 

在回答关于我遇到的问题的Rafaame问题时,我现在收到的信息是: **

  

EntityManager#persist()期望参数1是实体对象,   数组给出。

**

以下是我的功能:

public function jobSortAction()
    {
         $serviceLocator = $this->getServiceLocator();
         $objectManager = $this->getEntityManager();

         $form = new CreateJobSortForm($this->getEntityManager());

         if ($this->request->isPost())
         {
            $form->setData($this->request->getPost());

             if ($form->isValid()) {
                 $entity = $form->getData();

              $model = new JobSort($objectManager, $serviceLocator);
              $model->getEntityManager()->persist($entity);
              $model->getEntityManager()->flush();

             }
         }
        return array('form' => $form);
     } 

我的表格;即应设置水化器

namespace Workers\Form;

use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
use Workers\Form\Fieldset\JobSortFieldset;

class CreateJobSortForm extends Form
{
    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('JobSort');

        // The form will hydrate an object of type "BlogPost"
        $this->setHydrator(new DoctrineHydrator($objectManager, 'Workers\Entity\JobSort'));

        // Add the user fieldset, and set it as the base fieldset
        $JobSortFieldset = new JobSortFieldset($objectManager);
        $JobSortFieldset->setUseAsBaseFieldset(true);
        $this->add($JobSortFieldset);

1 个答案:

答案 0 :(得分:1)

如果您检查代码,则表示您正在创建一个JobSort实体,仅设置其 id 并将其绑定到表单:

$jobSort = new JobSort();
$jobSort->setId($id);
$form->bind($jobSort);

之后,您正在转储$ jobSort和$ this-> request-> getPost()。因此,显然,您在POST数据中获取jobId但在实体中没有(在将表单绑定到表单之前未设置实体的jobId)。您的实体代码没有任何问题。

解决方案:不要将任何内容绑定到表单。在编辑操作的情况下,您应该只将实体绑定到表单,从数据库中获取实体并希望使用其值填充表单。

添加操作的示例:

public function addAction()
{

    $serviceLocator = $this->getServiceLocator();
    $objectManager = $this->getObjectManager();

    $form = new Form\EmailCampaign\Add($serviceLocator, $objectManager);

    if($this->request instanceof HttpRequest && $this->request->isPost())
    {

        $form->setData($this->request->getPost());

        if($form->isValid())
        {

            $entity = $form->getData();

            //If you want to modify a property of the entity (but remember that it's not recommended to do it here, do it in the model instead).
            //$entity->setJobId(11);

            $model = new Model\EmailCampaign($serviceLocator, $objectManager);
            $model->save($entity);

            if($entity->getId())
            {

                $this->flashMessenger()->addSuccessMessage('Email campaign successfully added to the database.');
                return $this->redirect()->toRoute('admin/wildcard', ['controller' => 'email-campaign', 'action' => 'edit', 'id' => $entity->getId()]);

            }
            else
            {

                $this->flashMessenger()->addErrorMessage('There was an error adding the email campaign to the database. Contact the administrator.');

            }

        }

    }

    return new ViewModel
    ([

        'form' => $form,

    ]);

}

编辑操作的示例:

public function editAction()
{

    $serviceLocator = $this->getServiceLocator();
    $objectManager = $this->getObjectManager();

    $form = new Form\EmailCampaign\Edit($serviceLocator, $objectManager);

    $id = $this->getEvent()->getRouteMatch()->getParam('id');
    $entity = $objectManager
                ->getRepository('Application\Entity\EmailCampaign')
                ->findOneBy(['id' => $id]);

    if($entity)
    {

        $form->bind($entity);

        if($this->request instanceof HttpRequest && $this->request->isPost())
        {

            $form->setData($this->request->getPost());

            if($form->isValid())
            {

                //If you want to modify a property of the entity (but remember that it's not recommended to do it here, do it in the model instead).
                //$entity->setJobId(11);

                $model = new Model\EmailCampaign($serviceLocator, $objectManager);
                $model->save($entity);

                $this->flashMessenger()->addSuccessMessage('Email campaign successfully saved to the database.');

            }

        }

    }
    else
    {

        $this->flashMessenger()->addErrorMessage('A email campaign with this ID was not found in the database.');
        return $this->redirect()->toRoute('admin', ['controller' => 'email-campaign']);

    }

    return new ViewModel
    ([

        'form' => $form,
        'entity' => $entity,

    ]);

}

希望这有帮助。

编辑:

我提供的是如何使用Doctrine 2 + ZF2处理表单和实体的示例。

你必须记住的是,Doctrine不适用于模型的概念,它只是理解实体。我在我的应用程序中使用的模型是MVC(模型 - 视图 - 控制器)设计模式(ZF2使用)的概念,我决定将实体管理器调用(持久化和刷新)包装在我的模型的方法中,我将 save()命名(如果实体在保存到数据库之前需要一些特殊处理,并且因为直接在控制器中使用实体管理器不是一个好习惯 - 请参阅此幻灯片Marcos Pivetta演讲http://ocramius.github.io/presentations/doctrine2-zf2-introduction/#/66)。

您可能误解的另一件事是,当您将 $ form-> getData()添加到具有DoctrineObject水合器的表单时,它将返回实体对象,而不是带有数据的数组(如果它没有水化器,则会发生这种情况)。因此,您不需要在执行 $ form-> getData()之后创建实体,如果这样做,则此创建的实体将不会提供表单提供的任何信息。

您的代码现在应该可以使用:

public function jobSortAction()
{
     $serviceLocator = $this->getServiceLocator();
     $entityManager = $this->getEntityManager();

     $form = new CreateJobSortForm($entityManager);

     if ($this->request->isPost())
     {

        $form->setData($this->request->getPost());

         if ($form->isValid()) {

             //I'm considering you are setting the DoctrineObject hydrator to your form,
             //so here we will get the entity object already filled with the form data that came through POST.
             $entity = $form->getData();

             //Again, if you need special treatment to any data of your entity,
             //you should do it here (well, I do it inside my model's save() method).
             //$entity->setJobId(11);

             $entityManager->persist($entity);
             $entityManager->flush();

         }

     }

    return array('form' => $form);

 }