Moorani
Moorani

Reputation: 129

Form Validation in CakePHP 2

In my view I have

<?= $this->Form->create('Asc201516', array(
'url' => array(
    'controller' => 'asc201516s', 
    'action'     => 'submit_asc201516'
    ), 
'class' => 'form-inline',
'onsubmit' => 'return check_minteacher()'
)); ?>

<div class="form-group col-md-3">
    <?= $this->Form->input('bi_school_na', array(
        'type' => 'text',
        'onkeypress' => 'return isNumberKey(event)',
        'label'       => 'NA', 
        'placeholder' => 'NA', 
        'class'       => 'form-control'
    )); ?>
</div>
<?php 
$options = array(
    'label' => 'Submit',
    'class' => 'btn btn-primary');
echo $this->Form->end($options); 
?>

In my Controller, I have

$this->Asc201516->set($this->request->data['Asc201516']);
        if ($this->Asc201516->validates()) {
            echo 'it validated logic';
            exit();

        } else {                
            $this->redirect(
                array(
                    'controller' => 'asc201516s',
                    'action' => 'add', $semisid
                    )
                );

        }

In my Model, I have

 public $validate = array(
        'bi_school_na' => array(
            'Numeric' => array(
                'rule' => 'Numeric',
                'required' => true,
                'message' => 'numbers only',
                'allowEmpty' => false
            )
        )
    );

When I submit the form, logically it should not get submitted and print out the error message but the form gets submitted instead and validates the model inside controller which breaks the operation in controller.

Upvotes: 0

Views: 1086

Answers (1)

Pradeep Singh
Pradeep Singh

Reputation: 1280

You have to check validation in your controller like

$this->Asc201516->set($this->request->data);  
if($this->Asc201516->validates()){  
    $this->Asc201516->save($this->request->data);  
}else{  
    $this->set("semisid",$semisid);
    $this->render("Asc201516s/add");
}

You will have your ID there in variable $semisid, or you can set data in $this->request->data = $this->Asc201516->findById($semisid);

Upvotes: 1

Related Questions