I have a field gentel_id with the following validation rules in my model Contrat:
public $validate = array(
'gentel_id' => array(
'numeric' => array(
'rule' => 'numeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Veuillez entrer un identifiant GENTEL ou mettre la valeur 0000000000',
),
),
);
In my controller:
public function add($id = null) {
if ($this->request->is('post')) {
$this->Contrat->create();
if ($this->Contrat->save($this->request->data)) {
$this->Session->setFlash(__('Le Contrat a été ajouté'));
$this->redirect(array('action' => 'edit', $this->Contrat->getInsertID() ));
} else {
debug($this->Contrat->validationErrors);
$this->Session->setFlash(__('Le Contrat ne peut être ajouté'));
}
$this->set('id',$id);
...
}
In my form:
<?php echo $this->Form->create('Contrat');?>
<?php
if (empty($id)){
echo $this->Form->input('client_id',array('empty' => "Client non défini",'default' => $id, 'onchange'=>"window.location.href= '/contrats/add/'+this.form.ContratClientId.options[this.form.ContratClientId.selectedIndex].value"));
}else{
echo "<span class=\"label\">".__('Client')."</span>".$this->Kaldom->link(h($clients[$id]),array('controller' => 'clients', 'action' => 'view',$id));
echo $this->Form->input('client_id', array('type' => 'hidden','value' => $id));
}
echo $this->Form->input('gentel_id',array('type'=>'text','label'=> 'Gentel ID'));
?>
<?php echo $this->Form->end(__('Créer'));?>
When I try to save my form with "gentel_id" empty, the save is correctly not done and a debug ($this->Contrat->validationErrors) give me this:
Array
(
[gentel_id] => Array
(
[0] => Veuillez entrer un identifiant GENTEL ou mettre la valeur 0000000000
)
)
But the error messsage is not displayed in my form.
Note that it is an add function but I have passed a parameter in the url like this:
.../contrats/add/3
Can you help me please?
Related
I have a project where I have a procedures, categories and subcategories table,
Sub-category poced from a foreign key to category
Procedure has a foreign key to category and to subcategory
In my controller / setupListOperation, I added 2 filters that I would like to put in relation, see that the subcategories of the category select as a filter.
But I do not see how to make the link between the two select2_ajax.
// Filtre sur la catégorie
CRUD::addFilter([
'name' => 'filtre_categorie',
'type' => 'select2',
'label' => 'Filtre de catégorie',
'placeholder' => 'Sélectionner une catégorie',
'minimum_input_length' => 0,
],
function () { return \App\Models\Categorie::all()->keyBy('id')->pluck('name', 'id')->toArray();
}, function ($value) { // if the filter is active
$this->crud->addClause('where', 'categorie_id', $value);
});
// Filtre sur la sous catégorie
CRUD::addFilter([
'name' => 'filtre_souscategorie',
'type' => 'select2_ajax',
'label' => 'Filtre de sous-catégorie',
'placeholder' => 'Sélectionner une sous-catégorie',
'minimum_input_length' => 0,
],
url('admin/procedure/ajax-souscategory-options'), // the ajax route
function($value) { // if the filter is active
$this->crud->addClause('where', 'souscategorie_id', $value);
});
I found a solution by doing so:
My Field :
// Filtre sur nom
CRUD::addFilter([
'type' => 'text',
'name' => 'nom_filter',
'label' => 'Recherhe par nom de procédure'
],
false,
function($value) { // if the filter is active
$this->crud->addClause('where', 'name', 'LIKE', "%$value%");
});
// Filtre sur la catégorie
CRUD::addFilter([
'name' => 'filtre_categorie',
'type' => 'select2',
'label' => 'Filtre de catégorie',
'placeholder' => 'Sélectionner une catégorie',
'minimum_input_length' => 0,
],
function () { return \App\Models\Categorie::all()->keyBy('id')->pluck('name', 'id')->toArray();
}, function ($value) { // if the filter is active
$this->crud->addClause('where', 'categorie_id', $value);
});
My Class :
public function souscategoryFilterOptions(Request $request) {
$term = $request->input('term');
$options = \App\Models\Souscategorie::query();
$str = $_SERVER['HTTP_REFERER'];
$qs = parse_url($str, PHP_URL_QUERY);
if(!empty($qs)){
parse_str($qs, $output);
$resultsFilter = $options->where('categorie_id', $output['filtre_categorie'])->get()->pluck('name', 'id');
}
if ($term) {
$resultsFilter = $options->where('name', 'LIKE', '%'.$term.'%')->paginate(10);
} else {
$resultsFilter = $options->paginate(10);
}
return $resultsFilter;
}
I'm trying to display validation errors with CakePHP (Newbie) but I'm stuck. I get this error "Delimiter must not be alphanumeric or backslash". Don't know if the logic is respected, I'm starting from scratch.
Nothing is displayed. Here's my code:
User model
class User extends AppModel {
public $validate = array(
'nom' => array(
'message' => 'Saisie obligatoire',
'required' => true
),
'prenom' => array(
'message' => 'Saisie obligatoire',
'required' => true
),
'date_naissance' => array(
'rule' => array('date','dmy'),
'message' => 'Veuillez respecter le format de la date (jour/mois/année)',
'allowEmpty' => true
),
'email' => array(
'rule' => 'email',
'message' => 'Veuillez introduire une adresse mail valide',
'required' => true
),
'password' => array(
'rule' => 'password',
'message' => 'Un mot de passe est requis'
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
add function into UsersController
public function add() {
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Auth->login($this->User);
return $this->redirect('/index');
}
}
} else {
return $this->User->validationErrors;
}
}
add.ctp
<?= $this->element('navbar');?>
<div class="formcontainer">
<div class="page-header">
<h1>Rejoignez-nous</h1>
</div>
<form action="/users/add" id="UserAddForm" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST"/>
</div>
<div class="form-group input text">
<label for="UserNom">Nom:</label>
<input name="data[User][nom]" maxlength="20" type="text" id="UserNom" class="form-control" placeholder="requis">
</div>
<div class="form-group input text">
<label for="UserPrenom">Prénom:</label>
<input name="data[User][prenom]" maxlength="20" type="text" id="UserPrenom" class="form-control" placeholder="requis">
</div>
<div class="form-group input text">
<label for="UserDateNaissance">Date de naissance:</label>
<input name="data[User][date_naissance]" maxlength="20" type="text" id="UserDateNaissance" class="form-control">
</div>
<div class="form-group input email">
<label for="UserEmail">Email:</label>
<input name="data[User][email]" maxlength="100" type="email" id="UserEmail" class="form-control" placeholder="requis"/>
</div>
<div class="form-group input password">
<label for="UserPassword">Mot de passe:</label>
<input type="password" name="data[User][password]" class="form-control" id="UserPassword" placeholder="requis">
</div>
<button type="submit" class="btn btn-default bSub">M'inscrire</button>
</form>
</div>
Your validation should be like this(You must add rule for field and there is no inbuilt passowrd rule in cakephp).
public $validate = array(
'nom' => array(
'rule' => 'notEmpty', //add rule here
'message' => 'Saisie obligatoire',
'required' => true
),
'prenom' => array(
'rule' => 'notEmpty', //add rule here
'message' => 'Saisie obligatoire',
'required' => true
),
'date_naissance' => array(
'rule' => array('date', 'dmy'),
'message' => 'Veuillez respecter le format de la date (jour/mois/année)',
'allowEmpty' => true
),
'email' => array(
'rule' => 'email',
'message' => 'Veuillez introduire une adresse mail valide',
'required' => true
),
'password' => array(
'rule' => 'notEmpty', //there is no inbuilt validation rule with name *password*
'message' => 'Un mot de passe est requis'
)
);
If you want to show error message then you should use Form Helper for create form inputs like this
echo $this->Form->input("User.nom", array("class"=>"form-control", "placeholder"=>"requis", 'label'=>false));
Or you can display message by using isFieldError method of Form helper
if ($this->Form->isFieldError('nom')) {
echo $this->Form->error('nom');
}
// Model
class User extends AppModel {
public $validate = array(
'password' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Un mot de passe est requis'
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Veuillez introduire une adresse mail valide',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'date_naissance' => array(
'date' => array(
'rule' => array('date'),
'message' => 'Veuillez respecter le format de la date (jour/mois/année)',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'prenom' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Saisie obligatoire',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'nom' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Saisie obligatoire',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
// Controller
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
// add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('password');
echo $this->Form->input('email');
echo $this->Form->input('date_naissance');
echo $this->Form->input('prenom');
echo $this->Form->input('nom');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users'), array('action' => 'index')); ?></li>
</ul>
</div>
I’ve a problem with implementing recaptcha in a CodeIgniter application.
The problem is that the recapctha_challenge_field and recaptcha_response_field do not get posted, however, the recapctcha (and those fields) is visible on the page (within the form).
The the recapctha_challenge_field and recaptcha_response_field are appearing in the HTML of the page, but not in the header when I post the form.
I’ve downloaded de recaptcha library and added it as an helper in CI.
Within the form in my view I echo the recaptcha_get_html($publickey) (with the public key set).
In my controller, I load the recaptchalib_helper and add set a form validation rule for the recapctha_challenge_field.
This is my view:
<h1>Register</h1>
<fieldset>
<legend>Personal information</legend>
<?php
echo form_open('login/create_user');
echo form_label('First name:', 'first_name');
echo form_input(
array(
'name' => 'first_name',
'id' => 'first_name',
'value' => set_value('first_name')
)
);
echo form_label('Last name:', 'last_name');
echo form_input(
array(
'name' => 'last_name',
'id' => 'last_name',
'value' => set_value('last_name')
)
);
echo form_label('Birth date:', 'birth_date');
echo form_input(
array(
'name' => 'birth_date',
'id' => 'birth_date',
'value' => set_value('birth_date')
)
);
echo form_label('E-mail:', 'email');
echo form_input(
array(
'name' => 'email',
'id' => 'email',
'value' => set_value('email')
)
);
?>
</fieldset>
<fieldset>
<legend>Login information</legend>
<?php
echo form_label('Username:', 'username');
echo form_input(
array(
'name' => 'username',
'id' => 'username',
'value' => set_value('username')
)
);
echo form_label('Password:', 'password1');
echo form_password(
array(
'name' => 'password1',
'id' => 'password1',
'value' => set_value('password1')
)
);
echo form_label('Confirm password:', 'password2');
echo form_password(
array(
'name' => 'password2',
'id' => 'password2',
'value' => set_value('password2')
)
);
$publickey = "mypublickey"; // here I entered my public key
echo recaptcha_get_html($publickey);
echo form_label(nbs(1), 'submit');
echo form_submit(
array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Registreren'
)
);
echo form_close();
?>
<?php echo validation_errors('<p class="error">'); ?>
</fieldset>
</div>
and this is a part of my controller:
function create_user() {
print_r($_POST);//for debugging
$this->load->library('form_validation');
$this->load->model('user');
$this->form_validation->set_rules('recaptcha_challenge_field', 'Captcha', 'callback_validate_captcha');
$this->form_validation->set_rules('first_name', 'First name', 'trim|xss_clean|required');
$this->form_validation->set_rules('last_name', 'Last name', 'trim|xss_clean|required');
$this->form_validation->set_rules('email', 'E-mail', 'trim|xss_clean|valid_email|callback_is_email_available|required');
$this->form_validation->set_rules('username', 'Username', 'trim|xss_clean|min_length[5]|callback_is_username_available|required');
$this->form_validation->set_rules('password1', 'Password', 'trim|xss_clean|min_length[8]|max_length[32]|required');
$this->form_validation->set_rules('password2', 'Confirm password', 'trim|xss_clean|matches[password1]|required');
if ($this->form_validation->run() == FALSE) {
$this->signup();
} else {
if ($this->user->create_user($this->input->post('username'),$this->input->post('password1'),$this->input->post('email'),$this->input->post('first_name'),$this->input->post('last_name'),$this->input->post('birth_date'))) {
$data['main_content'] = 'login/signup_successful';
$this->load->view('includes/template', $data);
} else {
$this->load->view('login/signup_form');
}
}
}
public function validate_captcha($recaptcha_challenge_field) {
$this->load->helper('recaptchalib');
$privatekey = "myprivatekey";//this is et to my private key
$resp = recaptcha_check_answer ($privatekey,
$this->input->ip_address(),
$this->input->post("recaptcha_challenge_field"),
$this->input->post("recaptcha_response_field"));
if (!$resp->is_valid) {
$this->form_validation->set_message('validate_captcha', 'Invalid Capctha code entered.');
return FALSE;
} else {
return TRUE;
}
}
The capctha fields are not set in the HTTP headers:
Form data:
csrf_test_name:8cc3f2391784867df2d46f193a65a317
first_name:Myfirstname
last_name:Mylastname
birth_date:10-12-2012
email:myemail#adres.com
username:username
password1:password
password2:password
submit:Register
What am I doing wrong?
Your sincerely,
Alwin
Does the form tag not begin within a table, tbody or tr?
Iam new in cakephp ,I need to validate a form.
This is the code:
Controller:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
public function index(){
}
function add_task()
{
if(!empty($this->data)) {
//print_r($this->data);
$this->Task->set($this->data);
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
// didn't validate logic
echo $errors = $this->Task->validationErrors;
}
}
}
}
?>
Model:
<?php
class Task extends AppModel
{
public var $name = 'Task';
var $useDbConfig = 'travanco_erp';
public var $useTable = 'tbl_tasks'; // This model uses a database table 'exmp'
public var $validate = array(
'task_title_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The title field is required'
),
'task_description_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The description field is required'
),
'task_from_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The from date field is required'
),
'task_to_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The to date field is required'
)
);
}
?>
This is the view:
<div class="employeeForm" style="width:64%; padding:10px 30%;">
<?php echo $this->Form->create('test', array('class'=>'form'));?>
<fieldset style="width:36em; padding:0px 0px;">
<div style="width:475px; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#333333; font-weight:bold; margin-left:20px; margin-top:10px;">Add Task</div>
<br/>
<?php
/*echo $this->Form->input('task_ids_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Task ID',
));*/
echo $this->Form->input('task_title_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Title',
));
echo $this->Form->input('task_description_mm', array( 'type' => 'textarea',
'cols'=>60,
'rows' => 5,
'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Description',
));
echo $this->Form->input('task_from_mm', array( 'div'=>'frm_filed_new','id'=>'task_from_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'From',
));
echo $this->Form->input('task_to_mm', array( 'div'=>'frm_filed_new','id'=>'task_to_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'To',
));
?>
<br/>
<?php echo $this->Form->button('Submit', array('type'=>'submit','escape'=>true)); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
The validation not working.
What is the error in my code?
How can i solve this?
EDIT:
It is the mistake of misconfiguration of databse.php file.Now its corrected .And the print_r($errors) displays the errors.But that not displayed in the view page , i mean near the textboxes.
This is that error array:
Array ( [task_title_mm] => Array ( [0] => The title field is required ) [task_description_mm] => Array ( [0] => The description field is required ) [task_from_mm] => Array ( [0] => The from date field is required ) [task_to_mm] => Array ( [0] => The to date field is required ) )
How can i put it in near the text box?
CakePHP is designed to automatically validate model and display validation errors. Auto validation runs on model save. In your case:
$this->Task->save($this->request->data);
above will trigger validation. There is no need to run: $this->Task->validates() - If you do so, you also have to take care of displaying validation error by your own. So I think you simply should try:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
function add_task()
{
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Task->save($this->request->data)) {
//saved and validated
}
}
}
}
?>
one thing i noticed in your code that you are writing in your model
public var $validate=array();
instead try
public $validate= array() or var $validate=array();
Validation should work after words.
Thanks :)
Try this:
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
$this->validateErrors($this->Task);
$this->render();
}
I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.