2013-04-01 1 views
1

zfcAdmin 및 BjyAuthorize에 내 사용자 정의 모듈을 통합하는 데 문제가 있습니다.zf2 양식 유효성 검사 (zfcAdmin 및 BjyAuthorize 관련)

내 폼 클래스 :

...  
$formOptions = $this->settings->getFormSettings(); 
foreach ($formOptions as $field){ 
if (isset($field['field'])) 
    $this->add($field['field']);   
} 
... 

내 필터 클래스 :

$formOptions = $this->settings->getFormSettings(); 
foreach ($formOptions as $filter){ 
if (isset($filter['filter'])) 
    $this->add($filter['filter']); 
} 
... 

필드, 필터 및 기타 옵션이 설정 파일에서 검색됩니다.

기본적으로 모든 것이 잘 작동합니다. 양식 데이터를 db에서 추가, 편집 또는 삭제할 수 있습니다. 또한 zfcAdmin 모듈 설치 후 문제가 발생하지 않았습니다. 모든 '사이트/mymodule'경로와 '사이트/관리/mymodule'경로를 사용하여 잘 작동합니다 : 나는 여전히 데이터베이스에서 항목을 추가, 편집 및 삭제할 수 있습니다.

여기에서 문제 : 일부 양식 요소 (이 경우 특정 선택)는 관리자 만 편집/볼 수 있어야합니다. (나는 admin을 위해 새로운 컨트롤러/엔티티 클래스 'ad hoc'을 쓸 수 있지만 전체 사이트에 동일한 코드를 사용하고 싶습니다.)

bjyoungblood/BjyAuthorize 모듈을 설치하고 구성했습니다. "값은 필수이며 비워 둘 수 없습니다"코드 여기

: 내가 편집 모드에있을 때 폼 요소는/오직 관리자에 필드하지만 양식 유효성 검사 오류가 표시됩니다

//view/mymodule/mymodule/update.phtml 
<div id="page" style="margin-top: 50px;"> 

<?php if (isset($this->messages) && count($this->messages) > 0): ?> 
<?php foreach ($this->messages as $msg): ?> 
<div class="alert alert-<?php echo $this->escapeHtmlAttr($msg['type']); ?>"> 
    <?php if (isset($msg['icon'])) echo '<i class="'.$this->escapeHtmlAttr($msg['icon']).'"></i>&nbsp;'; ?><?php echo $this->escapeHtml($msg['message']); ?> 
</div> 
<?php endforeach; ?> 
<?php endif; ?> 

<?php 
$title = 'Edit Item'; 
$this->headTitle($title); 
?> 
<h1><?php echo $this->escapeHtml($title); ?></h1> 

<?php 
$form = $this->form; 
$form->setAttribute('action', $this->url($this->route . 'mymodule/update', array('action' => 'update', 'id' => $this->id))); 
$form->prepare(); 
$form->setAttribute('method', 'post'); 
$input = $form->getInputFilter(); 

?> 

<?php echo $this->form()->openTag($form) ?> 
<dl class="zend_form"> 
    <?php foreach ($form as $element): ?> 

     <?php 
      //CHECK USER PRIVILEDGES 
      $elName = $element->getName(); 
      $elResource = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['resource'] : "userresource"; 
      $elPrivilege = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['privilege'] : "view"; 

      //SHOW THE ELEMENT IF ALLOWED 
      if($this->isAllowed($elResource, $elPrivilege)): 
     ?> 
      <?php if ($element->getLabel() != null): ?> 
       <dt><?php echo $this->formLabel($element) ?></dt> 
       <?php endif ?> 
      <?php if ($element instanceof Zend\Form\Element\Button): ?> 
       <dd><?php echo $this->formButton($element) ?></dd> 
       <?php elseif ($element instanceof Zend\Form\Element\Select): ?> 
       <dd><?php echo $this->formSelect($element) . $this->formElementErrors($element) ?></dd> 
       <?php else: ?> 
       <dd><?php echo $this->formInput($element) . $this->formElementErrors($element) ?></dd> 
       <?php endif ?> 
      <?php else: ?> 
      <?php   

      ?>   
     <?php endif ?> 

    <?php endforeach ?> 
</dl> 
<?php echo $this->form()->closeTag() ?> 


</div> 
<div class="clear-both"></div> 

내 컨트롤러 액션

//controller 
     public function updateAction(){ 
      $messages = array(); 
      $id = (int)$this->getEvent()->getRouteMatch()->getParam('id'); 
      $form = $this->getServiceLocator()->get('FormItemService'); 

      $itemMapper = $this->getItemMapper(); 
      $item = $itemMapper->findById($id); 
      $form->bind($item); 

      $request = $this->getRequest(); 

      if($request->isPost()){ 
       $form->setData($request->getPost()); 
       if ($form->isValid()) {    
        die('c');//never here 
        $service = $this->getServiceLocator()->get('mymodule\Service\Item'); 
        if ($service->save($form->getData())) 
        { 
         $messages[] = array(
           'type' => 'success', 
           'icon' => 'icon-ok-sign', 
           'message' => 'Your profile has been updated successfully!', 
         ); 
        } 
        else 
        { 
         $messages[] = array(
           'type' => 'error', 
           'icon' => 'icon-remove-sign', 
           'message' => 'Profile update failed! See error messages below for more details.', 
         ); 
        } 
       }else{ 
        var_dump($form->getMessages());//Value is required and can't be empty 
       } 
      } 

      return array(
       'messages' => $messages,  
       'form' => $form, 
       'id' => $id,  
       'form_options' => $this->getServiceLocator()->get('mymodule_module_options')->getFormSettings(), 
       'route' => $this->checkRoute($this->getEvent()->getRouteMatch()->getmatchedRouteName()) 
      ); 
     } 

사용자가 리소스를 볼 수 없으면 요소가 에코되지 않습니다. 따라서 $ request-> getPost()에는 해당 양식 요소에 대한 값이 없으며 isValid()에 의해 오류가 리턴됩니다.

누구나 비슷한 문제를 해결 했나요? 아니면 누군가가 올바른 방향으로 나를 가리킬 수 있습니까? 감사합니다.

+0

이 블로그는 검증 그룹 HTTP에 특히 마지막 섹션, 읽기 가치가있다 : //www.michaelgallego.fr/blog/2012/07/04/new-zendform-features-described/ – Crisp

답변

2

문제는 필수 필드를 정의한 FormFilter 클래스에서 보안 검사를 수행하지 않는다는 것입니다.

$ form-> isValid() 함수는 게시 된 데이터를 해당 필터 요소와 비교하여 검사합니다. 따라서 '에코 필드'가 보이지 않도록하려면 필터 요소에 보안 검사를 적용해야합니다.

+0

어쩌면 당신의 말을 완전히 이해하지 못했지만 해결책을 찾았습니다. 기본적으로보기 스크립트에서 Form으로 필터 클래스. 감사합니다 – IamFraz

0

하나의 다른 접근법은 프런트 엔드 용으로 하나와 관리자 용으로 두 가지 양식을 만드는 것입니다. 관리자 용 필드와 동일한 필드와 추가 선택 필드가 하나씩 있으므로 관리 양식을 프론트 엔드로 확장 할 수 있습니다. 예 :

class myForm 
{ 
    public function __construct(...) 
    { 
     // add fields and set validators 
    } 
} 

및 관리자 양식이 될 수 : 당신은 항상 최신 상태로 될 것입니다 백 엔드를 (또는 유효성 검사기를) 프론트 엔드 양식을 편집 할 경우에도 그 방법으로

class MyAdminForm extends myForm 
{ 
    public function __construct(...) 
    { 
     parent::__construct(...); 
     // add the extra field and extra validator 
    } 
} 

. 이 :) 도움이

희망,

의 Stoyan

+0

당신의 힌트를 가져 주셔서 감사합니다. 이상적으로 말하자면, 이것은 제가 찾고있는 것이 아닙니다. 필드는 액세스 수준과 같이 증가 할 수 있습니다. – IamFraz