Correct way to post a form in cakephp 2.* with client side validation in JavaScript

|
| By Webner

If we follow cakephp rules to create a form then we can use cakephp inbuilt functionality like we don’t need to assign labels to form fields. Cakephp automatically creates a label for each form field also in case of update/insert validation error messages, the message is automatically shown below the field. In controller, we can directly use posted data in save and update functions there is no need to write extra code to pass into save or update functions.

In View/User/add.ctp file:

<!-- Form name must be same as model name -->
<?php
echo $this->Form->create('User', array(
'id' => 'User'
));
?>
<fieldset>
<legend><?php
echo __('Add User');
?></legend>
<?php
//always set input field name same as column in user table
echo $this->Form->input('name');
echo $this->Form->input('age', array(
'id' => 'age'
));
?>
</fieldset>
<?php
echo $this->Form->end(__('Submit'));
?>

<script>
$( "#User" ).submit(function( event ) {
$('span.error-keyup-1').hide();
var numericReg = /^[0-9]*\.?[0-9]*$/;
var inputVal = $('#age').val();
if(!numericReg.test(inputVal)) {
$('#age').after('<span class="error error-keyup-1" style="color:red">Numeric value only.</span>');
$("#age").focus();
return false;
}
$( "#User" ).submit();
});
</script>

In Controller/UserController file:

public
function add() {
if (isset($_POST['data']['User'])) {
$this - > User - > saveAll($this - > request - > data);
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *