2016-04-06 120 views
0

在Symfony2中我可以打電話給Symfony3的setAction在FormType

// MyController.php 
$formType = new MyFormType($this->container); 
$form = $this->createForm($formType); 

// MyFormType.php 
protected $container; 

public function __construct(ContainerInterface $container) 
{ 
    $this->container = $container; 
} 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->setAction($this 
      ->container 
      ->get('router') 
      ->generate('myAction') 
     ); 
    // ... 
    } 
} 

在symfony3我應該通過stringcreateForm方法,所以我不能夠控制或路由器通過向MyFormType

我試着將FormType定義爲服務,但不會改變行爲。

如何設置MyFormType(不在MyController)中的操作?

+0

顯示如何將表單類型定義爲服務。你應該可以在沒有問題的情況下注入路由器。 – Cerad

+0

是的,我注入路由器沒有問題,但在我看來,symfony創建窗體類型爲「新的FormType」,根本不調用服務(當使用'createForm'方法時)。所以我在FormType中的構造函數被調用時沒有任何參數。 – Eddie

+0

不是。如果您將表單類型正確定義爲服務,那麼createForm功能會將其從容器中拉出。仔細檢查你的工作。確保您的服務定義正在使用container:debug進行加載。我保證它會起作用。 – Cerad

回答

1

第一,我發現目前唯一的選擇是:

// MyController.php 
$this->createForm(MyFormType::class, null, ['router' => $this->get('router')]); 

// MyFormType.php 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->setAction($options['router']->generate('myAction')); 
    // ... 
} 

public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults([ 
     'router' => null, 
     // ... 
    ]); 
} 

但這種方法似乎有點有點難看我。

0

你應該定義形式的服務,如:

// src/AppBundle/Form/Type/MyFormType.php 
namespace AppBundle\Form\Type; 

use Symfony\Bundle\FrameworkBundle\Routing\Router; 
use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\Form\Extension\Core\Type\SubmitType; 

class MyFormType extends AbstractType 
{ 
    private $router; 

    public function __construct(Router $router) 
    { 
     $this->router = $router; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     // You can now use myService. 
     $builder 
      ->setAction(
       $this->router->generate('myAction') 
      ) 
      ->add('myInput') 
      ->add('save', SubmitType::class) 
     ; 
    } 
} 
# app/config/services.yml 
services: 
    app.form.type.my_form_type: 
     class: AppBundle\Form\Type\MyFormType 
     arguments: [ "@router" ] 
     tags: 
      - { name: form.type } 

在您的控制器,那麼你只需要調用$this->createForm(MyFormType::class);

+0

我嘗試了你寫的東西,我不會在這裏發佈所有的類,因爲代碼太多。在symfony2(一段時間之前),我用這種方式定義FormTypes(services.yml),它的工作,但在sf3我沒有在MyFormType構造函數:( – Eddie

1

至少在Symfony2中(2.7測試),你可以這樣做:

//MyController.php 
$this->createForm(MyFormType::class, null, array('action' => $this->generateUrl('my_acton_name'))); 

使用此解決方案無需修改您的FormType,選項'動作'是Symfony Forms支持的真正選項,因此無需使用路由器添加它。 你可以找到文件here

+0

它幾乎與我的答案相同。不同的是,我通過路由器,而不是網址。我不想將url存儲在控制器中,這不是一個好習慣。 – Eddie

+0

確實這和你幾乎一樣,不同的是我使用了內置的功能。兩者都是可能的。 – AnthonyB