2010-03-17 5 views
3

저는 cakephp를 처음 사용하고 간단한 응용 프로그램을 작성하려고하지만 일부 양식 유효성 검사 문제가 있습니다.CakePHP 폼 유효성 검사가 실패 할 때 URL 매개 변수를 유지하는 방법

나는 많은 "PersonSkill"개체가있는 "Person"이라는 모델이 있습니다. 나는 우리가 사람의 이름을 표시 할 때문에

http://localhost/myapp/person_skills/add/person_id:3

나는 person_id로 통과되었습니다 사람에게 "PersonSkill"를 추가하려면,이 같은 URL을 호출하도록 설정 한 기술을 추가합니다.

내 문제는 유효성 검사에 실패하면 person_id 매개 변수가 다음 요청에 대해 유지되지 않으므로 사람의 이름이 표시되지 않습니다.

컨트롤러에 추가하는 방법은 다음과 같습니다 : 내 person_skill의 add.ctp에서

function add() {   
    if (!empty($this->data)) {   
     if ($this->PersonSkill->save($this->data)) { 
      $this->Session->setFlash('Your person has been saved.'); 
      $this->redirect(array('action' => 'view', 'id' => $this->PersonSkill->id)); 
     }  
    } else { 
     $this->Person->id = $this->params['named']['person_id']; 
     $this->set('person', $this->Person->read());   
    } 
} 

내가 person_id로를 보유하고 숨겨진 필드, 예를 들어 설정 :

echo $form->input('person_id', array('type'=>'hidden','value'=>$person['Person']['id'])); 

을 방법이 있나요 폼 유효성 검사가 실패 할 때 person_id url 매개 변수를 유지하려면이 작업을 수행하는 더 좋은 방법이 있습니까?

모든 조언을 주시면 감사하겠습니다.

답변

6

에서 컨트롤러의 검증에 사용 설명서에서

if(!empty($this->data)) { 
if($this->PersonSkill->validates()) { 
    if($this->PersonSkill->save($this->data) { 
    ... 
    } 
    else { // invalid data 
    $this->redirect(array('action' => 'view', 'id' => $this->PersonSkills->id)); 
    } 
} 
} 

FormHelper는 :: 방법은 당신이 작성하는 양식 태그의 action 속성에있는 URL을 구성 할 수 있습니다()를 만듭니다.

동일한 URL에 게시 할 수 있도록 현재 URL이 사용되고 있는지 확인하고 유효성 검사에 실패하면 person_id라는 이름의 매개 변수가 그대로 유지됩니다. 현재 컨트롤러와 액션으로

echo $form->create('PersonSkill', array('url' => $this->params['named'])); 

CakePHP의 명명 된 PARAMS, 즉 배열을 병합한다 (=> 3 'person_id로')를 당신이에있는 같은 URL을 반환 :

이 같은 것을보십시오.

한편, $ this-> data가 비어 있지 않으면 사람 세부 정보를 읽고보기에서 사용 가능하도록 설정해야하므로 컨트롤러에서 else 문을 잃어 버리고 그냥 가지고있을 것입니다 :

function add() {   
    if (!empty($this->data)) {   
     if ($this->PersonSkill->save($this->data)) { 
      $this->Session->setFlash('Your person has been saved.'); 
      $this->redirect(array(
       'action' => 'view', 
       'id' => $this->PersonSkill->id 
      )); 
     }  
    } 
    $this->Person->id = $this->params['named']['person_id']; 
    $this->set('person', $this->Person->read());   
} 
+0

감사합니다 - 이것은 내가 필요한 것입니다! –

+0

이미 존재한다면 매개 변수가 중복되지 않습니다. 우수한 솔루션. – Cruachan

관련 문제