Ok, so I have validation somewhat working. It doesn't validate when it SHOULD, which seems to be the opposite of every problem I can find on google. I've tried copying the exact code from the CakePHP docs, but it doesn't seem to work. Maybe someone here can figure it out.
Model:
<?php
App::uses('AppModel', 'Model');
class User extends AppModel {
public $validate = array(
'email' => array(
'rule' => 'email',
'required' => true,
'allowEmpty' => false
),
'full_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false
),
'password' => array(
'rule' => array('minLength', 8),
'required' => true,
'allowEmpty' => false
)
);
}
?>
Controller:
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
function login() {
$this->layout = 'signin';
}
function signup() {
$this->layout = 'signin';
if($this->request->is('post')) {
$this->User->set($this->request->data);
if($this->User->validates())
$this->Session->setFlash('Validated!');
else
$this->Session->setFlash('Did not validate!' . print_r($this->User->validationErrors, true) . print_r($this->request->data, true));
}
}
}
?>
View:
<div class="placeholder text-center"><i class="fa fa-pencil"></i></div>
<?php echo $this->Session->flash(); ?>
<div class="panel panel-default col-sm-6 col-sm-offset-3">
<div class="panel-body">
<?php echo $this->Form->create('User'); ?>
<div class="form-group">
<?php echo $this->Form->input('full_name', array('placeholder' => 'Your full name', 'class' => 'form-control')); ?>
</div>
<div class="form-group">
<?php echo $this->Form->input('email', array('placeholder' => 'Enter email', 'class' => 'form-control')); ?>
</div>
<div class="form-group">
<?php echo $this->Form->input('password', array('placeholder' => 'Password', 'class' => 'form-control')); ?>
</div>
<div class="form-group">
<?php echo $this->Form->input('confirm_password', array('placeholder' => 'Retype Password', 'class' => 'form-control')); ?>
</div>
<button type="submit" class="btn btn-primary btn-block">Create Account</button>
<?php echo $this->Form->end(); ?>
</div>
</div>
Any help in the right direction is appreciated. I've always had issues with validation with CakePHP so I never used it before. Now it's required so I have no choice but to drudge through this until I get it working.
Oh, I should note that the data does go through. Here's the result of the print_r function:
Did not validate!Array ( [full_name] => Array ( [0] => This field
cannot be left blank ) [password] => Array ( [0] => This field cannot
be left blank ) ) Array ( [User] => Array ( [full_name] => Sean
Templeton [email] => sean#********.com [password] => ********
[confirm_password] => ******** ) )
Please go through this link. It explains how cakephp validations work.
http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
Updated:
Your fullname validation has 'rule'=> 'alphaNumeric' which does not include spaces. but if you check your data [full_name] => Sean Templeton which has a space in it.
You can set your own messages in the model. I don't think I need to say that.
Try this in your controller
function signup() {
$this->layout = 'signin';
if ($this->request->is('post')) {
$this->User->create($this->request->data); //"create" instead of "set"
if ($this->User->validates())
$this->Session->setFlash('Validated!');
else
$this->Session->setFlash('Did not validate!' . print_r($this->User->validationErrors, true) . print_r($this->request->data, true));
}
}
}
Related
I got stuck in a a problem in which I need to update some info from database in the same page that is shown.
On this case I'm fetching some "global settings" from a website in an index page which comes with a form in it. Here is a picture of it just to make it more clear to understand what I mean.
As you can see I created the button and I made it possible to see the values from the database, the problem is that I can not figure it out how to update it from there. Can somebody suggest an idea?
Here is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Settings extends Admin_Controller {
public function index()
{
$this->form_validation->set_rules('website_favicon', 'Favicon', 'trim|required|min_length[4]');
$this->form_validation->set_rules('website_logo', 'Logon', 'trim|required|min_length[4]');
$this->form_validation->set_rules('website_name', 'Website Name', 'trim|required|min_length[4]');
$this->form_validation->set_rules('website_credits', 'Credits', 'trim|required|min_length[4]');
$this->form_validation->set_rules('website_credits_link', 'Credits Link', 'trim|required|min_length[4]');
$this->form_validation->set_rules('website_copyright', 'Copyright', 'trim|required|min_length[4]');
if($this->form_validation->run() == FALSE){
// Get Current Subject
$data['item'] = $this->Settings_model->get_website_data();
//Load View Into Template
$this->template->load('admin', 'default', 'settings/index', $data);
} else {
// Create website settings
$data = array(
'website_favicon' => $this->input->post('website_favicon'),
'website_logo' => $this->input->post('website_logo'),
'website_name' => $this->input->post('webiste_name'),
'website_credits' => $this->input->post('website_credits'),
'website_credits_link' => $this->input->post('website_credits_link'),
'website_copyright' => $this->input->post('website_copyright'),
);
// Update User
$this->Settings_model->update($id, $data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'website settings',
'action' => 'updated',
'user_id' => $this->session->userdata('user_id'),
'message' => 'User (' . $data["username"] . ') updated the website settings'
);
// Add Activity
$this->Activity_model->add($data);
//Create Message
$this->session->set_flashdata('success', 'Website setting has been updated');
//Redirect to Users
redirect('admin/settings');
}
}
}
Here is my model:
<?php
class Settings_model extends CI_MODEL
{
function __construct()
{
parent::__construct();
$this->table = 'website_settings';
}
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update($this->table, $data);
}
public function get_website_data()
{
$this->db->select('*');
$this->db->from($this->table);
$this->db->where('id', 1);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->row();
} else {
return false;
}
}
}
and here is my view(index.php) with the form:
<h2 class="page-header">Website Settings</h2>
<?php if($this->session->flashdata('success')) : ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Alert!</h4>
<?php echo $this->session->flashdata('success') ?></div>
<?php endif; ?>
<?php if($this->session->flashdata('error')) : ?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
<?php echo $this->session->flashdata('error') ?></div>
<?php endif; ?>
<?php echo validation_errors('<p class="alert alert-danger">'); ?>
<?php echo form_open('admin/settings/index/'.$item->id); ?>
<!-- Website Favicon -->
<div class="form-group">
<?php echo form_label('Website Favicon', 'title'); ?>
<?php
$data = array(
'name' => 'website_favicon',
'id' => 'website_favicon',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_favicon
);
?>
<?php echo form_input($data); ?>
</div>
<!-- Website Logo -->
<div class="form-group">
<?php echo form_label('Website Logo', 'website_logo'); ?>
<?php
$data = array(
'name' => 'website_logo',
'id' => 'website_logo',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_logo
);
?>
<?php echo form_input($data); ?>
</div>
<!-- Website Name -->
<div class="form-group">
<?php echo form_label('Website Name', 'website_name'); ?>
<?php
$data = array(
'name' => 'website_name',
'id' => 'website_name',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_name
);
?>
<?php echo form_input($data); ?>
</div>
<!-- Website Credits -->
<div class="form-group">
<?php echo form_label('Website Credits to', 'website_credits'); ?>
<?php
$data = array(
'name' => 'website_credits',
'id' => 'website_credits',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_credits
);
?>
<?php echo form_input($data); ?>
</div>
<!-- Website Credits Link -->
<div class="form-group">
<?php echo form_label('Website Credits to Link', 'website_credits_link'); ?>
<?php
$data = array(
'name' => 'website_credits_link',
'id' => 'website_credits_link',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_credits_link
);
?>
<?php echo form_input($data); ?>
</div>
<!-- Website Copyright -->
<div class="form-group">
<?php echo form_label('Copyrights', 'website_copyright'); ?>
<?php
$data = array(
'name' => 'website_copyright',
'id' => 'website_copyright',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_copyright
);
?>
<?php echo form_input($data); ?>
</div>
<!-- Website First Ad -->
<div class="form-group">
<?php echo form_label('Ad One', 'website_first_ad'); ?>
<?php
$data = array(
'name' => 'website_first_ad',
'id' => 'website_first_ad',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_first_ad
);
?>
<?php echo form_textarea($data); ?>
</div>
<!-- Website Second Ad -->
<div class="form-group">
<?php echo form_label('Ad Two', 'website_second_ad'); ?>
<?php
$data = array(
'name' => 'website_second_ad',
'id' => 'website_second_ad',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_second_ad
);
?>
<?php echo form_textarea($data); ?>
</div>
<!-- Website Third Ad -->
<div class="form-group">
<?php echo form_label('Ad Three', 'website_third_ad'); ?>
<?php
$data = array(
'name' => 'website_third_ad',
'id' => 'website_third_ad',
'maxlength' => '100',
'class' => 'form-control',
'value' => $item->website_third_ad
);
?>
<?php echo form_textarea($data); ?>
</div>
<?php echo form_submit('mysubmit', 'Update Website', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
Thanks for helping.
Check if the data is posted thru the controller. then use set_value to your input fields to retain the values after submit
CONTROLLER
public function index(){
if($this->input->post()){
//set rules for form validation
if($this->form_validation->run() !== FALSE){
//then update
}
}
//your views, data or any other things you do
}
VIEW
echo form_input('name', set_value('name'));
On click of the button you can bind the ajax call to submit the data to the update action of the controller and you can handle response to show relevant message on the same page.
Sample ajax call
$.ajax({
url:'settings/update',//controller action
type:'POST',
dataType:'JSON',
data:{'data':data,'id':id},//form data you need to upate with the id
success:function(response) {
//show success message here
},
error:function(response) {
//show error message here
}
});
Hope this helps.
I want to create the custompasswordhasher for my cakephp project. the cakephp version is 2.5. I have follow the cakephp cook book and create the following custom class in directory Controller/Auth/CustomPasswordHasher.php
App::uses('AbstractPasswordHasher', 'Controller/Component/Auth');
class CustomPasswordHasher extends AbstractPasswordHasher {
public function hash($password) {
$hasher = md5(Configure::read('Security.salt') . $password . Configure::read('Security.cipherSeed'));
return $hasher;
}
public function check($password, $hashedPassword) {
//debug('PHPassHasher'); die('Using custom hasher'); //<--THIS NEVER HAPPENS!
$password = md5(Configure::read('Security.salt') . $password . Configure::read('Security.cipherSeed'));
echo $password."==".$hashedPassword;exit;
return password_verify($password, $hashedPassword);
}
}
and here is my login function in the controller
public function admin_login() {
if ($this->Auth->loggedIn()) {
return $this->redirect($this->Auth->redirect());
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Username or password is incorrect', 'error');
}
}
}
and in appController.php I config function
public function beforeFilter() {
if ($this->request->prefix == 'admin') {
$this->layout = 'admin';
AuthComponent::$sessionKey = 'Auth.User';
$this->Auth->loginAction = array('controller' => 'administrators', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'administrators', 'action' => 'dashboard');
$this->Auth->logoutRedirect = array('controller' => 'administrators', 'action' => 'login');
$this->Auth->authenticate = array(
'all' => array(
'scope' => array(
'User.is_active' => 1
)
),
'Form' => array(
'userModel' => 'User',
'passwordHasher' => array(
'className' => 'Auth/CustomPasswordHasher'
)
)
);
$this->Auth->allow('login');
} else {
/* do another stuff for user authentication */
}
}
And here is my login form.
<div class="login-box">
<div class="login-logo">Admin Login</div>
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<?php echo $this->Session->flash(); ?>
<?php echo $this->Form->create(); ?>
<div class="form-group has-feedback">
<?php
echo $this->Form->input('User.username',
array(
'label' => false,
'class' => 'form-control',
'placeholder' => 'Username',
'autocomplete' => 'off',
'autofocus' => true,
'value' => #$username
)
);
?>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<?php
echo $this->Form->input('User.password',
array(
'type' => 'password',
'label' => false,
'class' => 'form-control',
'placeholder' => 'Password',
'value' => #$password
)
);
?>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck ">
<label>
<input type="checkbox" name="data[Admin][remember_me]"> Remember Me </label>
</div>
</div>
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
</div>
<?php echo $this->Form->end(); ?>
I forgot my password<br>
</div>
</div>
how every when submit form. I got the stack trace
So everyone can you help me with this?
I call wrong className in my controller . it should be "Custom" not "CustompasswordHasher". Cake will automatic add that.
I am trying to build a section where we can add users with Role_ID=2
Role_ID is in some other table named as User_Details, and is linked with current user table id as foreign key.
Here is code for my UserController.php
function addUser(){
$this->set('setTab','addUser');
$this->set('parent_tab','Manage Users');
$this->set('tab','Add User');
// Super admin doesn't have an access of Manage user section
if($this->Session->read('User.access_rights') == 4){
$this->redirect('dashboard');
}
$this->layout = 'user';
$this->set('setTab','manageUsers');
$this->set('statusArray', $this->statusArray);
/*CREATE USER DROP DOWN ARRAY START*/
/*$userDrop['0']='Select Parent';
$getUsers = $this->User->generatetreelist('User.access_rights <> 4',null,'{n}.User.username','-');
if($getUsers) {
foreach ($getUsers as $key=>$value){
$userDrop[$key] = $value;
}
$this->set(compact('userDrop'));
}*/
/*CREATE USER DROP DOWN ARRAY END*/
if(!$this->Session->check('User')){
$this->redirect('login');
}
if($this->data){
$data = $this->data;
$this->User->set($data);
if ($this->User) {
// pr($this->data); die;
// because we like to send pretty mail
//Set view variables as normal
$this->set('userDetails', $data['User']);
//$this->User->recursive = 1;
if($this->User->saveAll($data)){
$this->Session->setFlash('User added successfully', 'default', array('class' => 'errMsgLogin'));
$this->redirect('manageUsers');
}
else {
echo "User not added";
}
}
else {
// do nothing
}
}
}//Ends here
Here is code for model user.php
<?php
class User extends AppModel{
var $name = "User";
var $validate = array(
'Username' => array(
'notempty' => array(
'rule' => array('notempty'),
'required' => false,
'message' => 'Username can not be empty!',
),
'maxLength'=> array(
'rule' => array('maxLength', 20),
'message' => 'Username can not be longer that 20 characters.'
)
),
'First_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'First name can not be empty!',
)
),
/*'phone' => array(
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'rule' => array('minLength', 10),
'message' => 'Phone number should be of 10 digits'
),*/
'Last_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Last name can not be empty!',
)
),
'Email_Id' => array(
'notempty' => array(
'rule' => array('email'),
'allowEmpty' => false,
'message' => 'Please Enter a valid Email Address'
)
)
/*'status'=> array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
'message' => 'Please Enter a Status'
)
),*/
);
Here is view code add_user.ctp
<h4 class="widgettitle">Add New User</h4>
<div class="widgetcontent">
<?php echo $this->Form->create('User',array('url'=>'addUser/', "enctype" => "multipart/form-data",'class'=>'stdform','id'=>'form1')); ?>
<div class="par control-group">
<label class="control-label" for="firstname">First Name*</label>
<div class="controls">
<?php echo $this->Form->input('First_Name',array('label'=>false, 'id'=>'firstname','class'=>'input-large')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastname">Last Name*</label>
<div class="controls">
<?php echo $this->Form->input('Last_Name',array('label'=>false,'id'=>'lastname','class'=>'input-large')); ?>
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Username*</label>
<div class="controls">
<?php echo $this->Form->input('Username',array('label'=>false,'id'=>'username','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="email">Email*</label>
<div class="controls">
<?php echo $this->Form->input('Email_Id',array('label'=>false,'id'=>'email','class'=>'input-xlarge')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="location">Office Phone*</label>
<div class="controls">
<?php echo $this->Form->input('User_Phone1',array('label'=>false, 'maxlength'=>false,'id'=>'phone','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="location">Cell Phone*</label>
<div class="controls">
<?php echo $this->Form->input('User_Phone2',array('label'=>false, 'maxlength'=>false,'id'=>'phone','class'=>'input-large')); ?>
</div>
</div>
<div class="par control-group">
<label class="control-label" for="status">Status</label>
<div class="controls">
<?php echo $this->Form->input('Is_Active',array('type'=>'select', 'width' => 100, 'options'=>$statusArray, 'label' => false, 'class'=>'input-large')); ?>
</div>
</div>
<p class="stdformbutton">
<button class="btn btn-primary">Save</button>
</p>
<?php echo $this->Form->end(); ?>
</div><!--widgetcontent-->
After adding:
$this->User->bindModel(array('belongsTo'=>array('UserDetail'=>array('className' => 'UserDetail', 'foreignKey' => 'Role_ID', ))));
Got Error in query:
SQL Query: SELECT `User`.`User_ID`, `User`.`First_Name`, `User`.`Last_Name`, `User`.`Email_Id`, `User`.`Username`, `User`.`User_Password`, `User`.`User_Phone1`, `User`.`User_Phone2`, `User`.`Created_By`, `User`.`Created_Date`, `User`.`Is_Active`, `User`.`Is_Deleted`, `UserDetail`.`User_Detail_ID`, `UserDetail`.`User_ID`, `UserDetail`.`Role_ID`, `UserDetail`.`Unit_ID`, `UserDetail`.`Rank_ID`, `UserDetail`.`City_ID`, `UserDetail`.`State_ID`, `UserDetail`.`RSID`, `UserDetail`.`User_Address1`, `UserDetail`.`User_Address2`, `UserDetail`.`Zip_Code`, `UserDetail`.`User_Url`, `UserDetail`.`Created_By`, `UserDetail`.`Created_Date`, `UserDetail`.`Is_Active`, `UserDetail`.`Is_Deleted` FROM `national`.`users` AS `User` LEFT JOIN `national`.`user_details` AS `UserDetail` ON (`User`.`Role_ID` = `UserDetail`.`id`) WHERE 1 = 1 ORDER BY `User`.`User_ID` DESC
Any suggestions on how can I build this?
Please update User model Code :-
User Model User.php
<?php
class User extends AppModel{
var $name = "User";
/**
* Model associations: hasOne
*
* #var array
* #access public
*/
public $hasOne = array(
'UserDetail'
);
var $validate = array(
'Username' => array(
'notempty' => array(
'rule' => array('notempty'),
'required' => false,
'message' => 'Username can not be empty!',
),
'maxLength'=> array(
'rule' => array('maxLength', 20),
'message' => 'Username can not be longer that 20 characters.'
)
),
'First_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'First name can not be empty!',
)
),
/*'phone' => array(
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'rule' => array('minLength', 10),
'message' => 'Phone number should be of 10 digits'
),*/
'Last_Name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Last name can not be empty!',
)
),
'Email_Id' => array(
'notempty' => array(
'rule' => array('email'),
'allowEmpty' => false,
'message' => 'Please Enter a valid Email Address'
)
)
/*'status'=> array(
'notempty' => array(
'rule' => array('notEmpty'),
'allowEmpty' => false,
'message' => 'Please Enter a Status'
)
),*/
);
}
Then update controller code
Here is code for UserController.php
function addUser(){
$this->set('setTab','addUser');
$this->set('parent_tab','Manage Users');
$this->set('tab','Add User');
// Super admin doesn't have an access of Manage user section
if($this->Session->read('User.access_rights') == 4){
$this->redirect('dashboard');
}
$this->layout = 'user';
$this->set('setTab','manageUsers');
$this->set('statusArray', $this->statusArray);
/*CREATE USER DROP DOWN ARRAY START*/
/*$userDrop['0']='Select Parent';
$getUsers = $this->User->generatetreelist('User.access_rights <> 4',null,'{n}.User.username','-');
if($getUsers) {
foreach ($getUsers as $key=>$value){
$userDrop[$key] = $value;
}
$this->set(compact('userDrop'));
}*/
/*CREATE USER DROP DOWN ARRAY END*/
if(!$this->Session->check('User')){
$this->redirect('login');
}
if($this->data){
$data = $this->data;
$this->User->set($data);
if ($this->User) {
// pr($this->data); die;
// because we like to send pretty mail
//Set view variables as normal
$this->set('userDetails', $data['User']);
//$this->User->recursive = 1;
$data['UserDetail']['Role_ID'] = 2;
if($this->User->saveAll($data)){
$this->Session->setFlash('User added successfully', 'default', array('class' => 'errMsgLogin'));
$this->redirect('manageUsers');
}
else {
echo "User not added";
}
}
else {
// do nothing
}
}
}//Ends here
You can use bindModel functionality for associate or link two table like this
$this->User->bindModel(array('belongsTo'=>array('UserDetail'=>array('className' => 'UserDetail',
'foreignKey' => 'Role_ID',
))));
Now when you find the data of User table than it show the userdetail data also.
You can also use containable behaviour if you want particular field of userdetail model
First check table name of userdetail if your table name like userdetails than you can use class name in bindModel like this Userdetails
if you use the table name like this user_details than put class name like this UserDetails .Can You give a function where you find the user data and use bind model function in particular function .Model should be loaded
Please check table name
It's my form class:
<?php
class Application_Form_Message extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->addElement(
'text',
'email',
array(
'label' => 'E-mail',
'filters' => array('StringTrim'),
'class' => 'size-large-big',
'required' => true
)
);
$this->addElement(
'text',
'subject',
array(
'label' => 'Subject',
'filters' => array('StringTrim'),
'class' => 'size-large-big',
'required' => true
)
);
$this->addElement(
'textarea',
'content',
array(
'label' => 'Content',
'filters' => array('StringTrim'),
'class' => 'size-large-big',
'required' => true
)
);
$this->addElement(
'file',
'file',
array(
'label' => 'Attachments',
'filters' => array('StringTrim'),
'class' => 'size-large-big',
'isArray' => true,
'required' => false,
'allowEmpty' => true,
'style' => 'display: inline;'
)
);
$this->file->setDestination(realpath(APPLICATION_PATH . '/../public/uploads'))
->addValidator('Extension', false, 'png, jpg, jpeg', 'pdf', 'doc', 'docx');
$this->file->getValidator('Upload')->setMessages(array(
Zend_Validate_File_Upload::NO_FILE => 'Empty filename',
));
$this->addElement(
'submit',
'submit',
array(
'ignore' => true,
'label' => 'Send',
'class' => 'btn'
)
);
}
}
My view:
<div class="container" >
<section class="main">
<form action="<?php echo $this->form->getAction(); ?>" method="<?php echo $this->form->getMethod(); ?>">
<ul class="form-inputs login">
<h2>Message</h2>
<p><?php echo $this->page->content; ?></p>
<li>
<?php echo $this->form->email->renderLabel(); ?>
<?php echo $this->form->email->renderViewHelper(); ?>
</li>
<li>
<?php echo $this->form->subject->renderLabel(); ?>
<?php echo $this->form->subject->renderViewHelper(); ?>
</li>
<li>
<?php echo $this->form->content->renderLabel(); ?>
<?php echo $this->form->content->renderViewHelper(); ?>
</li>
<li>
<?php echo $this->form->file->renderLabel(); ?>
<?php echo $this->form->file->renderFile(); ?>
</li>
<li>
<?php echo $this->form->submit->renderViewHelper(); ?>
</li>
</ul>
</form>
</section>
</div>
The problem is that form isn't valid, even if I fill all inputs and add one file.
print_r($form->getMessages()); //error messages
print_r($form->getErrors()); //error codes
print_r($form->getErrorMessages()); //any custom error messages
Controller:
public function newAction()
{
$page = new Application_Model_DbTable_Page();
$form = new Application_Form_Message();
if($this->getRequest()->isPost())
{
if ($form->isValid($this->getRequest()->getPost()))
{
$data = $form->getValues();
die('its ok');
$this->_sendComplaint($data['subject'], $data['content'], $data['email']);
}
else
{
print_r($form->getMessages()); //error messages
print_r($form->getErrors()); //error codes
print_r($form->getErrorMessages()); //any custom error messages
}
}
else
$form->email->setValue($this->view->userDetails->email);
$this->view->page = $page->getPageBySlug('message');
$this->view->form = $form;
$this->view->pageName = 'Message';
}
return me nothing, just empty arrays: Array ( ) Array ( [email] => Array ( ) [subject] => Array ( ) [content] => Array ( ) [file] => Array ( ) [submit] => Array ( ) ) Array ( )
Thanks for help.
I found the problem myself, it was that the enctype="multipart/form-data" attribute was missing in the form tag.
How do I show the messages when using the CakePHP validation? As I creating the input fields manually using input() instead using the shorthand form() helper.
e.g. Form:
<?php echo $this->Form->create('User', array('id' => 'loginform', 'type' => 'post',
'url' => array('controller' => 'users', 'action' => 'login'))); ?>
<fieldset id="login">
<ul class="clearfix">
<li id="li-username">
<?php echo $this->Form->input('email', array( 'label' => array('class' => 'placeholder', 'text' => 'Email address or username') )); ?>
</li>
<li id="li-password">
<?php echo $this->Form->input('password', array( 'type' => 'password', 'label' => array('class' => 'placeholder', 'text' => 'Password') )); ?>
<span id="iforgot"><?php echo $this->Html->link('?',
array('controller' => 'users', 'action' => 'forgotpassword'), array('title' => 'Forgot your password?')); ?></span>
</li>
<li id="li-submit">
<button type="submit" title="Log in">Log in ►</button>
</li>
</ul>
</fieldset>
<?php echo $this->Form->end(); ?>
and this is my validation in the user model:
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'email',
'message' => 'The email is not valid'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter an email'
)
)
);
However the validation error messages don't show?
EDIT:
I tested this on my register form at /users/add/ and it works so it seems that the auto validation does not work with the login method???? How do I add validation for the login form then :/
The validation is actually stored in the model object. I'm not entirely sure off-hand how to access the errors, but I think its in $this->User->validationErrors.
Have a look at the model api for more information.
For logging in, use the auth component. If you'd rather not, then just get the user from the db and display an error using $this->Session->SetFlash() if the user doesn't authenticate.
You can show your code login function?
I think in your code that have redirect in-case validate false
If you use $this->redirect() it'll not show validate messages :)
First you check your post data is going to validate function.you can simple check this in your else condition like this :
$this->{$this->modelClass}->set($this->data);
if($this->{$this->modelClass}->validates(){
//Save data in DB
}else{
pr($this->{$this->modelClass}->validationErrors); // This will show your error message
}
You can also show error in your view.ctp file like this
$errors = '';
foreach ($this->validationErrors[$model] as $key => $validationError) {
$errors .= $this->Html->tag('li', $validationError[0]);
}
echo $this->Html->tag('ul', $errors,array('class' => 'error'));