2011-12-03 27 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); 
    } 

} 

如何獲得$foo$bar$form對象,這樣我可以驗證它,並堅持呢?

回答

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() 

所以我猜你可以使用這個鉤子添加你的兩個字段。

相關問題