cakephp create custompasswordhasher internal server error - php

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.

Related

How to update optional fields if not empty in CodeIgniter?

So I have this form in which a user can update his information:
The problem comes when some of these inputs are optional. Let's say a user updates his email and password, then the update updates but when a user only edits his email and leave the password inputs blank the password in the database should not be updated....it currently changes the password as well even when they're empty.
Here is my HTML:
<?php echo validation_errors('<p class="alert alert-dismissable alert-danger">'); ?>
<?php echo form_open('users/edit/'.$item->id); ?>
<div class="nav-tabs-custom">
<ul class="nav nav-tabs">
<li class="active">Basics</li>
<li class="">About Me</li>
</ul>
<br>
<div class="tab-content">
<!-- Basics -->
<div class="tab-pane active" id="basics">
<!-- Email -->
<div class="form-group">
<?php echo form_label('Email', 'email'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-envelope" aria-hidden="true"></i></div>
<?php
$data = array(
'name' => 'email',
'id' => 'email',
'maxlength' => '150',
'class' => 'form-control',
'value' => $item->email,
);
?>
<?php echo form_input($data); ?>
</div>
</div>
<!-- Avatar Image -->
<div class="form-group">
<?php echo form_label('Avatar Image URL', 'avatar_img'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-id-card-o" aria-hidden="true"></i></i></div>
<?php
$data = array(
'name' => 'avatar_img',
'id' => 'avatar_img',
'class' => 'form-control',
'placeholder' => '96x96 Pixels',
'value' => $item->avatar_img
);
?>
<?php echo form_input($data); ?>
</div>
</div>
<!-- Cover Image -->
<div class="form-group">
<?php echo form_label('Cover Img URL', 'cover_img'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-id-card-o" aria-hidden="true"></i></div>
<?php
$data = array(
'name' => 'cover_img',
'id' => 'cover_img',
'class' => 'form-control',
'value' => $item->cover_img
);
?>
<?php echo form_input($data); ?>
</div>
</div>
<!-- Occupation -->
<div class="form-group">
<?php echo form_label('Occupation', 'occupation'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-briefcase" aria-hidden="true"></i></div>
<?php
$data = array(
'name' => 'occupation',
'id' => 'occupation',
'class' => 'form-control',
'value' => $item->occupation
);
?>
<?php echo form_input($data); ?>
</div>
</div>
<!-- Website -->
<div class="form-group">
<?php echo form_label('Website', 'website'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-link" aria-hidden="true"></i></div>
<?php
$data = array(
'name' => 'website',
'id' => 'website',
'class' => 'form-control',
'value' => $item->website
);
?>
<?php echo form_input($data); ?>
</div>
</div>
<!-- Password -->
<div class="form-group">
<?php echo form_label('Password', 'password'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-lock" aria-hidden="true"></i></div>
<?php
$data = array(
'name' => 'password',
'id' => 'password',
'class' => 'form-control',
'value' => set_value('password'),
);
?>
<?php echo form_password($data); ?>
</div>
</div>
<!-- Password2 -->
<div class="form-group">
<?php echo form_label('Confirm Password', 'password2'); ?>
<div class="input-group date"><div class="input-group-addon"><i class="fa fa-lock" aria-hidden="true"></i></div>
<?php
$data = array(
'name' => 'password2',
'id' => 'password2',
'class' => 'form-control',
'value' => set_value('password2'),
);
?>
<?php echo form_password($data); ?>
</div>
</div>
</div>
</div>
</div>
<?php echo form_submit('mysubmit', 'Update User', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
and here is what I have tried:
<?php
$data = array(
'email' => $this->input->post('email'),
'avatar_img' => $this->input->post('avatar_img'),
'cover_img' => $this->input->post('cover_img'),
'occupation' => $this->input->post('occupation'),
'website' => $this->input->post('website'),
'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
'password2' => password_hash($this->input->post('password2'), PASSWORD_DEFAULT),
);
if($this->input->post('password') != ''){
$data['password'] = ($this->input->post('password') && !empty($this->input->post('password'))) ? $this->input->post('password') : NULL;
}
if($this->input->post('password2') != ''){
$data['password2'] = ($this->input->post('password2') && !empty($this->input->post('password2'))) ? $this->input->post('password2') : NULL;
}
// Update User
$this->User_model->update($id, $data);
?>
but it just don't work, so I tried making more simple:
<?php
$data = array(
'email' => $this->input->post('email'),
'avatar_img' => $this->input->post('avatar_img'),
'cover_img' => $this->input->post('cover_img'),
'occupation' => $this->input->post('occupation'),
'website' => $this->input->post('website'),
'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
'password2' => password_hash($this->input->post('password2'), PASSWORD_DEFAULT),
);
if($this->input->post('password') != ''){
$data['password2'] = password_hash($this->input->post('password2'), PASSWORD_DEFAULT);
}
if($this->input->post('password2') != ''){
$data['password2'] = password_hash($this->input->post('password2'), PASSWORD_DEFAULT);
}
// Update User
$this->User_model->update($id, $data);
?>
Update method in Userr model:
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update($this->table, $data);
}
Thanks in advance.
If you want the password(s) to be updated on database only if the password field(s) are NOT empty, do it like below:
<?php
$data = array(
'email' => $this->input->post('email'),
'avatar_img' => $this->input->post('avatar_img'),
'cover_img' => $this->input->post('cover_img'),
'occupation' => $this->input->post('occupation'),
'website' => $this->input->post('website')
);
if(trim($this->input->post('password')) != ''){
$data['password'] = password_hash(trim($this->input->post('password')), PASSWORD_DEFAULT);
}
if(trim($this->input->post('password2')) != ''){
$data['password2'] = password_hash(trim($this->input->post('password2')), PASSWORD_DEFAULT);
}
// Update User
$this->User_model->update($id, $data);
?>
I removed "password" and "password2" from first array list and kept in condition check. I added trim in case the fields have white-spaces in it.
I hope this will work!
edit this code.
$data = array(
'email' => $this->input->post('email'),
'avatar_img' => $this->input->post('avatar_img'),
'cover_img' => $this->input->post('cover_img'),
'occupation' => $this->input->post('occupation'),
'website' => $this->input->post('website'),
'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
'password2' => password_hash($this->input->post('password2'), PASSWORD_DEFAULT),
);
to
if(!empty($this->input->post('email'))){
$data['email'] = $this->input->post('email');
}
if(!empty($this->input->post('avatar_img'))){
$data['avatar_img'] = $this->input->post('avatar_img');
}
if(!empty($this->input->post('cover_img'))){
$data['cover_img'] = $this->input->post('cover_img');
}
if(!empty($this->input->post('occupation'))){
$data['occupation'] => $this->input->post('occupation');
}
if(!empty($this->input->post('website'))){
$data['website'] = $this->input->post('website');
}
if(!empty($this->input->post('password'))){
$data['password'] = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
}
if(!empty($this->input->post('password2'))){
$data['password2'] = password_hash($this->input->post('password2'), PASSWORD_DEFAULT);
}

Fetch and Update Data in same page CodeIgniter

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.

validation rules from config file doesnot set errors

I am trying to validate a form through config. When i submit blank input field,it just shoes same page. I needs errors displayed in add_article.php Help....
config/form_validation.php
<?php
$config = [
'add_article_rules' => [
[
'field' => 'title',
'label' => 'Article Title',
'rules' => 'required|alphadash'
],
[
'field' => 'body',
'label' => 'Article Body',
'rules' => 'required'
]
]
];
My Controller (admin.php)
<?php
class Admin extends MY_Controller{
public function __construct(){
parent::__construct();
if(! $this->session->userdata('user_id')){
return redirect('login');
}
}
public function dashboard(){
$this->load->model('articlesmodel','articles');
$articles= $this->articles->article_list();
$this->load->view('admin/dashboard',['articles'=>$articles]);
}
public function add_article(){
$this->load->view('admin/add_article');
}
public function store_article(){
$this->load->library('form_validation');
if($this->form_validation->run('add_article_rules')){
//if sucesss
}else{
return redirect('admin/add_article');
}
}
public function edit_select(){}
public function edit_article(){}
public function delete_article(){}
}
View file (add_article.php)
<?php require_once('admin_header.php'); ?>
<div class="container">
<?php echo validation_errors(); ?>
<div class="row">
<?php echo form_open('admin/store_article',['class'=>'form-horizontal']); ?>
<?php echo form_hidden('user_id', $this->session->userdata('user_id'));?>
<fieldset>
<legend>Add Article</legend>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="inputEmail" class="col-lg-4 control-label">Title</label>
<div class="col-lg-8">
<?php
$data = array(
'name' => 'title',
'class' => 'form-control',
'value' => set_value('title'),
'placeholder' => 'Username'
);
echo form_input($data);
?>
</div>
</div>
</div>
<div class="col-sm-6">
<?php echo form_error('title'); ?>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="inputPassword" class="col-lg-4 control-label">Article Body</label>
<div class="col-lg-8">
<?php
$data = array(
'name' => 'body',
'value' => set_value('body'),
'class' => 'form-control',
'placeholder' => 'Article Body',
);
echo form_textarea($data);
?>
</div>
</div>
</div>
<div class="col-sm-6">
<?php echo form_error('body'); ?>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<div class="col-lg-8 col-lg-offset-4">
<?php
$data = array(
'name' => 'reset',
'class' => 'btn btn-default',
'value' => 'Reset',
);
echo form_reset($data);
?>
<?php
$data = array(
'name' => 'submit',
'class' => 'btn btn-primary',
'value' => 'Submit',
);
echo form_submit($data);
?>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<?php require_once('admin_footer.php'); ?>
// Just Change Admin Controller method and view file
// View File in add_article.php
<?php echo form_open(); ?>
//Controller File
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
}
public function add_article()
{
if ($this->form_validation->run('add_article_rules')) {
echo "Success";
} else {
$this->load->view('admin/add_article');
}
}
public function edit_select()
{
}
public function edit_article()
{
}
public function delete_article()
{
}
}

cakephp auth login always false

I am working on a simple login application with cake.. Always return false.. why? My code
My AppController code is...
AppController.php
public $components = array(
'Session', 'RequestHandler', 'Auth', 'Email'
);
public $helpers = array(
'Session','Time','Text','Number'
);
public $titleForLayout = null;
public $currentUser = array();
public function beforeFilter() {
// Configurações específicas para cada prefixo
if ($this->isPrefix('operador')) {
$this->layout = 'admin';
} elseif ($this->isPrefix('user')) {
}
// Configurações de login
$this->_manageAuthConfigs();
$this->currentUser = $this->Auth->user();
$this->set('usuario',$this->Auth->user('nome'));
$this->set('id',$this->Auth->user('id'));
return parent::beforeFilter();
}
public function _forceSecure(){
$this->redirect('https://'.env('SERVER_NAME').env('REQUEST_URI'));
}
// Verifiy that is a prefix
protected function isPrefix($prefix)
{
$params = $this->request->params;
return isset($params['prefix']) && $params['prefix'] === $prefix;
}
private function _manageAuthConfigs() {
// $this->Auth->authError = 'Área restrita, identifique-se primeiro.';
$this->Auth->authorize = array('Controller');
$this->Auth->allow('index', 'info', 'enviar');
AuthComponent::$sessionKey = 'Auth.User';
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'index', 'user' => true);
$this->Auth->loginRedirect = array('controller' => 'Obras', 'action' => 'painel');
$this->Auth->logoutRedirect = array('controller' => 'Home', 'action' => 'index');
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'User',
'fields' => array('username' => 'email', 'password'=>'password'),
),
);
if ($this->isPrefix('operador')) {
$this->layout = 'admin';
AuthComponent::$sessionKey = 'Auth.Operador';
$this->Auth->loginAction = array('controller' => 'operadors', 'action' => 'login', 'operador' => true);
$this->Auth->loginRedirect = array('controller' => 'operadors', 'action' => 'Home');
$this->Auth->logoutRedirect = array('controller' => 'operadors', 'action' => 'index');
$this->Auth->deny();
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'Operador',
'fields' => array('username' => 'email', 'password'=>'password'),
),
);
//$this->Auth->allow('index', 'login', 'home');
}
}
public function isAuthorized($user = null)
{
return true;
}
My UsersController code is...
UsersController.php
public function index(){
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash('<b>Erro!</b> E-mail ou senha inválidos.', 'default', array('class'=>'alert alert-danger'), 'Operador.CCN');
}
}
}
View/User/index.ctp
<?php echo $this->Session->flash('bad');?>
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>E-mail</label>
<?php echo $this->Form->input('email', array('class'=>'form-control', 'label'=>false));?>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<a class="pull-right" id="headerRecover" href="#">Esqueci minha senha</a>
<label>Senha</label>
<?php echo $this->Form->input('password', array('class'=>'form-control', 'label'=>false));?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
<?php echo $this->Form->button(__('Login'), array('class'=>'btn btn-primary pull-right push-bottom')); ?>
</div>
</div>
</form>
</div>
</div>

Cakephp form never validates when it should

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));
}
}
}

Categories