How to Edit User CakePHP 3 -
so i've been trying edit user functionality working in app, , i'm little confused how go doing cakephp 3. i've got edit action in userscontroller.php:
public function edit() { $this->layout = 'dashboard'; $user = $this->users->get($this->auth->user('id')); if ($this->request->is(['post', 'put'])) { $this->users->patchentity($user, $this->request->data); if ($this->users->save($user)) { $this->flash->success(__('your account has been edited')); return $this->redirect(['controller' => 'users', 'action' => 'edit']); } $this->flash->error(__('your account not edited. please fix errors below.')); } $this->set(compact('user')); }
and in edit.ctp file:
<?php $this->form->templates($form_templates['defaultbootstrap']); echo $this->form->create($user); ?> <fieldset> <legend><?php echo __('edit profile'); ?></legend> <?php echo $this->form->input('email', [ 'label' => __('email'), 'placeholder' => __('email'), 'autofocus' ]); echo $this->form->input('currency', [ 'label' => __('default currency'), 'options' => [ 'cad' => 'cad', 'usd' => 'usd' ] ]); echo $this->form->input('password', array( 'label' => __('password'), 'placeholder' => __('password'), 'value' => '' )); echo $this->form->input('confirm_password', array( 'label' => __('confirm password'), 'placeholder' => __('confirm password'), 'type' => 'password' )); ?> </fieldset> <?php echo $this->form->submit(__('edit')); echo $this->form->end(); ?>
the problem password gets attached form hashed, when use patchentity, gets hashed again, because of in entity user.php:
protected function _setpassword($password) { return (new defaultpasswordhasher)->hash($password); }
i've tried not grabbing password when set $user in controller. when use patchentity hashes blank value instead.
maybe i'm going entirely wrong way, i'm looking direction on how tackle if can out.
if need have ability change password in edit
form, you'll have make sure being dropped before being marshalled in case no data being provided.
this can achieved using model.beforemarshal
event in users
table class.
http://book.cakephp.org/3.0/en/orm/saving-data.html#before-marshal
public function beforemarshal(event $event, \arrayobject $data, \arrayobject $options) { if(isset($data['password']) && empty($data['password'])) { unset($data['password']); } }
this basic example, may want add more strict checks, maybe remove whitespaces before testing value being empty, etc
you separate editing profile data , editing credentials different actions/views/forms, , use fieldlist
option restrict fields can marshalled.
http://book.cakephp.org/3.0/en/orm/saving-data.html#avoiding-property-mass-assignment-attacks
edit profile:
$this->users->patchentity($user, $this->request->data, [ 'fieldlist' => ['currency'] ]);
edit credentials:
$this->users->patchentity($user, $this->request->data, [ 'fieldlist' => ['email', 'password'] ]);
Comments
Post a Comment