2012-05-09 44 views
5

Tôi muốn tạo trình xác thực tương tự như cách GitHub xử lý việc xóa kho. Để xác nhận xóa, tôi cần nhập tên repo. Ở đây tôi muốn xác nhận xóa bằng cách nhập thuộc tính thực thể "name". Tôi sẽ cần phải chuyển tên cho ràng buộc hoặc truy cập vào một cách nào đó, làm cách nào để làm điều đó?Trình xác thực/Ràng buộc tùy chỉnh với các đối số/tham số trong Symfony 2

Trả lời

2

bạn thực sự có thể sử dụng một hạn chế validator để làm điều đó:

1: Tạo một hình thức xóa (directy hoặc sử dụng một loại):

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

2: Thêm một tài sản công cộng comparisonName vào thực thể của bạn. (hoặc sử dụng một đối tượng proxy), sẽ được ánh xạ tới trường biểu mẫu tương ứng ở trên.

3: Xác định một hạn mức lớp, gọi lại validator để so sánh cả hai giá trị:

/** 
* @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: Hiển thị hình thức của bạn theo quan điểm của bạn:

<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: Để xác minh rằng truy vấn xóa hợp lệ, hãy sử dụng truy vấn này trong trình điều khiển của bạn:

$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()); 
Các vấn đề liên quan