gpt4 book ai didi

php - symfony 一对多表单

转载 作者:行者123 更新时间:2023-11-28 23:19:32 24 4
gpt4 key购买 nike

我正在使用 symfony 构建如下函数:我有产品和运输方式。一个产品可以有多个 ShippingWays,一个 ShippingWay 只能匹配一个产品。

产品实体:

/**
* @ORM\OneToMany(targetEntity="ShippingWay",mappedBy="product")
*/
private $shippingWays;

ShippingWay 实体:

/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="shippingWays")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
**/
private $product;

然后我构建了 ProductType 和 ShippingWayType。

产品类型

->add('shippingWays', EntityType::class, array(
'label' => ' Shipping Ways',
'translation_domain' => 'forms',
'class' => 'CoreBundle:ShippingWay',
'choice_label' => 'name',
'multiple' => true,
'required' => false,
))

产品 Controller

 /**
* @Route("/admin/product/new", name="admin_product_new")
* @Template()
*/
public function newAction(Request $request)
{
$product = new Product();
$shippingWay= new ShippingWay();
$form = $this->createForm(ProductType::class, $product);
$shippingForm = $this->createForm(ShippingWayType::class, $shippingWay);

if ($request->isMethod('POST')) {
$form->handleRequest($request);

if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($product );
$em->flush();
return $this->redirect($this->generateUrl('admin_product'));
}
}
return(array('form' => $form->createView(),'users'=>$users,'shippingForm '=>$shippingForm ->createView()));
}
  • 我想在产品页面中添加/编辑运输方式。
  • 如果没有合适的运输方式,那么我必须在产品页面中创建一个新的运输方式。像这样:

enter image description here

目前我有两个问题:

  • 如何像往常一样在产品页面中使用表格管理运输方式?是否有一种通用的方法来处理 OneToMany 和 ManyToOne 关系下的表单?
  • 我在添加产品 X 时选择运输方式 A,然后我可以在添加产品 Y 时像以前一样选择运输方式 A。我发现运输方式 A 的 procuct_id 始终为 Null。

有人可以给我一些建议和引用吗?非常感谢。

最佳答案

对于您的第一个问题:在您的 ProductType 中,您不应将 EntityType 用于 ShippingWay,因为它仅显示与 ShippingWay 实体相关的现有条目列表。

如果要添加/编辑,最好使用 CollectionType,如下所示:How to Embed a Collection on a Symfony Form

在您的情况下,您的ProductType 将是:

->add('shippingWays', CollectionType::class, array(
'label' => ' Shipping Ways',
'translation_domain' => 'forms',
'entry_type => 'CoreBundle:ShippingWay',
'choice_label' => 'name',
'allow_add' => true,
'allow_delete' => true
))

关于php - symfony 一对多表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438077/

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