gpt4 book ai didi

php - Symfony2,Doctrine2 在关联 sth#category 上找到类型为 Doctrine\Common\Collections\ArrayCollection 的实体,但期待 sth

转载 作者:可可西里 更新时间:2023-11-01 13:50:23 25 4
gpt4 key购买 nike

现在我在表单中提交帖子数据时遇到问题(我的表单如下所示:

Task: <input text>
Category: <multiple select category>
DueDate: <date>
<submit>

)提交表单后,我会收到此错误:

Found entity of type Doctrine\Common\Collections\ArrayCollection on association Acme\TaskBundle\Entity\Task#category, but expecting Acme\TaskBundle\Entity\Category

我的来源:

任务对象 Task.php

<?php

namespace Acme\TaskBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity
* @ORM\Table(name="tasks")
*/
class Task
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @ORM\Column(type="string", length=200)
* @Assert\NotBlank(
* message = "Task cannot be empty"
* )
* @Assert\Length(
* min = "3",
* minMessage = "Task is too short"
* )
*/
protected $task;

/**
* @ORM\Column(type="datetime")
* @Assert\NotBlank()
* @Assert\Type("\DateTime")
*/
protected $dueDate;

/**
* @Assert\True(message = "You have to agree")
*/
protected $accepted;

/**
* @ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
*/
protected $category;

/**
* Constructor
*/
public function __construct()
{
$this->category = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}

/**
* Set task
*
* @param string $task
* @return Task
*/
public function setTask($task)
{
$this->task = $task;

return $this;
}

/**
* Get task
*
* @return string
*/
public function getTask()
{
return $this->task;
}

/**
* Set dueDate
*
* @param \DateTime $dueDate
* @return Task
*/
public function setDueDate($dueDate)
{
$this->dueDate = $dueDate;

return $this;
}

/**
* Get dueDate
*
* @return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}

/**
* Add category
*
* @param \Acme\TaskBundle\Entity\Category $category
* @return Task
*/
public function addCategory(\Acme\TaskBundle\Entity\Category $category)
{
$this->category[] = $category;

return $this;
}

/**
* Remove category
*
* @param \Acme\TaskBundle\Entity\Category $category
*/
public function removeCategory(\Acme\TaskBundle\Entity\Category $category)
{
$this->category->removeElement($category);
}

/**
* Get category
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCategory()
{
return $this->category;
}
}

类别对象 Category.php

<?php

namespace Acme\TaskBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity
* @ORM\Table(name="categories")
*/
class Category
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @ORM\Column(type="string", length=200, unique=true)
* @Assert\NotNull(message="Choose a category", groups = {"adding"})
*/
protected $name;

/**
* @ORM\ManyToMany(targetEntity="Task", mappedBy="category")
*/
private $tasks;


public function __toString()
{
return strval($this->name);
}
/**
* Constructor
*/
public function __construct()
{
$this->tasks = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}

/**
* Set name
*
* @param string $name
* @return Category
*/
public function setName($name)
{
$this->name = $name;

return $this;
}

/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}

/**
* Add tasks
*
* @param \Acme\TaskBundle\Entity\Task $tasks
* @return Category
*/
public function addTask(\Acme\TaskBundle\Entity\Task $tasks)
{
$this->tasks[] = $tasks;

return $this;
}

/**
* Remove tasks
*
* @param \Acme\TaskBundle\Entity\Task $tasks
*/
public function removeTask(\Acme\TaskBundle\Entity\Task $tasks)
{
$this->tasks->removeElement($tasks);
}

/**
* Get tasks
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTasks()
{
return $this->tasks;
}
}

任务类型 任务类型.php

<?php

namespace Acme\TaskBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Acme\TaskBundle\Form\Type\Category;

class TaskType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\TaskBundle\Entity\Task',
'cascade_validation' => true,
));
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('task', 'text', array('label' => 'Task'))
->add('dueDate', 'date', array('label' => 'Due Date'))
->add('category', new CategoryType(), array('validation_groups' => array('adding')))
//->add('accepted', 'checkbox')
->add('save', 'submit', array('label' => 'Submit'));
}

public function getName()
{
return 'task';
}
}

类别类型 CategoryType.php

<?php

namespace Acme\TaskBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CategoryType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
));
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'entity', array(
'class' => 'AcmeTaskBundle:Category',
'query_builder' => function($repository) { return $repository->createQueryBuilder('c')->orderBy('c.id', 'ASC'); },
'property' => 'name',
'multiple' => true,
'label' => 'Categories',
));
}

public function getName()
{
return 'category';
}
}

和我的 Controller DefaultController.php:

public function newAction(Request $request)
{
$task = new Task();
$task->setTask('Write name here...');
$task->setDueDate(new \DateTime('tomorrow'));

$form = $this->createForm('task', $task);
$form->handleRequest($request);

if($form->isValid())
{
$this->get('session')->getFlashBag()->add(
'success',
'Task was successfuly created'
);
$em = $this->getDoctrine()->getManager();
/*
$category = $this->getDoctrine()->getManager()->getRepository('AcmeTaskBundle:Category')->findOneByName($form->get('category')->getData());
$task->setCategory($category);
*/
$em->persist($task);
try {
$em->flush();
} catch (\PDOException $e) {
// sth
}

//$nextAction = $form->get('saveAndAdd')->isClicked() ? 'task_new' : 'task_success';

//return $this->redirect($this->generateUrl($nextAction));
}

return $this->render('AcmeTaskBundle:Default:new.html.twig', array('form' => $form->createView()));
}

所以,我在谷歌上查看了这个问题,但是有不同种类的问题。有什么想法吗?

更新完整错误信息:

[2013-09-30 14:43:55] request.CRITICAL: Uncaught PHP Exception Doctrine\ORM\ORMException: "Found entity of type Doctrine\Common\Collections\ArrayCollection on association Acme\TaskBundle\Entity\Task#category, but expecting Acme\TaskBundle\Entity\Category" at /var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 762 {"exception":"[object] (Doctrine\\ORM\\ORMException: Found entity of type Doctrine\\Common\\Collections\\ArrayCollection on association Acme\\TaskBundle\\Entity\\Task#category, but expecting Acme\\TaskBundle\\Entity\\Category at /var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:762)"} []

更新 2

我的 TWIG 模板 new.html.twig

<html>
<head>
<title>Task create</title>
</head>
<body>
{% for flashMessage in app.session.flashbag.get('success') %}
<div style="display: block; padding: 15px; border: 1px solid green; margin: 15px; width: 450px;">
{{ flashMessage }}
</div>
{% endfor %}

{{ form_start(form, {'action': path ('task_new'), 'method': 'POST', 'attr': {'novalidate': 'novalidate' }}) }}
{{ form_errors(form) }}

<div>
{{ form_label(form.task) }}:<br>
{{ form_widget(form.task) }} {{ form_errors(form.task) }}<br>
</div>
<div>
{{ form_label(form.category) }}:<br>
{{ form_widget(form.category) }} {{ form_errors(form.category) }}
</div>
<div>
{{ form_label(form.dueDate) }}:<br>
{{ form_widget(form.dueDate) }} {{ form_errors(form.dueDate) }}<br>
</div>

{{ form_end(form) }}
</body>
</html>

最佳答案

您可以通过更改实体中的 setter 来改进 Controller 代码:

任务中:

public function addCategory(Category $category)
{
if (!$this->categories->contains($category)) {
$this->categories->add($category);
$category->addTask($this); // Fix this
}
}

类别中:

public function addTask(Task $task)
{
if (!this->tasks->contains($task)) {
$this->tasks->add($task);
$task->addCategory($this);
}
}

这将使 ArrayCollection 中的元素保持唯一,这样您就不必在代码中进行检查,并且还会自动设置反面。

关于php - Symfony2,Doctrine2 在关联 sth#category 上找到类型为 Doctrine\Common\Collections\ArrayCollection 的实体,但期待 sth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19079191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com