【发布时间】:2014-07-28 20:51:37
【问题描述】:
当我尝试在数据库中创建一个新的car 时,下面的示例工作正常。如果我在网络表单中留下brands 选择框空白,我会在提交后收到“The Brand field is required”错误,这是完全正常且符合预期的。
问题:
如果我在尝试更新选定记录时重复与上述完全相同的步骤,在提交后我仍然会收到“需要品牌字段”错误,而不是收到“@987654323 @"
任何原因或任何解决方案?
汽车更新控制器(不起作用)
private function getForm($car, $id)
{
return $this->createForm(new CarsType(), $car,
array('action' => $this->generateUrl('cars_independent_update_process',
array('id' => $id))));
}
public function processAction(Request $request, $id)
{
$repo = $this->getDoctrine()->getRepository('CarBrandBundle:Cars');
$car = $repo->findOneBy(array('id' => $id));
if (! $car)
{
return new Response('There is no such car in database');
}
$form = $this->getForm($car, $id);
$form->handleRequest($request);
if ($form->isValid() !== true)
{
return $this->render('CarBrandBundle:Independent:cars_update.html.twig',
array('page' => 'Cars Update Independent', 'form' => $form->createView()));
}
exit('FINE');
}
汽车创建控制器(工作正常)
class CarsCreateController extends Controller
{
private function getForm()
{
return $this->createForm(new CarsType(), new Cars(),
array('action' => $this->generateUrl('cars_independent_create_process')));
}
public function processAction(Request $request)
{
$form = $this->getForm();
$form->handleRequest($request);
if ($form->isValid() !== true)
{
return $this->render('CarBrandBundle:Independent:cars_update.html.twig',
array('page' => 'Cars Update Independent', 'form' => $form->createView()));
}
exit('FINE');
}
实体
class Cars
{
/**
* @ORM\ManyToOne(targetEntity="Brands", inversedBy="cars")
* @ORM\JoinColumn(name="brands_id", referencedColumnName="id", nullable=false)
* @Assert\NotBlank(message="The Brand field is required.")
*/
protected $brands;
/**
* @param \Car\BrandBundle\Entity\Brands $brands
*/
public function setBrands(\Car\BrandBundle\Entity\Brands $brands)
{
$this->brands = $brands;
return $this;
}
/**
* @return \Car\BrandBundle\Entity\Brands
*/
public function getBrands()
{
return $this->brands;
}
}
表格类型
class CarsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['action'])
->setMethod('POST')
->add('brands', 'entity',
array(
'error_bubbling' => true,
'class' => 'CarBrandBundle:Brands',
'property' => 'name',
'multiple' => false,
'expanded' => false,
'empty_value' => '',
'query_builder' => function (EntityRepository $repo)
{
return $repo->createQueryBuilder('b')
->orderBy('b.name', 'ASC');
}
))
->add('model', 'text', array('label' => 'Model', 'error_bubbling' => true))
->add('year', 'date', array('label' => 'Year', 'error_bubbling' => true))
->add('button', 'submit', array('label' => 'Submit'))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array('data_class' => 'Car\BrandBundle\Entity\Cars'));
}
public function getName()
{
return 'cars';
}
}
【问题讨论】:
标签: php symfony orm doctrine-orm