5

我有复选框,我想找出带有选中复选框的项目并仅将它们发送到数据库。所以我做了这个:

class NotNeededFieldsSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_BIND => 'preBindData');
    }

    public function preBindData(FormEvent $event)
    {    
        $data = $event->getData();

        $count = count($data['items']);

        for ($i=0; $i < $count; $i++){
             if (!array_key_exists('enabled', $data['items'][$i])){   
                unset($data['items'][$i]);               
             } 
        }       

        $event->setData($data);

    }
}

当我测试看到 $event->getData 正是我想要的。

在控制器中:

 $form = $this->formFactory->create(new ItemType(), $item);

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

                    $this->em->persist($item);
                    $this->em->flush();
                }
        }

        return $this->redirect($this->router->generate('home'));

问题是数据库中仍然检查和未检查的项目:(

任何想法为什么以及如何解决这个问题?首先十分感谢!:)

4

1 回答 1

0

由于复选框实际上是一个集合,也许您应该参考文档的这一部分:http: //symfony.com/doc/current/cookbook/form/form_collections.html#allowing-tags-to-be-removed

特别是“原则:确保数据库持久性”部分。您必须手动删除仍存储在数据库中但不再存储在表单中的实体

        // filter $originalTags to contain tags no longer present
    foreach ($task->getTags() as $tag) {
        foreach ($originalTags as $key => $toDel) {
            if ($toDel->getId() === $tag->getId()) {
                unset($originalTags[$key]);
            }
        }
    }

    // remove the relationship between the tag and the Task
    foreach ($originalTags as $tag) {
        // remove the Task from the Tag
        $tag->getTasks()->removeElement($task);

        // if it were a ManyToOne relationship, remove the relationship like this
        // $tag->setTask(null);

        $em->persist($tag);

        // if you wanted to delete the Tag entirely, you can also do that
        // $em->remove($tag);
    }
于 2013-10-10T23:25:30.533 回答