2011-12-03 3 views
0

一部のデータはフォームから送信するユーザーからのもので、残りの部分は実際のコントローラーで生成されます。だから、のようなもの:私はそれを検証し、それを持続できるようにSymfony2のコントローラー内で送信されたフォームオブジェクトにデータを追加します。

# controller 
use Acme\SomeBundle\Entity\Variant; 
use Acme\SomeBundle\Form\Type\VariantType; 

public function saveAction() 
{ 
    $request = $this->getRequest(); 

    // adding the data from user submitted from 
    $form = $this->createForm(new VariantType()); 
    $form->bindRequest($request); 


    // how do I add this data to the form object for validation etc 
    $foo = "Some value from the controller"; 
    $bar = array(1,2,3,4); 

    /* $form-> ...something... -> setFoo($foo); ?? */ 

    if ($form->isValid()) { 

     $data = $form->getData(); 

     // my service layer that does the writing to the DB 
     $myService = $this->get('acme_some.service.variant'); 
     $result = $myService->persist($data); 
    } 

} 

にはどうすれば$formオブジェクトに$foo$barを得るのですか?ここで

答えて

0

は、私が使用している一般的なパターンです:

public function createAction(Request $request) 
{ 
    $entity = new Entity(); 
    $form = $this->createForm(new EntityType(), $entity); 

    if ($request->getMethod() == 'POST') { 
     $foo = "Some value from the controller"; 
     $bar = array(1, 2, 3, 4); 

     $entity->setFoo($foo); 
     $entity->setBar($bar); 

     $form->bindRequest($request); 
     if ($form->isValid()) { 
      $this->get('some.service')->save($entity); 
      // redirect 
     } 
    } 

    // render the template with the form 
} 
0

Formクラスのbindメソッドのコードを読んで、私たちはこの読むことができます:

// Hook to change content of the data bound by the browser 
$event = new FilterDataEvent($this, $clientData); 
$this->dispatcher->dispatch(FormEvents::BIND_CLIENT_DATA, $event); 
$clientData = $event->getData() 

をだから私は、あなたが使うことができると思いますこのフックはあなたの2つのフィールドを追加します。

関連する問題