I know this question has been asked many times but none of the answers are fixing my problem. First of all let me show where I have setFlash and echo $this->Session->flash().
This is my add function:
if(!empty($this->request->data))
{
$friend_id = $this->request->data['User']['id'];
$user_id = $this->Auth->User('id');
$already_friends = $this->Group->findByIdAndFriend($user_id, $friend_id);
if($already_friends)
{
$this->Session->setFlash(__('You are already friends', true));
}
else
{
$this->Group->create();
$data = array($user_id, $friend_id);
if($this->Group->save($data))
{
$this->Session->setFlash(__('You are now friends', true));
}
else {
$this->Session->setFlash(__('Failed to add friend. Please try again', true));
}
}
$this->redirect(array('action' => 'index'));
This is my layout, the necessary part of it:
<div id="header">
<?php echo $this->Html->image('connect.jpg', array('alt' => 'My Image', 'id' => 'headerImage')) ?>
<div id="headerNavMenu">
<div name="navTab" class="menuTab">
<?php echo $this->Html->link('Me', array('controller' => 'users', 'action' => 'view', CakeSession::read("Auth.User.id")), array('class' => 'tabName')) ?>
</div>
<div name="navTab" class="menuTab">
<?php echo $this->Html->link('My Schedule', array('controller' => 'newSchedules', 'action' => 'index'), array('class' => 'tabName')) ?>
</div>
<div name="navTab" class="menuTab">
<?php echo $this->Html->link('My Group', array('controller' => 'groups', 'action' => 'index'), array('class' => 'tabName')) ?>
</div>
<div name="navTab" class="menuTab">
Settings
</div>
</div>
<div id="login">
<?php echo CakeSession::read("Auth.User.firstName").' '.CakeSession::read("Auth.User.lastName").' ' ?>
<?php echo $this->Html->link('logout', array('controller' => 'users', 'action' => 'logout')) ?>
</div>
</div>
<div id="mainContent">
<?php echo $this->Session->flash(); ?>
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->fetch('content') ?>
</div>
</div>
Besides the fact that no flash messages show up, it also seems like the validation criteria is not being checked for models since specific messages don't show up either.
I am new at cakePHP but I have been following the blog tutorial to do most of my work. The flash messages used to work, but now it doesn't work for even models it used to.
Here are my validations:
public $validate = array(
'first_name' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'First Name cannot be blank',
'allowEmpty' => false,
'required' => true
)
),
'last_name' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'Last Name cannot be blank',
'allowEmpty' => false,
'required' => true
)
),
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Email cannot be blank',
'allowEmpty' => false,
'required' => true
),
'valid' => array(
'rule' => array('email', true),
'message' => 'This is not a valid email',
'required' => true
),
'unique' => array(
'rule' => array('isUnique'),
'message' => 'This email already exists',
'required' => true
)
),
'password' => array(
'required' => array(
'rule' => array('notempty'),
'message' => 'Password cannot be blank',
'allowEmpty' => false,
'required' => true
),
'valid' => array(
'rule' => array('minlength', 6),
'message' => 'Password has to be at least 6 characters',
'required' => true
),
'password_has_to_be_alphanumeric' => array(
'rule' => 'alphanumeric',
'message' => 'Password has to be alphanumeric',
'required' => true
)
)
);
I can't add comments so I have to answer, but in line 4 of your add function You should write user in lower case
$this->Auth->user('id');.
Theme check to have added Session component to your $components array in AppController
Related
Please anyone help me, Thanks in advance,I am new to Cakephp. I am using Cakephp 2.8.5 version. In my project I have a form where I am selecting user from a combobox. On selecting user, below text boxes with Course name and price text boxes will appear. This is done through jquery.
But my problem is how to insert username,course name and price into mysql database as example
column 1 | column2 | column 3
ragith ITIL Foundation, CAPM $200,$400
My view page is add_price.ctp
Inside this page where you will find
<div class="form-group" id="divprice">
</div> where the Course name and Price textboxes are displaying through jquery
My full view page as below
<head>
<?php echo $this->Html->script('jquery.js'); ?>
<script>
$(document).ready(function(){
$('#user').change(function(){
var nameIdVal = $(this).val();
$.ajax({
type: "POST",
url: '/invl_exams/userprice',
cache: "false",
data: {userid:nameIdVal},
success : function(result){
//alert(result);
$('#divprice').html(result);
}
});
});
});
// using Ajax serialize to insert into DB
$(document).ready(function(){
$('.btn').click(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: "/invl_exams/submitprice",
cache: "false",
data: $('#addPriceForm').serialize(),
dataType: "text",
success: function(strMessage){
//alert(strMessage);
//console.log(strMessage);
//$('#msg').html(strMessage);
},
error: function(strMessage){
//alert('error');
console.log('error');
}
});
clearData();
});
});
function clearData()
{
$('#addPriceForm :input').each(function(){
$(this).val('');
});
}
</script>
</head>
<body>
<div id="content">
<div class="col-md-3">
<div id="msg"></div>
<form class="form-horizontal" role="form" accept-charset="utf-8" method="post" id="ExamAddExamForm" action="/invl_exams/users/priceSubmit">
<div style="display:none;"><input type="hidden" value="POST" name="_method"></div>
<div class="form-group">
<label for="ExamUsername">Users</label>
<select class="form-control" required="required" id="user" name="data[Exam][userid][]">
<option value="">-- Select --</option>
<?php foreach($users as $username): ?>
<option value="<?php echo $username['users']['id']?>"><?php echo $username['users']['username']?>
</option>
<?php endforeach; ?>
</select>
<label id="ExamUsername-error" class="error" for="ExamUsername"></label>
</div>
<!--On selecting username showing the Courses with price textboxes in this id here -->
<div class="form-group" id="divprice">
</div>
<div class="form-group">
<button class="btn btn-default">Submit</button>
</div>
</form>
</div><br class="clearall">
</div>
</body>
routes.php
Router::connect('/userprice', array('controller' => 'users', 'action' => 'showprice'));
Router::connect('/submitprice', array('controller' => 'users', 'action' => 'price_submit'));
Controller Page is UsersController.php
<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController
{
public function showprice()
{
$this->loadModel('Exam');
$id = $_POST['userid'];
//echo $id;
//die();
if($id!=0)
{
$allPrice = $this->Exam->query("select * from exams where username = $id");
$total_price = $allPrice[0]['exams']['exam'];
$price = explode(',',$total_price);
//This table will be displayed after selecting the user from combobox
echo "<table class='tblrow' width='450px'>";
for($i=0;$i<count($price);$i++)
{
//echo $price[$i];
echo "<tr>";
echo "<td><b>Course:</b><input type='' name='course[]' value='$price[$i]'></td>";
echo "<td><b>Price:</b><input type='text' name='price[]' value=''></td>";
echo "</tr>";
echo "<tr><td> </td></tr>";
}
echo "</table>";
}
else
{
echo "No results found";
}
die();
}
// This function is for inserting into the Mysql database table
public function price_submit()
{
// print_r($_POST);
if(isset($_POST['data']))
{
$this->loadModel('Price');
$priceData = $_POST['data'];
$this->Price->create();
if($this->Price->save($priceData))
{
echo "Data added successfully";
}
}
$this->loadModel('User');
//$userData = $this->User->find('all');
$userData = $this->User->query("select * from users where id!= 15 and id!= 8");
$this->set('users',$userData);
}
}
Model page is User.ctp
<?php
//App::uses ('AppModel','Model');
class User extends AppModel{
public $validate = array(
'username' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Username is required'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken')
),
'password' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A password is required'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Password has already been taken')
),
'full_name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Full name is required'
)
),
/*'role' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Role is required'
)
) */
'email' => array(
array(
'rule' => array('email'),
'massage' => 'Please enter a valid email address',
),
),
'secondary_email' => array(
array(
'rule' => array('email'),
'massage' => 'Please enter a valid email address',
),
),
'phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Phone is required'
)
),
'secondary_phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Phone is required'
)
),
'location' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Loacation is required'
)
),
'business_name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Business Name is required'
)
),
'document' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Document is required'
)
),
'doc_file' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Document is required'
)
),
'pname' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Name is required'
)
),
'pemail' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Please enter a Valid Email Id'
)
),
'pOfc_phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Please enter a Phone Number'
)
),
'pdesignation' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Designation is Required'
)
),
);
}
?>
Here's the component declaration in AppController.php>
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'User',
'fields' => array('username' => 'email', 'password' => 'code'),
'scope' => array('activated' => true),
),
),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'loginRedirect' => array('controller' => 'members', 'action' => 'dashboard', 'admin' => true),
'authError' => 'No Permission',
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
'userScope' => array('User.activated' => true),
),
The login form:
<?= $this->Form->create('User', array('url' => '/users/login', 'class' => 'form-inline'));?>
<div class="form-group">
<?= $this->Form->input('User.email', array(
'div' => false,
'label' => false,
'placeholder' => 'е-пошта',
'class' => 'form-control',
'required' => true,
));?>
<?= $this->Form->input('User.code', array(
'div' => false,
'label' => false,
'placeholder' => 'сериски број',
'class' => 'form-control',
'required' => true,
));?>
<?= $this->Form->button('<i class="fa fa-user"></i>', array('type' => 'submit', 'class' => 'btn btn-primary', 'escape' => false));?>
</div>
<?= $this->Form->end();?>
And a snippet of the login function:
// ...
if($this->request->is('post')) {
if($this->Auth->login()) {
if(isset($this->request->data['User']['token']) && $this->request->data['User']['token']) {
$token = substr(md5(time()), 0, 32);
$this->User->id = $this->Auth->user('id');
$this->User->saveField('token', $token);
$this->Cookie->write('remember_me', $token, false, '1 week');
}
return $this->redirect($this->Auth->loginRedirect);
}
// ...
Now, when I use $this->Auth->login($this->request->data) or $this->Auth->login($this->request->data['User']), it works, but when I use only $this->Auth->login() it doesn't. I can do a workaround by logging in with $this->request->data and then putting the rest of the user data manually to be available afterwards, but I want to know why this happens. Any ideas?
EDIT
So, as Karthik Keyan mentioned hashing, i figured this was the problem. CakePHP was automatically hashing the password (code field) and I didn't want it to. So I made a custom hasher class named NoPasswordHasher as follows:
App::uses('AbstractPasswordHasher', 'Controller/Component/Auth');
class NoPasswordHasher extends AbstractPasswordHasher {
public function hash($password) {
return $password;
}
public function check($password, $hashedPassword) {
return $password == $hashedPassword;
}
}
and used it in the Auth component:
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'User',
'fields' => array('username' => 'email', 'password' => 'code'),
'scope' => array('activated' => true),
'passwordHasher' => 'No',
),
),
It works now. Thank you.
Tell what type of errors can be display for you.Please check can you store the password in HASH (salt) format.
does any one can give me a hint why me login doesn't work?
It is possible to add a user, also the Blowfish password is created and the dataset in in saved into the database, but i can not login.
MODEL
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
class Benutzer extends AppModel{
public $useTable = 'Benutzer';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'benötigtes Feld'
)
),
'passwort' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'benötigtes Feld'
)
),
'rolle' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'author', 'borrow', 'archive')),
'message' => 'Please enter a valid role',
'allowEmpty' => false)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['passwort'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data[$this->alias]['passwort'] = $passwordHasher->hash($this->data[$this->alias]['passwort']);
}
return true;
}
AppContorler
public $components = array(
'DebugKit.Toolbar',
'Session',
'Paginator' => array(
'className' => 'Bancha.BanchaPaginator'),
'Auth' => array(
'loginRedirect' => array(
'controller' => 'posts',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
'home'
),
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish'
)
),
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
the login
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
LOGIN ctp-File
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('Benutzer'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php echo $this->Form->input('username', array('lable' => 'Username', 'type' => 'text'));?>
<?php echo $this->Form->input('passwort', array('lable' => 'Passwort', 'type' => 'password'));?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
The problem was, that i haven't define the 'fields'
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username', //Default is 'username' in the userModel
'password' => 'passwort' //Default is 'password' in the userModel
)
Instead of my custom validation message being show upon submitting a form, the default "This field cannot be left blank" is being shown. Any ideas?
Here is my validation:
public $validate = array(
'id' => array(
'rule' => 'notEmpty'
),
'first_name' => array(
'rule' => 'notEmpty'
),
'last_name' => array(
'rule' => 'notEmpty'
),
'accused_of' => array(
'rule' => 'notEmpty'
),
'last_4_of_ssn' => array(
'rule' => '/^[0-9]{4}$/', // NEED TO DOUBLE CHECK THIS
'messsage' => 'Exactly 4 digits'
),
'date_of_accusation' => array(
'rule' => array('date', 'ymd'), // NEED TO DOUBLE CHECK THIS
'message' => 'Date must be in YYYY-MM-DD format.'
),
'monitoring' => array(
'rule' => 'notEmpty'
)
);
And here is my form:
echo $this->Form->create('Offender');
echo $this->Form->input('first_name', array('label' => 'First name:'));
echo $this->Form->input('last_name', array('label' => 'Last name:'));
echo $this->Form->input('accused_of', array('label' => 'Accused of:'));
echo $this->Form->input('monitoring', array('label' => 'Monitoring (enter as comma seperated list. ex: BAC, location):'));
echo $this->Form->input('last_4_of_ssn', array('label' => 'Last 4 digits of SSN:') );
echo $this->Form->input('date_of_accusation', array('label' => 'Date of accusation:'));
echo $this->Form->end('Save New Offender');
It appears for some fields you have not set any custom messages please go to this URL http://book.cakephp.org/2.0/en/models/data-validation.html
You can also create a custom validation for this purpose like in validation array do like this
'last_4_of_ssn' => array(
'rule' => array('digitValidate'),
'messsage' => 'Exactly 4 digits'
)
and in Model you can create a public function with the same name.
public function digitValidate() {
$pattern = '/^[0-9]{4}$/';
if (!preg_match($pattern,$this->data['last_4_of_ssn'])) {
return false;
}
return true;
}
I hope this will help you.
Validations are working but form is not getting submitted and data is not inserted:
addgroup.ctp:
echo $form->create('Group', array('url' => array('controller' => 'admin', 'action' =>'addgroup'), 'onSubmit' => 'return Validate()'));
echo $form->input('name',array('label' => false));
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/>
Group Model:
var $validate = array(
'name' => array(
'isRequired' => array(
'rule' => 'required',
'message' => 'Enter group name.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This group name has already been taken.'
),
),
);
in controller:
$this->Group->save($this->data,array('validate' => true)
If I make any empty entry or duplicate entry it gives errormessge,
but if I make valid entries then also form gives error-message,
What m I missing here?
you need to close the form $this->Form->end('Submit'); and the save function: $this->Group->save($this->data); It will validate when it saves.