Delete user not working - php

I want to be able to delete a user, but when I try to it throws the following error. "Error: The requested address '/cakephp/users/delete/8?url=users%2Fdelete%2F8' was not found on this server."
The code for my delete function is
public function delete($id = null)
{
debug($this->User->delete());
if (!$this->request->is('get'))
{
throw new MethodNotAllowedException();
}
if ($this->User->delete($id))
{
$this->Session->setFlash('The user with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'usermanage'));
}
}
[NEW]
I got rid of the usermanagement code and the index code to make room for my user model code..
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $primary_key = 'userID';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'name' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Your name is required'
)
),
'surname' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Your surname is required'
)
),
'memberType' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'responder', 'volunteer')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
),
'address1' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter your first line of address'
)
),
'address2' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your second line of address'
)
),
'town' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter your town'
)
),
'postCode' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your postcode'
)
),
'dob' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your date of birth'
)
),
'emailAddress' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your email address'
)
),
'phoneNumber' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your phone number'
)
),
'mobileNumber' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'please enter your mobile number'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
}
}
?>
Any help will be appreciated!

This error can be corrected in two ways (pickup one):
1 - Change your action delete to:
if (!$this->request->is('post') && !$this->request->is('put')) {
throw new MethodNotAllowedException();
}
2 - Not use postLink, and change delete action:
<?php echo $this->Html->link('Delete', array('controller' => 'users', 'action' => 'delete', $user['User']['userID'])); ?>
public function delete($id = null) {
$this->User->id = $id;
if(!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash('The user with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'usermanage'));
}
}
[EDIT]
For your primaryKey problem:
In User model:
public $primary_key = 'userID';
In Other models (belongsTo, hasMany, hasBelongsToMany):
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'userID'
)
);
Sorry for my english, I'm brazilian.

Related

Validation not working when updating fields with saveField

Insde the User Model
App::uses('SimplePasswordHasher','Controller/Component/Auth');
class User extends AppModel {
public $useTable = 'users';
public $hasMany = array(
'Reminder' => array(
'className' => 'Reminder'
)
);
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'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Username is already taken'
)
),
'password' => array(
'between' => array(
'rule' => array('between',5,10),
'message' => 'Between 5 to 10',
),
'compareFields' => array(
'rule' => array('compareFields','confirm_password'),
'message' => 'Passwords do not match',
'required' => 'update'
)
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please enter valid email address'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Email is already in use'
),
'compareFields' => array(
'rule' => array('compareFields','confirm_email'),
'message' => 'Emails do not match',
'required' => 'update'
)
),
'timezone' => array(
'isValid' => array(
'rule' => 'isValid',
'message' => 'Please select a timezone'
)
)
);
Inside the User Controller.
// Changed existing emails
if(!empty($this->request->data['User']['email'])) {
echo "Email is set <br/>";
$this->User->set($this->request->data['User']['email']);
if($this->User->validates(array('fieldList' => array('email')))) {
echo "Email is valid <br/>";
$this->User->id = $this->Session->read('Auth.User.id');
$this->User->saveField('email',$this->request->data['User']['email'],true);
$this->Session->setFlash("Settings updated");
}
}
// Change existing password
if(!empty($this->request->data['User']['password'])) {
echo "Password is set <br/>";
$this->User->set($this->request->data['User']['password']);
if($this->User->validates(array('fieldList' => array('password')))) {
echo "Password is valid <br/>";
$this->User->id = $this->Session->read('Auth.User.id');
$this->User->saveField('password', $this->request->data['User']['password'],true);
$this->Session->setFlash("Password changed");
}
}
I know 'saveField()' doesn't do validation automatically so I've set the validation parameter to true, but to no avail.
I've included the models containing the validations.
Any help would be appreciated.
Edited:
I actually ment that you had to do the validation like this:
$this->User->id = $this->Session->read('Auth.User.id');
if(!$this->User->saveField('password', 'asdf', true)) {
echo "Invalid.";
pr($this->User->invalidFields());
} else {
echo "Saved!";
}
or optionally, do this:
Just read() the data, overwrite the new password in that array, then $this->User->set() and use $this->User->validates() like you have.
See here.

CakePHP skipping validation for an input

I followed this post for password confirmation, but CakePHP seems to be skipping over my re_password validation settings.
Here's my form
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add Account'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('re_password', array('type'=>'password', 'label'=>'Re-Enter Password', 'value'=>''));
echo $this->Form->input('role', array('type' => 'hidden', 'default' => 'user'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This is in my User model
function equalToField($array, $field) {
return strcmp($this->data[$this->alias][key($array)], $this->data[$this->alias][$field]) == 0;
}
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('minLength', '3'),
'message' => 'A username with a minimum length of 3 characters is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken.'
)
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Please enter a valid email address.',
)
),
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'A password with a minimum length of 8 characters is required'
)
),
're_password' => array(
'required' => array(
'rule' => array('equalToField', 'password'),
'message' => 'Passwords do not match'
)
)
);
An error occurs if the minlength rule was triggered for the password field, but nothing ocurrs for the re_password field
I deleted the equalToField method just to see what would happen. I didn't even get an error so it seems as if re_password isn't even being looked at.
I'm not sure if this has anything to do with it, but when I added an additional rule to the password field regarding re_password, I got the following error: "Undefined index: re_password [APP/Model/User.php"
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'rule' => array('equalToField', 're_password'),
'message' => 'A password with a minimum length of 8 characters is required'
)
),
Also, in my UsersController action I printed(this->request->data) and the re_password field is set.
For CakePHP2 you can use something like this:
public $validate = array(
'password' => array(
'length' => array(
'rule' => array('minLength', '8'),
'message' => 'Password should have at least 8 chars.'
)
),
'password_confirmation' => array(
'length' => array(
'rule' => array('minLength', '8'),
'message' => 'Password should have at least 8 chars.'
),
'compare' => array(
'rule' => array('validate_passwords'),
'message' => 'Passwords are not same.',
)
),
);
public function validate_passwords() {
return $this->data[$this->alias]['password'] === $this->data[$this->alias]['password_confirmation'];
}
This is working for me, Try with this..
public $validate = array(
'password' => array(
'minLength' => array(
'rule' => array('minLength', 4),
'message' => 'Password must be at least 4 characters long'
),
'maxLength' => array(
'rule' => array('maxLength', 50),
'message' => 'Password cannot be longer than 50 characters'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a password'
)
),
'confirm_password' => array(
'passwordMatch' => array(
'rule' => array('identicalFieldValues', 'password'),
'message' => 'The two passwords you entered do not match, please try again'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Please confirm your password by entering it twice'
)
)
);

Cakephp Not validating data in Form

I am Trying to validate data from Form(.ctp file) in cakephp 2.3.8.
echo $this->Form->create('User').'<br />'.
$this->Form->input('handle', array(
'rule' => 'notEmpty',
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Username must be only letters and numbers, no special characters'
),
'between' => array(
'rule' => array('between', 4, 8),
'message' => 'Username must be between 4 and 8 characters',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username is already taken. Please choose a different one.'
))).'<br />'.
$this->Form->input('email',array(
'type'=>'text',
'placeholder'=>'Enter your E-mail',
'class'=>'form-control')).'<br />'.
$this->Form->input('password',array(
'type'=>'password',
'placeholder'=>'Enter your password',
'class'=>'form-control'));?>
This is my modle code
public function beforeSave($options = array()) {
parent::beforeSave($options = array());
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
$this->data['User']['token'] = Security::hash(mt_rand(),'md5',true);
$this->data['User']['resetkey'] = Security::hash(mt_rand(),'md5',true);
return true;
}
but when i singup, it not validating data and i don't know where i am mistaking
I have not seen validation rules in the view before, only in either the model or the controller. This may very well be an alternate method. Try moving validation code to the model.
class User extends AppModel {
public $validate = array(
'handle' => array(
'lengthCheck'=>array(
'rule'=>array('between', 4, 8),
'message'=>'The username must be between 4 and 8 characters.'
),
'isUnique'=>array(
'rule'=>'isUnique',
'message'=>'This username is already taken. Please choose a different one.'
),
'alphanumeric' => array(
'rule' => array('alphanumeric'),
'message' => 'Username must be only letters and numbers, no special characters',
),
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your username',
),
),
'password' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your password',
),
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Invalid email',
),
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please enter your email',
),
),
);
In your view
<?php
echo $this->Form->create('User');
echo $this->Form->input('handle', array(
'placeholder'=>'Enter your username',
'class'=>'form-control'
));
echo $this->Form->input('email', array(
'placeholder'=>'Enter your E-mail',
'class'=>'form-control'
));
echo $this->Form->input('password', array(
'placeholder'=>'Enter your password',
'class'=>'form-control'
));
?>
By default, it will recognize the password field as 'type' => 'password'

Looking for invalidFields() with CakePHP

I'm trying to find out how to get the actual message from my validate() array which contains all the rules to validate a submission within my model.
Basically I'm POSTing ajaxily and I'd like to return all of the error messages in the form that have failed validation, but it's sending them anyway even when they have passed validation.
So in my
SubmissionsController I'm doing this:
if ($this->request->is('ajax')) {
$formData = $this->Submission->invalidFields();
$this->set(compact('formData'));
}
In my Submission model I have:
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer (e.g. IJL John F. Kennedy donated his presidential salary to charity)'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'shortDescription' => array(
'rule' => array('shortDescription'),
'message' => 'Your description needs to be longer'
),
'longDescription' => array(
'rule' => array('longDescription'),
'message' => 'Your description needs to be shorter'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
'website' => array(
'rule' => 'url',
'message' => 'Enter a valid source URL (e.g. http://en.wikipedia.org/wiki/Penguins)'
),
),
'category' => array(
'category' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please choose a category'
)
)
);
In my Submissions/json/submit.ctp file I have:
<?php
$fragment = $this->element('errors/flash_error');
$toReturn = array(
'formData' => $formData
);
echo json_encode($toReturn);
If I enter in a valid title or any other valid field, I still am getting back the error message instead of nothing.
Is there something I'm missing that invalidFields() needs in order to NOT return fields which HAVE passed validation?
EDIT:
As Leo suggested below, I wasn't calling save before invalidFields()
The correct code should be:
if ($this->Submission->save($this->request->data)) {
$formData = null;
} else {
$formData = $this->Submission->invalidFields();
}
$this->set(compact('formData'));
You're calling invalidFields() without validation either by a save() call or validates()!

CakePHP: anyway to tell why Model->validates() returns false?

If Model->validates() returns false is there an easy way to know why?
I am trying to save some data but it will not save. As it turns out, it is not validating either. If I turn off validation it saves. I need to validate it though, but I can not tell why it is not validating?
I used this code:
if($this->User->create($user) && !$this->User->validates())
{
debug($user);
}
So if it doesn't validate it tells me what the data is.
It prints out this:
Array
(
[User] => Array
(
[first_name] => Tim
[last_name] => Zahn
[phone] => 8833323235
[email] => t#z.com
[password] => ert
)
[Confirm] => Array
(
[email] => t#z.com
[password] => ert
)
)
Which looks like it should be passing validation.
Also if needed I can post my Model source as well.
Update:
Here is the model. I am using the multivalidatable behavior. I have tried using the default and register validation sets:
class User extends AppModel
{
var $actsAs = array('Multivalidatable');
var $hasOne = 'WishList';
var $hasMany = array(
'Address' => array(
'conditions' => array('NOT' => array('Address.deleted' => '1')),
'order' => array('Address.is_billing DESC')
)
);
var $validate = array(
'first_name' => array(
'rule' => 'notEmpty'
),
'last_name' => array(
'rule' => 'notEmpty'
),
'password' => array(
'passRule1' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a password'
),
'passRule2' => array(
'rule' => array('identicalFieldValues', 'password'),
'message' => 'Passwords do not match'
)
),
'email' => array(
'emailRule1' => array(
'rule' => 'email',
'message' => 'You must specify a valid email address'
),
'emailRule3' => array(
'rule' => array('identicalFieldValues', 'email'),
'message' => 'Emails do not match'
)
)
);
var $validationSets = array(
'register' => array(
'first_name' => array(
'rule' => 'notEmpty'
),
'last_name' => array(
'rule' => 'notEmpty'
),
'password' => array(
'passRule1' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a password'
),
'passRule2' => array(
'rule' => array('identicalFieldValues', 'password'),
'message' => 'Passwords do not match'
)
),
'email' => array(
'emailRule1' => array(
'rule' => 'email',
'message' => 'You must specify a valid email address'
),
'emailRule2' => array(
'rule' => 'isUnique',
'message' => 'That email address is already in our system'
),
'emailRule3' => array(
'rule' => array('identicalFieldValues', 'email'),
'message' => 'Emails do not match'
)
)
),
'billing' => array(
'email' => array(
'emailRule1' => array(
'rule' => 'email',
'message' => 'You must specify a valid email address'
),
'emailRule3' => array(
'rule' => array('identicalFieldValues', 'email'),
'message' => 'Emails do not match'
)
)
)
);
public function beforeValidate()
{
parent::beforeValidate();
// if password is empty reset from hash to empty string
if (isset($this->data['User']['password']) && $this->data['User']['password'] == Security::hash('', null, true)) {
$this->data['User']['password'] = '';
}
return true;
}
function identicalFieldValues($field=array(), $compare_field=null)
{
foreach ($field as $key => $value)
{
$v1 = $value;
$v2 = $this->data["Confirm"][$compare_field];
if ($compare_field == 'password' && $v2 != '')
{
$v2 = Security::hash($v2, null, true);
}
if ($v1 !== $v2)
{
return false;
}
else
{
continue;
}
}
return true;
}
}
I'd start with something like this:
if($this->User->create($user) && !$this->User->validates())
{
debug($user);
debug($this->User->validationErrors);
}
That should tell you exactly which field or fields aren't passing validation and why.
Do you have a message set up in the validation so it can tell you where it is failing, for example:
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
Also, if you have AUTH on, it may be encrypting the password.
Also, you should assert validate BEFORE you attempt to create/save.

Categories