I am using cake PHP for integrating my stuff; however it is not showing model validation errors in my view.I think some small think is missed from my code, but didn't find out.
Below is my model, view and controller code:
Model:
class Category extends Model {
var $validate = array(
'title' => array(
'rule' => 'notEmpty',
'message' => 'Title is required'
)
);
}
View:
<?php
echo $this->Form->create( 'Category', array( 'action'=>'add', 'enctype' => 'multipart/form-data' ) );
?>
<fieldset>
<legend>Add new category</legend>
<?php
echo $this->Form->input( 'title' );
?>
</fieldset>
<?php
echo $this->Form->submit( 'Add Category' );
echo $this->Form->end();
?>
Controller:
class CategoriesController extends AppController {
var $helpers = array( 'Form', 'Html', 'Js' );
function add() {
$this->loadModel('Category');
$this->Category->set( $this->data );
$this->Category->save( $this->data );
if( !$this->Category->validates() ){
$errors = $this->Category->validationErrors;
}
}
}
Thanks in advance.
if( !$this->Category->save( $this->data ) ){
$errors = $this->Category->validationErrors;
}
You just check wether data has been saved or not. If not then process validation errors. Set errors to the view or just debug in the controller itself.
this may help you.
Related
I is not What is the problem, I made a simple blog in Croogo, the problem is it is not adding or modifying or delete, because Arabic language ??
function add in controller
`public function admin_add() {
$this->set('title_for_layout', __('Add Part'));
if (!empty($this->request->data)) {
$this->Part->create();
if ($this->Part->save($this->request->data)) {
$this->Session->setFlash(__('The Part has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));//, $this->Part->id));
} else {
$this->Session->setFlash(__('The Part could not be saved. Please, try again.'), 'default', array('class' => 'error'));
}
}
}`
=>
model
`class Part extends AppModel {
public $name = 'Part';
var $belongsTo = array(
'Market' => array(
'className' => 'Market',
'foreignKey' => 'market_id',
)
);
protected $_displayFields = array(
'id',
'num_part',
'prix_part',
'prop_Pledge',
'prix_Pledge',
);
}
`
add view
<?php $this->extend('/Common/admin_edit'); ?>
<?php echo $this->Form->create('Part');?>
<fieldset>
<div class="tabs">
<ul>
<li><span><?php echo __('Part'); ?></span></li>
<?php echo $this->Layout->adminTabs(); ?>
</ul>
<div id="role-main">
<?php
echo $this->Form->label('num_part', 'العدد : ');
echo $this->Form->input('num_part',array('label' => false ));
echo $this->Form->label('prix_part', 'االمبلغ : ');
echo $this->Form->input('prix_part',array('label' => false ));
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
echo $this->Form->input('prop_Pledge',array('label' => false ));
echo $this->Form->label('prix_Pledge', 'مبلغ التعهد : ');
echo $this->Form->input('prix_Pledge',array('label' => false ));
?>
</div>
<?php echo $this->Layout->adminTabs(); ?>
</div>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->end(__('Save'));
echo $this->Html->link(__('Cancel'), array(
'action' => 'index',
), array(
'class' => 'cancel',
));
?>
</div>
message error : The requested address was not found on this server.
I don't think it is because of Arabic language because when you do :
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
The second parameter is a text. I don't know which Cake version you're using but I think that the first field should be Part.prop_Pledge (Cake v3).
I suggest you to try to use debug() and exit to see where is the real problem or try to put remove arabic characters to see if this is the reason of you're problem.
Just a question where is your $this->Form->create() in view ?
line added to the database successfully but does not retoure to index
it displays an error message
Could you print the message error hello21 please ?
Hope this will help you.
In version 2.2.1 I could validate a form using rules and custom messages like below. But somehow the password rule isn't working as of version 2.3. Any help what I might be doing wrong here?
Model:
class User extends AppModel {
public $validate = array(
'password' => array(
'rule' => array ('between', 5, 10 ),
'message' => 'Password must between 5 and 10 characters long'
)
);
public function beforeSave($options = array()) {
$this->data['User']['password'] = Security::hash($this->data['User']['password'], 'sha1', true);
return true;
}
}
View:
<?php
echo $this->Form->create();
echo $this->Form->input('firstname', array('label' => 'First name'));
echo $this->Form->input('lastname', array('label' => 'Last name'));
echo $this->Form->input('adminrole', array('type' => 'checkbox', 'label' => 'Is admin?<br /><br />'));
echo $this->Form->input('email', array('label' => 'E-mail address'));
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->input('picturethumb', array('type' => 'file', 'label' => 'Profile picture'));
echo $this->Form->end('Save');
?>
Please bare in mind that this exact same code validates correctly in 2.2.1
Controller:
class UsersController extends AppController {
public function index() {
$users = $this->User->find('all');
$this->set('users', $users);
}
public function add() {
if ($this->request->is('post')) {
$this->User->save($this->request->data);
$this->redirect('/users');
}
}
}
Try this-
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if($this->User->save($this->request->data)){
$this->redirect('/users');
}else{
$this->Session->setFlash('Opps... Something is wrong');
}
}
}
I don't work with cake sometime, but I remember had this problem before. The problem is, the cakephp will create a hash of password, so when Model get password is already big. What I did in time was make another validate, like password_tmp and use it like field and create the hash by myself in controller for the real field password.
I'm using Lithium with MySQL.
I have a Users model that hasOne Contacts.
The Contacts model belongsTo Users.
I've listed a very basic version of my code, below.
My questions:
When I edit a user and submit the form, how do I make Users::edit save the Contact data, as well?
Also, how do I display contacts.email in the Users edit view?
models/Users.php
<?php
namespace app\models;
class Users extends \lithium\data\Model {
public $hasOne = array('Contacts');
protected $_schema = array(
'id' => array('type' => 'integer',
'key' => 'primary'),
'name' => array('type' => 'varchar')
);
}
?>
models/Contacts.php
<?php
namespace app\models;
class Contacts extends \lithium\data\Model {
public $belongsTo = array('Users');
protected $_meta = array(
'key' => 'user_id',
);
protected $_schema = array(
'user_id' => array('type' => 'integer',
'key' => 'primary'),
'email' => array('type' => 'string')
);
}
?>
controllers/UsersController.php
<?php
namespace app\controllers;
use app\models\Users;
class UsersController extends \lithium\action\Controller {
public function edit() {
$user = Users::find('first', array(
'conditions' => array('id' => $this->request->id),
'with' => array('Contacts')
)
);
if (!empty($this->request->data)) {
if ($user->save($this->request->data)) {
//flash success message goes here
return $this->redirect(array('Users::view', 'args' => array($user->id)));
} else {
//flash failure message goes here
}
}
return compact('user');
}
}
?>
views/users/edit.html.php
<?php $this->title('Editing User'); ?>
<h2>Editing User</h2>
<?= $this->form->create($user); ?>
<?= $this->form->field('name'); ?>
<?= $this->form->field('email', array('type' => 'email')); ?>
<?= $this->form->end(); ?>
Not many people know this but with lithium you can bind a form to multiple objects.
In your controller, return both a user and a contact object. Then in your form:
<?= $this->form->create(compact('user', 'contact')); ?>
You then render a field form a specific object like this:
<?= $this->form->field('user.name'); ?>
<?= $this->form->field('contact.email'); ?>
When the user submits the form, the data for both objects will be stored as:
$this->request->data['user'];
$this->request->data['contact'];
You can use this information to update the database as you would normally. If you only want to save the information if data from both objects are valid, you can call validate like this:
$user = Users::create($this->request->data['user']);
if($user->validates()) {
$userValid = true;
}
$contact = Contacts::create($this->request->data['contact']);
if($contact->validates()) {
$contactValid = true;
}
if($userValid && $userValid){
// save both objects
}
Hope that helps :)
My controller action is:
function add() {
if (!empty($this->data)) {
$this->Customer->create();
if ($this->Customer->save($this->data)) {
$this->Session->setFlash('A new Customer has been added');
$this->redirect(array('action'=>'index'));
}
else {
$this->Session->setFlash('The customer cannot be added this time. Try again later.');
$this->redirect(array('action'=>'index'));
}
}
}
My model is:
class Customer extends AppModel {
var $name = 'Customer';
var $validate = array(
'name' => array(
'length'=> array(
'rule' => array('between', 4,50),
'message' => 'Name must be minimum 4 and maximum 50 characters long.'
),
'checkUnique'=> array(
'rule' => 'isUnique',
'message' => 'This Name is already registered'
)
));
and this is my view:
<div class="customers form">
<?php echo $form->create('Customer',array('action'=>'add'));?>
<fieldset>
<legend><?php __('Add Customer');?></legend>
<?php
echo $form->input('Customer.name');
echo $form->input('Customer.balance',array('type'=>'hidden','default'=>0));
?>
</fieldset>
<?php echo $form->end('Submit');?>
</div>
every time I submit the form it splashes:
The customer cannot be added this time. Try again later.
For the hidden input field use 'value' instead of 'default' in your view:
$form->input('Customer.balance', array('type' => 'hidden', 'value' => 0));
Can anyone help me with a clear and complete example on how to set validations for 2 fields, say an email and password, with error messages?
From my understanding, the correct format is:
var $validate = array(
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
),
'email_id' => array('email')
);
but I can’t seem to get it work (show a validation message, or halt the execution of the action) in my tests.
Validations work fine but no way for the custom messages to appear!
EDIT
The validations and page redirections work fine now. Only the specific messages do not appear. That is, if I enter a password less than 8 characters, the message "minimum 8 characters needed" should appear immediately or after I click the register button. Is there any method to do this?
EDIT 2
My view file
<!-- File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Controller:
<?php
class UsersController extends AppController
{
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function register()
{
$userId=$this->User->registerUser($this->data);
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
function login()
{
$userId=$this->User->loginUser($this->data);
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
if($userId>0){
$this->Flash('Login Successful');
$this->redirect('/forms/homepage/'.$userId);
break;
}
else{
$this->flash('Username and password do not match.','/forms');
}
}
}
?>
Model:
<?php
class User extends AppModel {
var $name = 'User';
var $components=array('Auth');
var $validate = array(
'name' => array(
'rule' => VALID_NOT_EMPTY,
'message' =>'Name cannot be null.'
),
'password' => array(
'rule' => array('minLength', '6'),
'message' => 'Minimum 6 characters long.'
),
'email_id' => array(
'rule'=> array('email'),
'message'=>'Invalid email.'
)
);
function registerUser($data)
{
if (!empty($data))
{
$this->data['User']['name']=$data['User']['name'];
$this->data['User']['email_id']=$data['User']['email_id'];
$this->data['User']['password']=$data['User']['password'];
if($this->save($this->data))
{
$this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
function loginUser($data)
{
$this->data['User']['email_id']=$data['User']['email_id'];
$this->data['User']['password']=$data['User']['password'];
$login=$this->find('all');
foreach($login as $form):
if($this->data['User']['email_id']==$form['User']['email_id'] && $this->data['User']['password']==$form['User']['password'])
{
$this->data['User']['id']= $this->find('all',array('fields' => array('User.id'),
'conditions'=>array('User.email_id'=> $this->data['User']['email_id'],'User.password'=>$this->data['User']['password'])
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
}
?>
Here is a live example from my project..
This is how you set up your validation in your model: Article model
Ignore the fact that I'm initializing the validate array from constructor, you can keep doing it like you're doing it now if you don't plan on implementing I18n and L10n.
Handling validation errors in controller: Articles controller
From line 266 to 280 you can see validation and save errors being handled with setFlash() + return.
That's pretty much all you need to do, just don't forget you need to use the FormHelper for your forms for the messages to work as expected.
Common error: you must not do a $this->redirect() after failed validation.
Hopefully this will set you on the right track :)
Why dont you try $this->modelName->invalidFields(), which will return you an array with the fields that failed validation and the message to display.
http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller