I made a little application with users and tasks in CakePHP.
In case of delete users I dont want delete them, just change value in database where is column 'status' from '1' to '0'. I dont know how to do it.
Code of Users Controller (Delete) :
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($user['status'] == '1') {
//Here should be code about change value
$this->Flash->success(__('The user has been deleted.'));
} else {
$this->Flash->error(__('The user could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
Any ideas?
If you have created model by following proper naming convention then you can try the code below.
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->saveField('status', 0);) {
$this->Flash->success(__('User deleted'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('User was not deleted'));
return $this->redirect(array('action' => 'index'));
}
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($user->status == 1) {
$user->status = 0;
$this->Users->save($user);
$this->Flash->success(__('The user has been deleted.'));
} else {
$this->Flash->error(__('The user could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
Related
I have more function where I need to read $data['getContacts'] more times, the code working correctly, but there is a clean and different method for call it?
thanks!
class AppController extends CI_Controller {
public $id;
function __construct() {
parent::__construct();
$this->id = !empty($this->input->post('id')) ? (int)$this->input->post('id', TRUE) : '';
}
public function restoreCredit()
{
$data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
if($data['getContacts']->status != false) :
$this->appmodel->restoreCredit($this->id);
endif;
}
public function createRandToken()
{
$data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
if(!empty($data['getContacts']) && $data['getContacts']->token == false):
$this->appmodel->setRandUserToken($this->id);
endif;
}
}
Your could define a function getContacts. It will fetch $contacts first time from the DB, after that it will always returned the fetched Contacts.
<?php
class AppController extends CI_Controller
{
public $id;
public $contacts;
function __construct()
{
parent::__construct();
$this->id = !empty($this->input->post('id')) ? (int) $this->input->post('id', TRUE) : '';
}
public function getContacts() {
if( !empty ( $this->contacts) ) { //If its populated return from here.
return $this->contacts;
}
$this->contacts = $this->appmodel->getContacts($this->id);
return $this->contacts;
}
public function restoreCredit()
{
$data['getContacts'] = $this->getContacts();
if ($data['getContacts']->status != false) :
$this->appmodel->restoreCredit($this->id);
endif;
}
public function createRandToken()
{
$data['getContacts'] = $this->getContacts();
if (!empty($data['getContacts']) && $data['getContacts']->token == false) :
$this->appmodel->setRandUserToken($this->id);
endif;
}
}
I have one-to-many Model relationship. While creating a new record, I can save as many rows as I want. But I want to add new row or delete saved row after Update operation. How would I do it?
Item Model
public function models() {
return $this->hasMany(Model::class, 'item_id');
}
Model Model
public function model()
{
return $this->belongsTo(Item::class, 'item_id');
}
Controller
Store
public function store(Request $request, Item $item)
{
$item = new Item;
$item->title = request('title');
if($item->save())
{
for ($i=0; $i < count(request('model_name')); ++$i)
{
$model = new Model;
$model->name = request('name')[$i];
$model->price = request('price')[$i];
}
return redirect()->back();
}
Update
public function update(Request $request, $id){
$item = Item::findOrFail($id);
$data = $request->all()
$models = Model::with(['model'])->where('item_id', $item->id)->get();
$i=0;
foreach($models as $new_model)
{
if (isset($model_name[$i])){
$new_model->sku = request('name')[$i];
$new_model->price= request('price')[$i];
$++i;
$shnp->models()->save($new_model);
}
}
$item->update($data);
}
Edit Form
Database Table
Sorry before, may I ask, when change password and forgot password, the new password is not fed stored in the database if my beforeSave function like this :
public function beforeSave($options = array()) {
if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey]) && isset($this->data[$this->alias]['password'])) { $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); } else {
unset($this->data[$this->alias]['password']);
}return true;}
But if the function of BeforeSave changed like this
public function beforeSave($options = array()) { $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);}}
the value of new password is success save to database, but when the user doing edit function and password left empty, password in database has hashing twice
please help me, thanks before
oh yaa, this is my changePassword function :
public function account(){
if(!$this->Session->check('Auth.User')){
$this->Session->setFlash(__('You must be logged in to view this page.'));
return $this->redirect(array('action' => 'login'));
}
//set user's ID in model which is needed for validation
$this->User->id = $this->Auth->user('id');
//load the user (avoid populating $this->data)
$current_user = $this->User->findById($this->User->id);
$this->set('current_user', $current_user);
$this->User->useValidationRules('ChangePassword');
$this->User->validate['re_password']['compare']['rule'] = array('equalToField', 'password', false);
$this->User->set($this->data);
if(!empty($this->data) && $this->User->validates()){
$password = $this->data['User']['password'];
$this->User->saveField('password', $password);
$this->Session->setFlash('Your password has been updated');
$this->redirect(array('action' => 'account'));
}
$this->layout = 'dashboard_admin';
}
Add new form field in edit form, instead of password, add new_password. It will be hashed only if user put somethin in there...
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')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Saved.', true));
$this->redirect(array('action' => 'view', $id));
} else {
$this->Session->setFlash(__('Error.', true));
}
} else {
$user = $this->User->read(null, $id);
$this->request->data = $user;
unset($this->request->data['User']['password']);
$this->set('user', $user);
}
public function beforeSave($options = array()) {
if (!empty($this->data['User']['new_password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['new_password']);
unset($this->data['User']['new_password']);
}
}
Use this only in case of edit (where user is not changing his password) and you should not show even hashed password to your user
if ($this->request->is('post') || $this->request->is('put')) {
unset($this->request->data['User']['password']);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Saved.', true));
$this->redirect(array('action' => 'view', $id));
} else {
$this->Session->setFlash(__('Error.', true));
}
}
I am struggling a lot with this problem.
My Model Code
class User extends AppModel {
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
$validate = array();
public function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
Controller's save method
public function register(){
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(
__('registration is successfully completed. you can login now.'),
'success',
array(),
'auth'
);
return $this->redirect(array('action' => 'login'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.'),
'error'
);
}
$this->layout = false;
}
Thank you.
I sorted this out my file name was incorrect.
4 I have an application that registers users to edit and write on a page.My problem is once the first user logs in all the other users seem not to need a valid password.In short it will only authenticate the first user.
The add action is used to registered new users,the blog action is the edit and posting page.I appreciate any help thanks.
Below are my codes;
<?php
class UsersController extends AppController {
public $helpers = array('Html', 'Form');
public $name='Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add','logout'); // Letting users register themselves
}
public function isAuthorized($user){
if (in_array($this->action, array('edit'))){
if($user['id'] != $this->request->params['pass'][0]){
return false;
}
}
return true;
}
public function login() {
if ($this->request->is('post')) {
debug($this->Auth->login());
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else{
$this->Session->setFlash(__('Invalid username or password'),'default', array(), 'auth');
}
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
public function users() {
}
public function index() {
$this->set('users', $this->User->find('all'));
}
public function view($id = NULL) {
$this->set('users', $this->User->read(NULL, $id));
}
public function edit() {
}
public function blog() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
return $this->redirect(array('action' => 'index'));
}
}
$this->Session->setFlash(__('really'));
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->request->data['User']['password'] ==$this->request->data['User'][ 'password_Confirmation'];
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}