dongxu0690 2017-11-18 04: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 06: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 el-select光标位置问题
  • ¥15 单片机 TC277 PWM
  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
  • ¥15 雄安新区高光谱数据集的下载网址打不开
  • ¥66 android运行时native和graphics内存详细信息获取
  • ¥15 rk3566 Android11 USB摄像头 微信
  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
  • ¥35 西门子博图v16安装密钥提示CryptAcquireContext MS_DEF_PROV Error of containger opening
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部