2012-05-09 89 views
5

我想創建一個類似於GitHub處理刪除存儲庫的驗證器。要確認刪除,我需要輸入回購名稱。這裏我想通過輸入實體屬性「name」來確認刪除。我要麼需要將名稱傳遞給約束,要麼以某種方式訪問​​它,我該怎麼做?自定義驗證器/ Symfony 2中的參數/參數約束

回答

2

你確實可以使用驗證約束來做到這一點:

1:創建一個刪除形式(directy或使用類型):

return $this->createFormBuilder($objectToDelete) 
     ->add('comparisonName', 'text') 
     ->setAttribute('validation_groups', array('delete')) 
     ->getForm() 
    ; 

2:添加一個公共財產comparisonName進入你的實體。 (或者使用代理對象),它將被映射到上面相應的表單域。

3:定義一個類層次,回調驗證約束這兩個值進行比較:

/** 
* @Assert\Callback(methods={"isComparisonNameValid"}, groups={"delete"}) 
*/ 
class Entity 
{ 
    public $comparisonName; 
    public $name; 

    public function isComparisonNameValid(ExecutionContext $context) 
    { 
     if ($this->name !== $this->comparisonName) { 
      $propertyPath = $context->getPropertyPath() . '.comparisonName'; 
      $context->addViolationAtPath(
       $propertyPath, 
       'Invalid delete name', array(), null 
      ); 
     } 
    } 
} 

4:顯示錶單在視圖:

<form action="{{ path('entity_delete', {'id': entity.id }) }}"> 
    {{ form_rest(deleteForm) }} 
    <input type="hidden" name="_method value="DELETE" /> 
    <input type="submit" value="delete" /> 
</form> 

5:要驗證刪除查詢是否有效,請在您的控制器中使用它:

$form = $this->createDeleteForm($object); 
    $request = $this->getRequest(); 

    $form->bindRequest($request); 
    if ($form->isValid()) { 
     $this->removeObject($object); 
     $this->getSession()->setFlash('success', 
      $this->getDeleteFlashMessage($object) 
     ); 
    } 

    return $this->redirect($this->getListRoute());