现在我在表单中提交帖子数据时遇到问题(我的表单如下所示:
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/
Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur
尝试单击带有变音符号的按钮时出现此错误:syntaxerror,unexpected$end,expectingkeyword_endclick_on'NeueFirmahinzufц╪gen'我正在使用Ruby和Capabara进行测试。##Create_User_spec.rbrequire'acceptance/acceptance_helper'##Feature'CreateUser'feature'CreateUser'do##Scenario'CreateaUser'scenario'CreateaUser'do##Loginintotheservicevisit'url
目前有多个Ruby实现正在开发中。你期待哪个?为什么?您是否在生产中积极使用非MRI实现?一些选项包括:RubyMRI(original1.8branch)YARV(official1.9)JRubyRubiniusIronRuby-Ironruby.netMagLev(感谢Julian)GithublinkMacRuby(感谢DamienPollet) 最佳答案 Maglev.它将拥有多年来已进入主要SmalltalkVM的所有优化的速度优势。此外,它会几乎自动地自动保留所有数据,因此不再需要使用对象关系映射层等。
我是否必须保存对模型集合中单个项目的修改,或者是否有一种方法可以在我保存模型时调用以保存它们。#save似乎没有这样做。例如:irb>rental=#...#=>#irb>rental.dvd#=>#,sale_price:#>irb>rental.dvd.copies+=1#=>21irb>rental.save#=>trueirb>rental.dvd#=>#,sale_price:#>irb>Dvd.find_by_title('TheWomenofSummer')#=>#,sale_price:#>在上面的例子中,租赁的DVD副本似乎没有更新数据库中的副本(注意不同的副本数)。
我目前对连续调用的模拟设置了一些期望:规范:@my_mock=mock("a_mock")@options1={:some=>"option"}@options2={:some_other=>"option"}@first_param=mock("first_param")@my_mock.should_receive(:a_message).with(@first_param,@options1)@my_mock.should_receive(:a_message).with(@first_param,@options2)但是,我得到以下信息:Mock"a_mock"received
嘿,我是rubyonrails的新手,我正在尝试从这个博客运行一个简单的程序,但遇到了很多问题错误。http://goodbadtech.com/2009/05/13/ruby-on-rails-import-csv-data-into-database/无法找出解决方案。这是错误日志。/home/jeevan/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.1/lib/active_support/dependencies.rb:234:in`load':/home/jeevan/csv/config/routes.rb:64:s
classFoodefbar(a,b)...Foo.should_receive(:bar)期望使用任何参数调用bar。Foo.should_receive(:bar).with(:baz,:qux)期望:baz和:qux作为参数传入。如何期望第一个参数等于:baz,而不关心其他参数? 最佳答案 使用anything匹配器:Foo.should_receive(:bar).with(:baz,anything) 关于ruby-如何使用RSpecshould_receive期待一些(但不是
我的javascript代码中有以下函数:addParam(url,param,value){vara=document.createElement('a'),regex=/(?:\?|&|&)+([^=]+)(?:=([^&]*))*/g;varmatch,str=[];a.href=url;param=encodeURIComponent(param);while(match=regex.exec(a.search)){if(param!=match[1]){str.push(match[1]+(match[2]?'='+match[2]:''));}}str.push(p
我真的是JavaScript的新手,我无法找到关于这方面的一些教程。如果有,请告诉我阅读它们。我想做的是将变量从我的PHPController传递到.js文件-我想填充Highcharts变量。我知道我可以发送响应,但我还需要加载一个模板。这是模板:...{%blockbody%}Months//ThisistheChart:{%blockjavascript%}{%endblock%}{%endblock%}.js文件名为month.js$(function(){$('#container').highcharts({chart:{type:'bar'},title:{text:'B
对于某些测试场景,我遇到了针对多个值进行测试的需求,这些值都可以。我想做的事情如下:expect(resultCode).toBeIn([200,409]);当resultCode为200或409时,该规范应该通过。这可能吗?已添加感谢peter和dolarzo指导我创建匹配器。我在使用addMatchers()时遇到了问题。所以,最后我在jasmine.js中添加了以下内容:jasmine.Matchers.prototype.toBeIn=function(expected){for(vari=0;i这给了我一个可行的解决方案。我现在可以根据需要执行toBeIn。(Jasmine1