I am trying to get i18n to extract the strings from my model in Cakephp 2.0
The documentation states that
"CakePHP will automatically assume that all model validation error messages in your $validate array are intended to be localized. When running the i18n shell these strings will also be extracted."
http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html
But my messages in my model are not being extracted into my po file when I run cake i18n and extract the data.
Does anyone know how to get the message strings into the po file?
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A Username is required',
'rule' => 'isUnique',
'message' => 'This username has already been taken'
)
);
}
This is how you can solve the problem I came across.
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
function __construct() {
parent::__construct();
$this->validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'))
'message' => __('A Username is required', true)),
'unique' => array(
'rule' => 'isUnique',
'message' => _('This username has already been taken', true)
)
);}
}
The correct way of achieve this is:
class AppModel extends Model {
public $validationDomain = 'validation_errors';
.
.
.
}
internally cake will call:
__d('validation_errors', 'Username should be more fun bla bla');
http://book.cakephp.org/2.0/en/console-and-shells/i18n-shell.html#model-validation-messages
http://book.cakephp.org/2.0/en/core-libraries/internationalization-and-localization.html#translating-model-validation-errors
Your $validate structure is a little messed up, you have two identical array keys (rule,message) under the required key. It should be:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => __('A Username is required', true),
),
'unique'=>array(
'rule' => 'isUnique',
'message' => __('This username has already been taken', true)
)
)
);
Related
I read from the cakePhp documentation , they only allow one rule per field.
However If my field require unique Date and must be date format. How should I place them ?
Current Code
<?php
App::uses('AppModel', 'Model');
class EventDate extends AppModel {
//public $useTable = 'eventdate';
public $primaryKey = 'event_date_id'; //I still need for Delete
public $validate = array(
'event_date' => array(
'rule' => array('date','ymd'),
'message' => 'Enter a valid date in YY-MM-DD format.',
'required' => true,
'allowEmpty' => false
)
// ,'event_date' => array(
// 'rule' => 'isUnique'
// )
);
}
There is no restriction on the number of rules a field can have in CakePHP. You can provide an associative array of rules for a specific field like this:-
public $validate = array(
'event_date' => array(
'format' => array(
'rule' => array('date','ymd'),
'message' => 'Enter a valid date in YY-MM-DD format.',
'required' => true,
'allowEmpty' => false
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This date already exists'
)
)
);
Just remember to make sure your array indexes are unique.
The array indexes for the individual rules (e.g. format and unique in the example code) can be anything, but make them descriptive to the rule being defined.
I have a simple registration form and complete model validation.
public function add() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
$this->User->set($this->request->data); //echo '<pre>'; print_r($this->data);exit;
if($this->User->validates()){
if ($this->User->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('User Saved!');
return $this->redirect('/users');
}
}
}
}
Modal validation code is below
class User extends AppModel {
public $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
'email' => 'email',
'born' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
)
);
}
The problem is that when i delete html fields using firebug and submit form it save data with blank entries . i think its a big problem i am facing because it not good practice to save blank entry and i want to stop it by the hacker or any one.
please help.
Add the validation rule 'notEmpty' for all fields which shouldn't be blank entries in the database.
Reference: cookbook
I am agree with semmelbroesel13
please use notEmpty rules as:
'rule' => array('notempty')
Updated:
Please try below code and check whats the query exactly
public function add() {
// Has any form data been POSTed?
if ($this->request->is('post')) {
$this->User->set($this->request->data); //echo '<pre>'; print_r($this->data);exit;
if($this->User->validates()){
if ($this->User->save($this->request->data)) {
$log=$this->User->getDataSource()->getLog(false, false);
echo "<pre>";print_r($log);exit;
// Set a session flash message and redirect.
$this->Session->setFlash('User Saved!');
return $this->redirect('/users');
}
}
}
}
I have a a form which adds first_name and last_name of user in cakephp.
here is the code
code for view (add.ctp)
<?php
echo $this->Form->create('User');
echo $this->Form->input('first_name',array('label'=>'First Name'));
echo $this->Form->input('last_name',array('label'=>'Last Name'));
echo $this->Form->end('Add User');
?>
code for UserController (UsersController.php)
<?php
public function add(){
if($this->request->is('post')){
$addData = $this->request->data;
$this->User->create();
if($this->User->save($addData)){
$this->Session->setFlash('User has been added successfully');
$this->redirect(array('action'=>'index'));
}
}
}
?>
view code for User Model (UserModel.php)
<?php
class UserModel extends AppModel{
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
?>
This is the code I am using, I have seen on cakebook as well and used various other rules, but no validation is working for my form. Can some please help me what could be the reason ?
Thanks in advance!
Your model filename is incorrect. It should be User.php not UserModel.php
please change your file name to user.php if your using table name in mysql as users instead of UserModel.php
and your classname must be like below
<?php
class User extends AppModel{
var $name = 'User';
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
?>
Your model name should be User (as your table name and controller name is users).
So try this in your model file(User.php)
<?php
App::uses('AppModel', 'Model');
class User extends AppModel{
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
New to unit testing... testing an articles controller and I am getting a fail on the $this->assertNotEmpty();
Shouldn't this be displaying an array full of validation errors? Instead I am getting an empty array.
It seems my validation rules are not being picked up... as further inspection show that Article::save() is returning true on data that should fail....
/**
* Admin Add
* #see controllers/MastersController::_admin_add()
* #return void
*/
public function admin_add(){
//parent::_admin_add();
if(!empty($this->request->data){
$this->Article->save($this->request->data);
}
}
/**
* Test Admin Add
*
* #return void
*/
public function testAdminAdd() {
#define sample passing data
$sampleDataPass = array(
'Article'=>array(
'title'=>'Test Article Add Will Pass',
'body'=>'Test Article Add Body',
'status_id'=>1,
'category_id'=>1,
)
);
#test action
$this->testAction('admin/articles/add', array('data'=>$sampleDataPass));
$this->assertEmpty($this->Articles->Article->validationErrors); #####PASSES#####
#define sample failing data
$sampleDataFail = array(
'Article'=>array(
'title'=>'Test Article Add Will Fail',
)
);
$this->testAction('admin/articles/add', array('data'=>$sampleDataFail));
$this->assertNotEmpty($this->Articles->Article->validationErrors); #####FAILS#####
}
class Article extends AppModel {
/*
* Name
*/
public $name = 'Article';
/*
* Validation Rules
*/
public $validate = array(
'title' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'You must supply an article title in order to save.',
),
),
'body' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'You must supply an article title in order to save.',
),
),
'status_id' => array(
'numeric' => array(
'rule' => array('numeric'),
'message' => 'You must choose a status.',
'allowEmpty' => false,
),
),
'category_id' => array(
'numeric' => array(
'rule' => array('numeric'),
'message' => 'You must choose a category.',
'allowEmpty' => false,
),
)
);
}
CakePHP will ignore validation rules if the field is not present in the data.
By setting the option 'required' to true the validation rule will always be checked.
For example:
'title' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'You must supply an article title in order to save.',
'required' => true
),
),
Documention on validation in CakePHP can be found here: http://book.cakephp.org/2.0/en/models/data-validation.html#one-rule-per-field
This is a fairly long question but I have know idea where it's going wrong. I am making an ajax login script using CakePHP 2.0 but it keeps failing. I will post all of my code, and i hope someone has the time to go through it.
This is my sql Database
AccountID AccountEmail AccountPassword AccountActive
1 chris#hotmail.co.uk pass 0
2 chris#gmail.com pass 1
This is my relevant Model Code
class Account extends AppModel {
public $name = 'Account';
public $validate = array(
'AccountEmail' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please Enter A Valid Email.'
),
'email' => array(
'rule' => array('email', true),
'message' => 'Please supply a valid email address.'
)
),
'AccountPassword' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please Enter A Valid Password.'
)
)
);
}
This is my relevant Controller Code
class AppController extends Controller {
/**
* Class Variables
*/
public $helpers = array('Js', 'Html', 'Session', 'Form');
public $components = array(
'Session',
'RequestHandler',
'Auth' => array(
'logoutRedirect' => array(
'controller' => 'Accounts',
'action' => 'login'
),
'authError' => 'You can\'t Access That Page',
'authorize' => array('Controller'),
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'AccountEmail',
'password' => 'AccountPassword'
),
'scope' => array('AccountActive' => '1')
)
)
)
);
}
class AccountsController extends AppController {
/**
* Class Variables
*/
public $name = 'Accounts';
public $layout = 'Accounts';
/**
* Class Functions
*/
public function login()
{
if ($this->request->is('ajax')) {
$this->Account->set($this->data);
if ($this->Account->validates()) {
if($this->Auth->login()) {
echo "logged In";
exit;
} else {
echo "Login Failed";
exit;
}
} else {
echo 'validation/' . json_encode($this->Account->invalidFields());
exit;
}
}
}
I don't think there is anything else. Again i'm sorry for the huge amount of code but i just don't know what you need.
The info is all passed via 'echo' to jquery which at the moment is just displaying the response via 'alert'.
I know the validation is working, but if i enter the info of someone who should be able to login it just shows "Login Failed". Thanks For Your Time.
Your passwords in the database need to be in their hashed form. Using Cake's default settings, 'pass' would be: 1c31af5bd9913ff511fe780f506e6fab68979b90