2017-08-03 23 views
0

Ich habe eine modelless Form:Invalidate einzelnes Formularfeld CakePHP

protected function _buildSchema(Schema $schema) 
{ 
    return $schema->addField('name', ['type' => 'string']) 
       ->addField('line1', ['type' => 'string']) 
       ->addField('city', ['type' => 'string']) 
       ->addField('state', ['type' => 'string']) 
       ->addField('country', ['type' => 'string']) 
       ->addField('postal_code', ['type' => 'string']) 
       ->addField('phone', ['type' => 'string']) 
       ->addField('email', ['type' => 'string']); 
} 

/** 
* Form validation builder 
* 
* @param \Cake\Validation\Validator $validator to use against the form 
* @return \Cake\Validation\Validator 
*/ 
protected function _buildValidator(Validator $validator) 
{ 
    return $validator->notEmpty('name') 
        ->notEmpty('line1') 
        ->notEmpty('city') 
        ->notEmpty('state') 
        ->notEmpty('country') 
        ->notEmpty('postal_code') 
        ->notEmpty('email') 
        ->add('email', 'valid', ['rule' => 'email']); 
} 


protected function _execute(array $data) 
{ 
    return true; 
} 

public function setErrors($errors) 
{ 
    $this->_errors = $errors; 
} 

Wie in der Dokumentation beschrieben Invalidating Individual Form Fields from Controller jetzt ich ein Feld von der Steuerung entkräften will, aber die Methode execute markiert immer noch als gültig:

$address = new AddressForm(); 

    if ($this->request->is('post')) { 

$address->setErrors(["line1" => ["_custom" => 'Inavlid field']]); 
     if ($address->execute($this->request->getData())) { 
      $this->Flash->success('Valid address'); 
     } else { 
      $this->Flash->error('There was a problem submitting your form.'); 
     } 
    } 

$this->set(compact('address')); 

Ich verwende die setErrors-Methode falsch?

Antwort

0

Verschieben Sie einfach die Zeile setErrors() unter dem Aufruf execute(), es wird die Fehler zurücksetzen ...