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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛