I have simple program using cakephp3, when I try to directly put this into browser:
http://localhost/sample/users/edit/82
it directly goes to login page. Then after the login, my code still can edit the profile even that profile is not the current user login.
Below is my edit code
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
edit.ctp
<div class="actions columns large-2 medium-3">
<h3><?= __('Actions') ?></h3>
<ul class="side-nav">
<li><?= $this->Form->postLink(
__('Delete'),
['action' => 'delete', $user->id],
['confirm' => __('Are you sure you want to delete # {0}?',
$user->id)]
)
?></li>
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?>
</li>
</ul>
<div class="users form large-10 medium-9 columns">
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Edit User') ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
You have to check the existing user is trying to update his/her profile. You can do something like this.
All this on top of your edit method
public function edit($id = null)
{
$logged_user_id=$this->Auth->user('id');
if($logged_user_id==$id){
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
} else {
$this->Flash->error(__('You are not allowed to do this.'));
}
}
In my case and like ndm say, i don't use session, that's what i do (hope it helps):
public function edit($id = null)
{
if(!is_null($this->Auth->user())): // if the user is logged
if(is_null($id)) { $id = $this->Auth->user('id'); }
if($this->Auth->user()['group_id']<>1): // in my case group 1 is for the administrator group, i let them edit profile
$id = $this->Auth->user('id'); // in this case, if the user is not an administrator, id will always be his "user id"
endif;
endif;
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'edit', $id]);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
Related
Version: 4.2.9
My edit view is populating my inputs with the data, but when I change them and click on save, its not saving but giving me "user has been saved" message.
UsersController.php edit function
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => ['Userdata'],
]);
if ($this->request->is(['post', 'put'])) {
$user = $this->Users->get($id, [
'contain' => ['Userdata'],
]);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
}
my edit.php
<div class="users form large-9 medium-8 columns content">
<?php echo $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Edit User') ?></legend>
<?php
echo $this->Form->control('userdata.Email');
echo $this->Form->control('userdata.UserName');
echo $this->Form->control('PasswordHashed', ['type' => 'password']);
?>
</fieldset>
<?= $this->Form->button(__('save')) ?>
<?= $this->Form->end() ?>
</div>
Your update code is not complete, you have omitted the patchEntity method.
public function edit($id = null)
{
// call query only once
$user = $this->Users->get($id, [
'contain' => ['Userdata'],
]);
// Call the debug method just to test and understand your data
// debug($user);
// debug($this->getRequest()->getData()); // debug posted data
if ($this->request->is(['post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->getRequest()->getData());
// debug patched data debug($user); exit;
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
}
I want my url like this format http://localhost/blog/users/username instead of this http://localhost/blog/users/view/6
I have this code in Users view index.ctp
<?php foreach ($users as $user): ?>
<?= $this->Html->link(__('View Profile'), ['action' => 'view', $user['user']['slug']]) ?>
<?php endforeach; ?>
routes.php
<?php
$routes->connect('/user/*', array('controller' => 'users', 'action' => 'view'));
?>
//public function view($id = null)
public function view($username)
{
$users = $this->Users->get($username, [
'contain' => ['Subjects'] // i have relation
]);
$this->set('users', $users);
$this->set('_serialize', ['user']);
}
I tried this link but it not solved my problem
public function edit($id = null)
{
//$logged_user_id=$this->request->Session()->read('Auth.user.id');
$logged_user_id=$this->Auth->user('id');
if($logged_user_id==$id){
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('User profile successfuly updated.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
} else {
$this->Flash->error(__('You are not allowed to do this.'));
return $this->redirect(['action' => 'index']);
}
}
In index.ctp
<?php foreach ($users as $user): ?>
<?= $this->Html->link(__('View Profile'), ['action' => 'view', $user->username]) ?>
<?php endforeach; ?>
Please change $user->username as per your structure.
You don't have to do anything in your routs.php
the username will receive as an argument of the function view
function view($username){
//Your code
}
The get function uses the model's primary key field. It might be possible to change your primary key to username, but I suspect that will cause you other problems. Instead, try this:
$users = $this->Users->find('first')
->where(['username' => $username])
->contain(['Subjects']);
Also, is there a reason that your variable here is plural ($users)? You should only be getting a single user from this, right?
I have 2 models: User and UserInfo with relation 1-1 (One user have
one userinfo).
User(id) is primary key for User and UserInfo(user_id)
is both foreign key and primary key for UserInfo.
2 models have the same attribute: email, password.
I want to insert 'user_id', 'email', 'password' to UserInfo when add
new User.
But it seems can insert to UserInfo although User is successful saved.
I think it stop when ($this->User->UserInfos->save($userinfo)) run.
Anybody can help?
--Here is my code---
///**
* Add method
*
* #return void Redirects on successful add, renders view otherwise.
*/
public function add() {
$user = $this->Users->newEntity();
$userinfo = $this->Users->UserInfos->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
$userinfo = $this->Users->UserInfos->patchEntity($userinfo, [
'user_id' => $user['User']['id'],
'email' => $user['User']['email'],
'password' => $user['User']['password'],
]);
if ($this->User->UserInfos->save($userinfo)) {
$this->Flash->success(__('The userinfo has been saved.'));
}
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user', 'userinfo'));
$this->set('_serialize', ['user', 'userinfo']);
}
//Code in add.php
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Add User') ?></legend>
<?php
echo $this->Form->radio('user_type',
[
['value' => '0', 'text' => 'Personal'],
['value' => '1', 'text' => 'Company'],
]);
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->hidden('status', ['value' => '0']);
echo $this->Form->hidden('authority', ['value' => '0']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I think you may take the Bookmarker Tutorial as a reference because in the tutorial, new Tags are created while new Bookmarks is created. You can consider this as an idea of your UserInfo creation.
Well I am new to CakePHP too but have this idea for your case.
In your controller, controller\UserController, the action add() creates User entity:
public function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->User->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']); // same controller's index action, or you can set others
}
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
In your model, model\Table\UserTable.php, create a function called afterSave() which creates UserInfo after User entity is saved
$this->UserInfo->newEntity();
So inside newEntity(), you actually set some data which User doesn't have and UserInfo has, besides user_id (user_id should be set if you have already set up the associations of them)
I strongly recommend to follow all basic tutorials.
Remarks: I suggest you define model's name clearly as CakePHP conventions should be an important topic for CakePHP's developer. So for the above codes/filenames I typed, could be wrong if they don't match your case exactly. e.g. Users / Users / UsersInfo / UserInfo etc.
I have two tables Location and Car. What I want is, when I click on the picture of the car (View/Cars/view.ctp), redirect to the location add form (View/Locations/add.ctp) while keeping the ID of the car I've previously chosen.
LocationsController:
<?php
App::uses('AppController', 'Controller');
class LocationsController extends AppController {
public $components = array('Paginator', 'Session');
public $helpers = array(
'Js',
'GoogleMap'
);
public function index() {
$this->Location->recursive = 0;
$this->set('locations', $this->Paginator->paginate());
}
public function view($id = null) {
if (!$this->Location->exists($id)) {
throw new NotFoundException(__('Invalid location'));
}
$options = array('conditions' => array('Location.' . $this->Location->primaryKey => $id));
$this->set('location', $this->Location->find('first', $options));
}
public function add($car_id) {
if ($this->request->is('post')) {
$this->Location->create();
$this->set('car_id', $car_id);
if ($this->Location->save($this->request->data)) {
$this->Session->setFlash(__('The location has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The location could not be saved. Please, try again.'));
}
}
$users = $this->Location->User->find('list');
$agencies = $this->Location->Agency->find('list');
$cars = $this->Location->Car->find('list');
$this->set(compact('users', 'agencies', 'cars'));
}
public function edit($id = null) {
if (!$this->Location->exists($id)) {
throw new NotFoundException(__('Invalid location'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Location->save($this->request->data)) {
$this->Session->setFlash(__('The location has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The location could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Location.' . $this->Location->primaryKey => $id));
$this->request->data = $this->Location->find('first', $options);
}
$users = $this->Location->User->find('list');
$agencies = $this->Location->Agency->find('list');
$cars = $this->Location->Car->find('list');
$this->set(compact('users', 'agencies', 'cars'));
}
public function delete($id = null) {
$this->Location->id = $id;
if (!$this->Location->exists()) {
throw new NotFoundException(__('Invalid location'));
}
$this->request->allowMethod('post', 'delete');
if ($this->Location->delete()) {
$this->Session->setFlash(__('The location has been deleted.'));
} else {
$this->Session->setFlash(__('The location could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
public function admin_index() {
$this->Location->recursive = 0;
$this->set('locations', $this->Paginator->paginate());
}
public function admin_view($id = null) {
if (!$this->Location->exists($id)) {
throw new NotFoundException(__('Invalid location'));
}
$options = array('conditions' => array('Location.' . $this->Location->primaryKey => $id));
$this->set('location', $this->Location->find('first', $options));
}
public function admin_add() {
if ($this->request->is('post')) {
$this->Location->create();
if ($this->Location->save($this->request->data)) {
$this->Session->setFlash(__('The location has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The location could not be saved. Please, try again.'));
}
}
$users = $this->Location->User->find('list');
$agencies = $this->Location->Agency->find('list');
$cars = $this->Location->Car->find('list');
$this->set(compact('users', 'agencies', 'cars'));
}
public function admin_edit($id = null) {
if (!$this->Location->exists($id)) {
throw new NotFoundException(__('Invalid location'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Location->save($this->request->data)) {
$this->Session->setFlash(__('The location has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The location could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Location.' . $this->Location->primaryKey => $id));
$this->request->data = $this->Location->find('first', $options);
}
$users = $this->Location->User->find('list');
$agencies = $this->Location->Agency->find('list');
$cars = $this->Location->Car->find('list');
$this->set(compact('users', 'agencies', 'cars'));
}
public function admin_delete($id = null) {
$this->Location->id = $id;
if (!$this->Location->exists()) {
throw new NotFoundException(__('Invalid location'));
}
$this->request->allowMethod('post', 'delete');
if ($this->Location->delete()) {
$this->Session->setFlash(__('The location has been deleted.'));
} else {
$this->Session->setFlash(__('The location could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
and this CarsController
<?php
App::uses('AppController', 'Controller');
class CarsController extends AppController {
public $components = array('Paginator', 'Session');
public $helpers = array('Js', 'GoogleMap');
public function admin_index() {
$this->Car->recursive = 0;
$this->set('cars', $this->Paginator->paginate());
}
public function view($id = null){
if (!$this->Car->exists($id)) {
throw new NotFoundException(__('Invalid car'));
}
$options = array('conditions' => array('Car.' . $this->Car->primaryKey => $id));
$this->set('car', $this->Car->find('first', $options));
}
public function admin_view($id = null) {
if (!$this->Car->exists($id)) {
throw new NotFoundException(__('Invalid car'));
}
$options = array('conditions' => array('Car.' . $this->Car->primaryKey => $id));
$this->set('car', $this->Car->find('first', $options));
}
public function admin_add() {
if ($this->request->is('post')) {
$this->Car->create();
if ($this->Car->save($this->request->data)) {
$this->Session->setFlash(__('The car has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The car could not be saved. Please, try again.'));
}
}
$categories = $this->Car->Category->find('list');
$subcategories = $this->Car->Subcategory->find('list');
$this->set(compact('categories', 'subcategories'));
$this->set('categories', $this->Car->Subcategory->Category->find('list'));
}
public function admin_edit($id = null) {
if (!$this->Car->exists($id)) {
throw new NotFoundException(__('Invalid car'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Car->save($this->request->data)) {
$this->Session->setFlash(__('The car has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The car could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Car.' . $this->Car->primaryKey => $id));
$this->request->data = $this->Car->find('first', $options);
}
$categories = $this->Car->Category->find('list');
$subcategories = $this->Car->Subcategory->find('list');
$this->set(compact('categories', 'subcategories'));
}
public function admin_delete($id = null) {
$this->Car->id = $id;
if (!$this->Car->exists()) {
throw new NotFoundException(__('Invalid car'));
}
$this->request->allowMethod('post', 'delete');
if ($this->Car->delete()) {
$this->Session->setFlash(__('The car has been deleted.'));
} else {
$this->Session->setFlash(__('The car could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
public function index() {
$this->set('cars', $this->Car->find('all'));
}
}
and this is cars/view.ctp :
<div class="cars view">
<h2><?php echo __('Car'); ?></h2>
<?php
echo $this->Html->input("cars/car_id", array(
"alt" => "Cars",
'url' => array('controller' => 'locations', 'action' => 'add', 'car_id')
));
?>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($car['Car']['id']); ?>
</dd>
<dt><?php echo __('Title'); ?></dt>
<dd>
<?php echo h($car['Car']['title']); ?>
</dd>
<dt><?php echo __('Category'); ?></dt>
<dd>
<?php echo $this->Html->link($car['Category']['name'], array('controller' => 'categories', 'action' => 'view', $car['Category']['id'])); ?>
</dd>
<dt><?php echo __('Subcategory'); ?></dt>
<dd>
<?php echo $this->Html->link($car['Subcategory']['name'], array('controller' => 'subcategories', 'action' => 'view', $car['Subcategory']['id'])); ?>
</dd>
<dt><?php echo __('Color'); ?></dt>
<dd>
<?php echo h($car['Car']['color']); ?>
</dd>
<dt><?php echo __('Serial'); ?></dt>
<dd>
<?php echo h($car['Car']['serial']); ?>
</dd>
<dt><?php echo __('Model'); ?></dt>
<dd>
<?php echo h($car['Car']['model']); ?>
</dd>
<dt><?php echo __('Price'); ?></dt>
<dd>
<?php echo h($car['Car']['price']); ?>
</dd>
</dl>
</div>
<h5><?php echo $this->Html->link(__('Rent a Car'), array('controller'=>'locations','action' => 'add')); ?></h5>
and this locations/add.ctp :
<div class="locations form">
<?php echo $this->Form->create('Location'); ?>
<fieldset>
<legend><?php echo __('Add Location'); ?></legend>
<?php
echo $this->Form->input('status');
echo $this->Form->input('departure_date');
echo $this->Form->input('expected_return_date');
echo $this->Form->input('user_id');
echo $this->Form->input('agency_id');
echo $this->Form->input('car_id');
//echo $this->$Session->read('Auth.User.username');
//echo $this->$Session->read('Auth.Car.id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Locations'), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Users'), array('controller' => 'users', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New User'), array('controller' => 'users', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Agencies'), array('controller' => 'agencies', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Agency'), array('controller' => 'agencies', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Cars'), array('controller' => 'cars', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Car'), array('controller' => 'cars', 'action' => 'add')); ?> </li>
</ul>
</div>
Assuming you used the answer to the earlier question you posted you will have the car_id set correctly. All you now need to do is add it to your form in add.ctp correctly.
Replace:
echo $this->Form->input('car_id');
With
echo $this->Form->input('car_id', array('type'=>'hidden', 'value'=>$car_id));
Your form will then save the car_id correctly.
I'm using cake php for project, but i cannot edit the data i saved in the database. The edit function i used in the controller looks like below.
public function edit($id = null) {
if (!$this->Seller->exists($id)) {
throw new NotFoundException(__('Invalid seller'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Seller->save($this->request->data)) {
$this->Session->setFlash(__('The seller has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The seller could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Seller.' . $this->Seller->primaryKey => $id));
$this->request->data = $this->Seller->find('first', $options);
}
}
My edit.ctp file looks like below.
<div class="sellers form">
<?php echo $this->Form->create('Seller'); ?>
<fieldset>
<legend><?php echo __('Edit Seller'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('email');
echo $this->Form->input('phone_no');
echo $this->Form->input('address');
echo $this->Form->input('latitide');
echo $this->Form->input('longitude');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('product_type');
echo $this->Form->input('product_description');
echo $this->Form->input('approval');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('Seller.id')), array(), __('Are you sure you want to delete # %s?', $this->Form->value('Seller.id'))); ?></li>
<li><?php echo $this->Html->link(__('List Sellers'), array('action' => 'index')); ?></li>
</ul>
</div>
I can save and delete data in the database, but when i edit the saved data, saved changes are not getting saved. Please help me with this. Thanks in advance.
You need this :
$this->Seller->primaryKey= $id;
just before the first if .
edited - code working
public function edit($id = null) {
$this->Category->id = $id;
if (!$this->Category->exists()) {
throw new NotFoundException(__('Invalid category'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('Catégorie modifiée avec succès'),array('action' => 'index'));
} else {
$this->flash(__('Categorie pas modifiée...Réessayer Plus tard'),array('action' => 'index'));
}
} else {
$this->request->data = $this->Category->read(null, $id);
}
}
The reason you are able to add/delete, and not edit is because the primary key is not being submitted with the form. $id will only be there on initial page load, not when the form is submitted, since it then relies on the id being in $this->request->data. A good way to check if this is the case is to look in the database table you are saving to. If there is a new inserted record with the data you are trying to save, then this is it.
public function edit($id = null) {
$this->Seller->id = $id
if (!$this->Seller->exists($id)) {
throw new NotFoundException(__('Invalid seller'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Seller->save($this->request->data)) {
$this->Session->setFlash(__('The seller has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The seller could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->Seller->read(null, $id);
}
}
#may was correct, only he was referring to a different Model name than what you were using: it should be Seller not Category.
I would also change your find() call to use read() instead:
$this->request->data = $this->Seller->read(null, $id);