2011-07-16 9 views
9

Estoy tratando de tener una casilla de verificación "Agree TOS".Confirmación de Casilla de verificación de CakePHP "Agree TOS"

Si la casilla de verificación es no marcada, quiero publicar un mensaje de advertencia.

¿Cómo puedo hacer esto?

Mi Vista:

<?php 
     echo $form->create('Item', array('url' => array_merge(array('action' => 'find'), $this->params['pass']))); 
     echo $form->input('Search', array('div' => false)); 
     echo $form->submit(__('Search', true), array('div' => false)); 
     echo $form->checkbox('tos', array('label' => false, 'value'=>1)).' Agree TOS'; 
     echo $form->error('tos'); 
     echo $form->end(); 
?> 

Mi Modelo:

var $check = array(
      'tos' => array(
       'rule' => array('comparison', 'equal to', 1), 
       'required' => true, 
       'allowEmpty' => false, 
       'on' => 'index', 
       'message' => 'You have to agree TOS' 
       )); 
+3

Su regla La matriz s debe ser '$ validate', no' $ check', creo. – lxa

+0

Tal vez exagerado, pero también puede aprovechar un [Comportamiento confirmable] (http://www.dereuromark.de/tag/confirmable/). – mark

Respuesta

0

Creo que necesita tratar guardarlo en su modelo para atrapar sus reglas tos. Debería hacer algo como =

if(!$mymodel->save()){ 
// catch error tos. 
} 
0

$this->ModelName->invalidFields() devuelve una matriz de campos que no superaron la validación.

Puede tratar de buscar el campo tos y enviar un mensaje si la clave existe.

~ no probado (no estoy seguro de la parte superior de mi cabeza la estructura exacta de la matriz invalidFields retorno.

$failed_fields = $this->ModelName->invalidFields(); 

if(array_key_exists('tos', $failed_fields)) { 
    $this->Session->setFlash('Please accept the terms and conditions'); 
} 
0

que ni siquiera tiene que tener regla de validación para tos, solo hay que mirar en el controlador antes de guardar los datos.

if($this->data['Model']['tos']==1){ 
    // save data 
    }else{ 
    //set flash 
    } 
1

básicamente, se agrega la regla "notEmpty" para este campo a la public $validate gama del modelo. de esta manera se activará un error en Model->validates() si no se ha marcado la casilla de verificación.

tal vez un poco de sobrecarga en su caso, pero si lo usa con más frecuencia pruebe un enfoque DRY (no se repita). también se puede utilizar un comportamiento de esta opción para utilizar este limpio y sin templar demasiado con el modelo/controlador:

// view form 
echo $this->Form->input('confirmation', array('type'=>'checkbox', 'label'=>__('Yes, I actually read it', true))); 

y en la acción del controlador

// if posted 
$this->Model->Behaviors->attach(array('Tools.Confirmable'=>array('field'=>'confirmation', 'message'=>'My custom message'))); 
$this->Model->set($this->data); 
if ($this->Model->validates()) { 
    // OK 
} else { 
    // Error flash message here 
} 

1.x: https://github.com/dereuromark/tools/blob/1.3/models/behaviors/confirmable.php

para 2.x: https://github.com/dereuromark/cakephp-tools/blob/2.x/Model/Behavior/ConfirmableBehavior.php

3.x: https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ConfirmableBehavior.php

detalles: http://www.dereuromark.de/2011/07/05/introducing-two-cakephp-behaviors/

+0

enlace de github está muerto – Ruben

+0

thx. la ramificación modificó los enlaces. Lo corregí. – mark

16

Esto parece trabajar para mí. Espero que ayude

En el modelo:

  'tos' => array(
       'notEmpty' => array(
        'rule'  => array('comparison', '!=', 0), 
        'required' => true, 
        'message' => 'Please check this box if you want to proceed.' 
       ) 

En vista:

<?php echo $this->Form->input('tos', array('type'=>'checkbox', 'label'=>__('I confirm I have read the <a href="/privacy-statement">privacy statement</a>.', true), 'hiddenField' => false, 'value' => '0')); ?> 
1

Modelo

'agreed' => array(
     'notempty' => array(
      'rule' => array('comparison', '!=', 0),//'checkAgree', 
      'message' => ''You have to agree TOS'', 
      'allowEmpty' => false, 
      'required' => true, 
      'last' => true, // Stop validation after this rule 
      'on' => 'signup', // Limit validation to 'create' or 'update' operations 
     ), 
    ), 

Ver

<?php echo $this->Form->input('agreed',array('value'=>'0'),array('type'=>'checkbox', 'label'=>'Agree to TOS')); ?> 
Cuestiones relacionadas