I've noticed that their is many different ways to pass an ID to a form when editing a database entry. So for example for a edit user profile form I have the following code:
function edit($id = null)
{
$this->layout = 'page';
// this line isn't needed?
//$this->User->id = $id;
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your profile has been updated', 'flash', array('header' => 'Announcement', 'myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'view', $id));
}
}
}
Now the function expects an id passing in the url e.g. /users/edit/2 But let's say I wanted it to be something more user friendly like /profile/edit (rewrote by routing) I would no longer be passing in the ID as part of the url. As you can see in my code I have a line I have commented out because it isn't needed?
Also in the form I ALSO Need <?php echo $this->Form->input('id', array('type' => 'hidden')); ?> why?
Basically this is more of what are the options available to me to build various types of edit forms and passing data to the form. And what is the need for the hidden field in the form if the data is being passed either via the URL or some other way
I've also noticed on some sites that they have things like Form Keys and the username stored in meta tags in the page header???
EDIT:
public function beforeFilter()
{
$this->set('authUser', $this->Auth->user());
//
$user = $this->Auth->user();
if (!empty($user))
{
Configure::write('User', $user[$this->Auth->getModel()->alias]);
}
}
public function beforeRender()
{
$user = $this->Auth->user();
if (!empty($user))
{
$user = $user[$this->Auth->getModel()->alias];
}
$this->set(compact('user'));
}
// NEW VERSION
function settings()
{
$this->layout = 'page';
$this->set('title_for_layout', 'Edit Profile');
$this->User->id = $user['id'];
if (empty($this->data))
{
$this->data = $this->User->read();
}
else
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your settings have been updated', 'flash', array('myclass' => 'success'));
$this->redirect(array('controller' => 'users', 'action' => 'settings'));
}
}
}
Also in the form I ALSO Need Form->input('id',
array('type' => 'hidden')); ?> why?
Having the id hidden in the form removes the need for your controller action to grab the $id from the uri (aka passed as parameter). When in the form, it will automatically be placed into your $data array.
what is the need for the hidden field
in the form if the data is being
passed either via the URL or some
other way
It's not needed in the form if it's available from the uri. You'd simply grab the $id and assign it to the User model (as the commented out code does).
let's say I wanted it to be something
more user friendly like /profile/edit
I assume that would be when the user is editing his own profile. In that case, your system should be able to retrieve the user's id via the session.
Related
I try to find a good and clean way to deal with an admin panel "edit user" in cakePHP v.2.7.
To be clear : I want to be able to edit my user with or without overwriting their password, but the cakePHP validator tool don't let me do what I want...
I've already take a look at CakePHP: Edit Users without changing password and Updating user email and password with CakePHP but it seem really dirty :
the first one don't apply the rules onUpdate
the second display the hash (just no... u_u")
There is no other way to do it ? (with as few line as possible)
TL;DR :
View
// add in your view `app/View/Users/edit.ctp`
// a 'fake' field you'll only use on the controller
echo $this->Form->input('new_password');
Controller
// add in your controller `app/Model/User.php#edit()`
// if we have a new password, create key `password` in data
if(!empty($new_password = $this->request->data['User']['new_password']))
$this->request->data['User']['password'] = $new_password;
else // else, we remove the rules on password
$this->User->validator()->remove('password');
Ok, I finally get what I want, here is my code :
On your app/View/Users/edit.ctp you add a field to your form (a custom one, don't add it to your DB)
<?php
// app/View/Users/edit.ctp
echo $this->Form->create('User');
// your other fields
// a 'fake' field you'll only use on the controller
echo $this->Form->input('new_password');
Don't change your app/Model/User.php ; here is mine :
<?php
// app/Model/User.php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $validate = array(
// [...] other rules
'password' => array(
'passwordLength'=>array(
'rule' => array('minLength', 8),
'message' => 'Too short...',
),
'passwordNotBlank'=>array(
'rule' => 'notBlank',
'required' => true,
'allowEmpty' => false,
'message' => 'A password is required',
),
),
);
public function beforeSave($options = array()) {
if (!empty($pwd = $this->data[$this->alias]['password']))
$this->data[$this->alias]['password'] = AuthComponent::password($pwd);
return true;
}
}
And on your app/Controller/UsersController.php you use this :
<?php
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists())
throw new NotFoundException(__('Invalid user'));
if ($this->request->is('post') || $this->request->is('put')) {
// IMPORTANT >>>>>>>>>>>
// if we have a new password, create key `password` in data
if(!empty($new_password = $this->request->data['User']['new_password']))
$this->request->data['User']['password'] = $new_password;
else // else, we remove the rules on password
$this->User->validator()->remove('password');
// <<<<<<<<<<<<<<<<<<<<<
// then we try to save
if ($this->User->save($this->request->data)) {
$this->Flash->success(__('The user has been updated'));
$this->redirect(array('action' => 'index'));
}
else
$this->Flash->warning(__('The user could not be updated.'));
}
else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
}
With the 4 important lines, you are now able to set a new password if needed or disable the validation on the password.
I used this for reference
http://book.cakephp.org/2.0/en/models/data-validation.html#removing-rules-from-the-set
In Controller
public function add(){
$this->loadModel('User'); //load model
if($this->request->is('post')){
$filename=$this->User->checkFileUpload($this->request->data);
$this->User->set($this->request->data); //set data to model
if ($this->User->validates()){
$datas = array(
'User' => array(
'name' => $this->request->data['User']['name'],
'email'=>$this->request->data['User']['email'],
'password'=>$this->request->data['User']['password'],
'image'=>$filename
)
);
$pathToUpload= WWW_ROOT . 'upload/';
move_uploaded_file($this->request->data['User']['image']['tmp_name'],$pathToUpload.$filename);
// prepare the model for adding a new entry
$this->User->create();
// save the data
if($this->User->save($datas)){
//$this->Session->setFlash('User Information has been saved!');
return $this->Flash('User Information has been saved!',array('action' => 'index'));
//return $this->redirect(array('action' => 'index'));
}
} else {
$errors = $this->User->validationErrors; //handle errors
}
}
//$this->layout = NULL;
$this->viewpPath='Users';
$this->render('add');
}
In above code, i used flash() method to direct a user to a new page after an operation. This method showing the message but not redirecting in given url.
Please help me. What am i doing wrong here for redirecting with help of flash() method?
flash() does not redirect, it renders. It is very similar to the render() function, it will continue the execution of the script, unlike the redirect() function.
but if you still want to use this
you should use following in config file.
Configure::write('debug', 0);
Update
after add this into main.php use like
$this->flash(__("Some message for the user here..."), array("action" => "index"));
it'll work perfactly . Follow this forrefrence
Render != Redirect
If you need to redirect to the referer page you can use:
$this->redirect($this->referer());
if you want redirect to different controller:
$this->redirect(('controller' => 'YOURCONTROLLER', 'action' => 'YOURACTION'));
or if you want redirect to different action in same controller:
$this->redirect(('action' => 'YOURACTION'));
I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.
I am trying to create the "edit" profile page for a logged user in cakephp. This would be the function to add/edit information about the user.
I get an error during the $this->User->save($this->data) function and I don't understand what is the problem.
public function edit() {
$this->User->id = $this->Auth->User('id');
if ($this->request->is('post')) {
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The user has been saved'), 'flash_success');
// $this->redirect($this->Auth->redirect());
} else {
var_dump($this->invalidFields());
$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'flash_failure');
}
} else {
//autocompleto il form
$this->data = $this->User->read(null, $this->Auth->User('id'));
}
}
The view is:
<?php
echo $this->Form->create('User',array('action' => 'edit'));
echo $this->Form->input('name', array('label'=> 'Name'));
echo $this->Form->input('surname', array('label'=> 'Surname'));
echo $this->Form->input('id', array('type'=> 'hidden'));
echo $this->Form->end(__('Submit'));
?>
I see you use Auth component. If your Auth::authorize default value is overridden ensure that you give user proper rights to perform data writing (maybe he only allowed to read).
Another issue could be your $validate declaration in model, where you force user to enter field value (using 'required' = true) but actually this field is not even displayed on View. You could avoid this validation rule on data edit if 'on' => 'create' is defined inside.
Also I would recommend use CakePHP debug() instead of var_dump() for debugging purpose.
In my CakePHP application, I have setup the PersistantValidation plugin to validate my forms on the model level thanks to a kind previous suggestion. The plugin essentially makes it so that you can use model validation on a partial without having it redirect to the underlying page (ie. the register.ctp view or the login.ctp view, for example).
The validation works great for the login form, but it's not working properly on the user registration form for some reason.
The controller looks like this:
function register() {
if(!empty($this->data)) {
$name = $this->data['User']['name'];
$email = $this->data['User']['email'];
$password = $this->Password->generatePassword();
$this->data['User']['password'] = $this->Auth->password($password);
$this->User->create();
if($this->User->save($this->data)) {
$this->Session->setFlash(__('Your account has been created!', true));
$this->redirect(array('controller' => 'users', 'action' => 'offers'));
} else {
$this->redirect($this->referer());
}
}
}
The PresistentValidation component is also properly setup and included, since it works just fine in the login() function in the same controller. When I run this code, nothing happens. There is no redirect away from the partial, which is good, but the errors don't show up. Also, the errors do show up going to the register.ctp view, which means it isn't a problem with the validations themselves.
Does anyone have any ideas?
function register() {
if(!empty($this->data)) {
$this->data['User']['password'] = $this->Auth->password($password);
if($this->User->save($this->data)) {
$this->Session->setFlash(__('Your account has been created!', true));
$this->redirect(array('controller' => 'users', 'action' => 'offers'));
} else {
$this->redirect($this->referer());
}
}
}