dongxu0690 2017-11-18 12:35
浏览 72
已采纳

Symfony3表单复选框保存错误

I tried to look up on Google but didn't find anyone with such a problem. I think I did everything like the documentation guides but I guess I'm missing something

So I have a form with checkbox like this:

    $builder->add(
        'productTypes',
        EntityType::class,
        array(
            'label'        => 'Available for products',
            'class'        => 'ShopBundle:ProductType',
            'choice_label' => 'name',
            'multiple'     => true,
            'expanded'     => true,
            'by_reference' => false,
        )
    );

When I'm editing everything goes smooth, I can edit existing entry and check or uncheck this checkbox, it saves properly, but when I try to add new Object I get error:

PHP Fatal error: Call to a member function add() on null in C:\xampp\htdocs\uniacar-sf\src\ShopBundle\Entity\ProductAttribute.php on line 188

This is my controller action:

public function editAction(Request $request, $id = null)
{
    $this->setMenuTab('cars', 'admin');
    $productTypes = new ArrayCollection();

    if (!empty($id)) {
        $attribute = $this->getRepo(ProductAttribute::class)->find($id);
        $this->setTitle('admin.cars.attributes.edit');

        foreach ($attribute->getProductTypes() as $value) {
            $productTypes->add($value);
        }
    } else {
        $attribute = new ProductAttribute();
        $this->setTitle('admin.cars.attributes.new');
    }

    $form = $this->createForm(ProductAttributeForm::class, $attribute);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $attribute = $form->getData();

        foreach ($productTypes as $productType) {
            if (false === $attribute->getProductTypes()->contains($productType)) {
                $productType->getAttributes()->removeElement($attribute);
                $this->db()->persist($productType);
            }
        }

        $this->db()->persist($attribute);
        $this->db()->flush();

        return $this->redirectToRoute('carAdmin', array('tab' => 'attributes'));
    }

    $this->setVariables(
        array(
            'form'      => $form->createView(),
            'attribute' => $attribute,
        )
    );

    return $this->response();
}

$this->db() is my shortcut for $this->getDoctrine()->getManager()

And this is definition part of ProductAttribute that relates to ProductType:

/**
 * Constructor
 */
public function __construct() {
    $this->productTypes = new ArrayCollection();
}

/**
 * Many Attributes have Many ProductTypes
 * @ORM\ManyToMany(targetEntity="ProductType", mappedBy="attributes", cascade={"persist"})
 */
private $productTypes;

/**
 * @param ProductType $productType
 */
public function addProductType(ProductType $productType)
{
    $this->productTypes->add($productType);
    $productType->addProductAttribute($this);
}

/**
 * @param ProductType $productType
 */
public function removeProductType(ProductType $productType)
{
    $this->productTypes->removeElement($productType);
}

Also there is part of ProductType Entity that relates to ProductAttribute:

/**
 * Constructor
 */
public function __construct() {
    $this->attributes = new ArrayCollection();
}

/**
 * Many ProductTypes have Many Attributes
 * @ORM\ManyToMany(targetEntity="ProductAttribute", inversedBy="productTypes")
 * @ORM\JoinTable(name="product_type_to_attribute")
 */
private $attributes;


/**
 * @param ProductAttribute $attribute
 */
public function addProductAttribute(ProductAttribute $attribute)
{
    if (!$this->attributes->contains($attribute)) {
        $this->attributes->add($attribute);
    }
}

public function removeProductAttribute(ProductAttribute $attribute)
{
    $this->attributes->removeElement($attribute);
}

I tried to follow Symfony Embed Form Tutorial (How to Embed a Collection of Forms) I know that in this case there is no embeded collection (I have another field in this Entity, that is embeded collection of forms and it works just fine) but from what I understand relations are the same in this case, it's many to many so I have to tell the Symfony how to treat relations, add and remove objects. I dumped data that comes in POST but it's the same as for edition - productType is there. Any ideas why do I get this error?

It fires in ProductAttribute Entity in the line $this->productTypes->add($productType);

EDIT: I updated the controller code, I messed up the logic about unlinking ProductType from ProductAttribute. But it doesn't have any impact on the problem, still the same 500 error when I try to save new object.

EDIT2: I can't get stack trace from Symfony because I get ordinary browser 500 error (probably because it's Fatal Error, I found it in apache logs). The line in controller which creates error is $form->handleRequest($request);.

  • 写回答

2条回答 默认 最新

  • doutuo1908 2017-12-02 14:03
    关注

    So, I haven't found solution to the problem but I solved it somehow by fixing file structure of my project (moved bundle's Resources from general Resources folder to Bundle's Resources folder). I have no idea why this fixed the issue and what is even the connection between working but not proper folder structure and submitting forms but now it works, so I will mark the question as answered.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下
  • ¥100 单片机hardfaulr
  • ¥20 手机截图相片分辨率降低一半
  • ¥50 求一段sql语句,遇到小难题了,可以50米解决
  • ¥15 速求,对多种商品的购买力优化问题(用遗传算法、枚举法、粒子群算法、模拟退火算法等方法求解)
  • ¥100 速求!商品购买力最优化问题(用遗传算法求解,给出python代码)
  • ¥15 虚拟机检测,可以是封装好的DLL,可付费