2016-07-26 72 views
0

有一种表单可以创建Chain实体。Symfony2:表单未创建

class ChainType extends AbstractType 
{ 
    /** 
    * @param FormBuilderInterface $builder 
    * @param array $options 
    */ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name', TextType::class, array('label' => 'Company name')) 
      ->add('logoImageURL', TextType::class, array('label' => 'Company logo')); 
    } 

    /** 
    * @param OptionsResolver $resolver 
    */ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'CoreBundle\Entity\Chain' 
     )); 
    } 
} 

这里是一个newAction创建表单和保存实体

/** 
* Creates a new Chain entity. 
* 
* @Route("/new", name="chain_new") 
*/ 
public function newAction(Request $request) 
{ 
    $chain = new Chain(); 
    $form = $this->createForm(ChainType::class, $chain); 

    $form->handleRequest($request); 
    if ($form->isSubmitted() && $form->isValid()) { 
     $em = $this->getDoctrine()->getManager(); 
     $em->persist($chain); 
     $em->flush(); 

     return $this->redirectToRoute('chain_show'); 
    } 

    return $this->render(
     'AdminBundle:ChainPanel:new.html.twig', 
     array('form' => $form->createView()) 
    ); 
} 

下面是一个按钮来创建表单

<button type="button" class="btn btn-primary"> 
    <a href="{{ path('chain_new') }}"> 
     Add Chain 
    </a> 
</button> 

问题

当我点击“添加链'按钮表单没有创建,我只是重定向t o'chain_show'路线。我的代码有什么问题?

更新 - 我的解决方案

在控制器我把newAction的showAction之前。这个固定的问题。然而我找不到解释

回答

1

我不确定你想做什么,但是如果你想用ChainType表单创建一个页面,你还应该为该页面创建一个模板,像这样:

..... 

{% block YOUR_BLOCK %} 
    {{ form(form) }} 
{% endblock %} 

...... 

和,也不必包a标签与标签button,只是给class="btn btn-primary"a标签。

0

你的问题是你正在使用保存新链对象的变量。请参阅我下面的例子,这应该解决您的问题...

public function newAction(Request $request) 
{ 
    $chain = new Chain(); 
    $form = $this->createForm(ChainType::class, $chain); 

    $form->handleRequest($request); 
    if ($form->isSubmitted() && $form->isValid()) { 
     $chain = $form->getData(); 

     $em = $this->getDoctrine()->getManager(); 
     $em->persist($chain); 
     $em->flush(); 

     return $this->redirectToRoute('chain_show'); 
    } 

    return $this->render(
     'AdminBundle:ChainPanel:new.html.twig', 
     array('form' => $form->createView()) 
    ); 
} 

你也创造了不正确的提交按钮。为了测试它的所有工作正常,只需使用(在您的.twig.html文件中):

{{ form(form) }} 
0

虽然有趣,但我猜HTML的链接是错误的。您不应该将button包装到锚标签。有些浏览器不支持它。而是如下用途:

<a href="{{ path('chain_new') }}" class="btn btn-primary"> 
    Add Chain 
</a> 

如果这不能解决您的问题,你看到正在创建一个新的实体,当你点击链接?

0

在控制器中,我在showAction之前放置了newAction。这个固定的问题。但是我找不到解释