在Symfony2中填充实体的表单数据

时间:2015-08-08 16:57:45

标签: php mysql symfony

我有一个基本上呈现表单的操作,如果ID为空,我希望它是一个新表单,如果ID与数据库中的PK匹配,则需要一个编辑表单。显然我的逻辑是错误的,因为每一次都会渲染一个新表单。

public function editGlobalFirewallFilter(Request $request, Entities\GlobalFirewallFilter $firewall_rule = null) {
n
    // Check if we have a valid rule. If not create a new blank one and associate our account id
    // if( ! $firewall_rule ) {
    //     $results = $this->getDoctrine()->getRepository('bundle:GlobalFirewallFilter');
    //     $rules = $results->findAll();
    //     $firewall_rule = new Entities\GlobalFirewallFilter();
    // }
    $firewall_rule = new Entities\GlobalFirewallFilter();

    // Generate our form
    $form = $this->createForm(new SAForms\GlobalFirewallRuleType(), $firewall_rule);

    $form->handleRequest($request);

    if($form->isValid()) {

        // Save our firewall rule
        $em = $this->getDoctrine()->getManager();
        $em->persist($firewall_rule);
        $em->flush();

        return $this->redirect($this->generateUrl('_dashboard__global_firewall'));
    }


        return array(
        'title'         => $firewall_rule->getFirewallFilterId() ? 'Edit Rule' : 'New Rule',
        'form'          => $form->createView(),
    );
}

2 个答案:

答案 0 :(得分:0)

您应该以正确的方式使用form generator command

基于Doctrine实体生成CRUD控制器

http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html 使用此命令:

php app/console generate:doctrine:crud

我会根据您的具体情况,updateActionnewActioneditAction生成您所需的所有标准操作的控制器骨架。

答案 1 :(得分:0)

我不太确定为什么resultsrules - 你不能使用它们。我认为这段代码可以解决问题。

public function editGlobalFirewallFilter(Request $request, Entities\GlobalFirewallFilter $firewall_rule = null) {

    // Check if we have a valid rule. If not create a new blank one and associate our account id
    $firewall_rule = $firewall_rule ?: new Entities\GlobalFirewallFilter();

    // Generate our form
    $form = $this->createForm(new SAForms\GlobalFirewallRuleType(), $firewall_rule);

    $form->handleRequest($request);

    if($form->isValid()) {

        // Save our firewall rule
        $em = $this->getDoctrine()->getManager();
        $em->persist($firewall_rule);
        $em->flush();

        return $this->redirect($this->generateUrl('_dashboard__global_firewall'));
    }


    return array(
        'title'         => $firewall_rule->getFirewallFilterId() ? 'Edit Rule' : 'New Rule',
        'form'          => $form->createView(),
    );
}

P.S。可悲的是我还没有发表评论..你可以在使用这个功能时提供控制器动作吗?