Changing single variable value in AppController - cakephp

I have a Horse object that has a completed variable (text). I want to be able to click set complete in the View and then have that horse's completed variable set to "yes." After this, we would redirect the user to tasks/index. My thinking is to create setcomplete($id) function in Controller, so I could pass /setcomplete/4 and that horse's flag would change.
I have created a basic view for it, but the idea is that I would not need a view, but I do not know how to get around that....I was thinking of using $this->render() or something of this nature.
This is the basic code...pass in the id and then change the variable, then redirect to tasks/index.
I am not getting an error....its just not working, that's all.
public function setcomplete($id = null) {
if (!$this->Task->exists($id)) {
throw new NotFoundException(__('Invalid task'));
}
if ($this->request->is(array('post', 'put'))) {
$this->set('completed', 'yes');
if ($this->Task->save($this->request->data)) {
$this->Session->setFlash(__('The task has been updated.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The task could not be saved. Please, try again.'));
}
} else {
}
}

According to my understanding of your problem. you want to set the completed to yes for Task model.
i think you've done in a wrong way here.
what about the $this->request->data here?
Does it contain the data you want to save for the task model like the structure as below
Array(
'Task' => Array(
'id' => 4, // for eg..
'completed' => 'yes'
)
)
if not
you can solve the problem by doing like this. [Assuming you don't have $this->request->data]
public function setcomplete($id = null) {
if (!$this->Task->exists($id)) {
throw new NotFoundException(__('Invalid task'));
}
$this->Task->id = $id;
$this->Task->set('completed', 'yes')
if ($this->Task->save()) {
$this->Session->setFlash(__('The task has been updated.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The task could not be saved. Please, try again.'));
}
}

Related

Failure to Update record CakePHP

I am currently trying to update my user before sending an email which will have a confirm link with a resetkey for the user to reset the password.
The problem is that the user is not updating whilst the key is being generated.
the code can be seen hereunder
public function forgotpassword() {
if ($this->request->is('post')) {
$mail = $this->request->data['ContactDetail']['email'];
$data = $this->User->find('first', array('conditions' => array('ContactDetail.email' => $mail)));
if (!$data) {
$message = __('No Such E-mail address registerd with us ');
$this->Session->setFlash($message);
} else {
$data['User']['resetkey'] = Security::hash(mt_rand(),'md5',true);
debug($data);
if ($this->User->saveAssociated($data)) {
$this->Session->setFlash(__('The user has been saved.'));
}
else {
$this->Session->setFlash(__('The user could not be updated. Please, try again.'));
}
$key = $data['User']['resetkey'];
$id = $data['User']['id'];
$mail = $data['ContactDetail']['email'];
$email = new CakeEmail('default');
$email->to($mail);
$email->from("xxxx#yahoo.com");
$email->emailFormat('html');
$email->subject('Password reset instructions from');
$email->viewVars(array('key' => $key, 'id' => $id, 'rand' => mt_rand()));
$email->template('reset');
if ($email->send('reset')) {
$message = __('Please check your email for reset instructions.');
$this->Session->setFlash($message);
} else {
$message = __('Something went wrong with activation mail. Please try later.');
$this->Session->setFlash($message);
}
}
$this->redirect('/');
}
}
I checked the execution log of MySQL but all I am seeing are selects no updates or even inserts.
This is probably something very dumb but I can't understand why it doesn't say anything.
Why do you use saveAssociated method for update single field?
Something like this would be easier:
$this->User->updateAll(
array( 'User.resetkey' => $hash ),
array( 'User.id' => $userId )
);
try using
$this->User->saveMany($data, array('deep' => true));
When saving. Also
if (empty($data)) {...
Might be a safer way to go
This will work for you-
$this->User->id = $data['User']['id'];
if ($this->User->save($data)) {
$this->Session->setFlash(__('The user has been saved.'));
}else {
$this->Session->setFlash(__('The user could not be updated. Please, try again.'));
}
Try to debug like:
if ($this->User->saveAssociated($data)) {
$this->Session->setFlash(__('The user has been saved.'));
}
else {
$this->Session->setFlash(__('The user could not be updated. Please, try again.'));
}
$log=$this->User->getDataSource()->getLog(false, false);
echo "<pre>";print_r($log);exit;

Cakephp - Class 'DboSource' not found

The first block of code throw the error Fatal error: Class 'DboSource' not found whereas the second block of code works just fine. This beats me, both use the same line to save the created field...
Block 1
public function add() {
if ($this->request->is('post')) {
$this->request->data['created'] = DboSource::expression('NOW()');
$this->EbayAccount->create();
if ($this->EbayAccount->save($this->request->data)) {
//$this->EbayAccount->id = $this->EbayAccount->getLastInsertID();
//$this->EbayAccount->saveField('created', DboSource::expression('NOW()'));
$this->Session->setFlash(__('The ebay account has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The ebay account could not be saved. Please, try again.'));
}
}
$this->set('userId', $this->Auth->user('id'));
}
Block 2
public function add() {
if ($this->request->is('post')) {
//$this->request->data['created'] = DboSource::expression('NOW()');
$this->EbayAccount->create();
if ($this->EbayAccount->save($this->request->data)) {
$this->EbayAccount->id = $this->EbayAccount->getLastInsertID();
$this->EbayAccount->saveField('created', DboSource::expression('NOW()'));
$this->Session->setFlash(__('The ebay account has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The ebay account could not be saved. Please, try again.'));
}
}
$this->set('userId', $this->Auth->user('id'));
}
Well, expression is not a static method, so Douglesm's solution is the better way. However, as expression does not access any attributes and PHP allows it, your code should work, too.
Make sure to have DboSource included, though:
App::uses('DboSource', 'Model/DataSource');
the syntax for expression is :
$db = ConnectionManager::getDataSource('default');
$this->request->data['created'] = $db->expression('SYSDATE()');
if you want to use SYSDATE() , NOW(), and other expressions
it's working in cake 2.2.x

how to delete records in cakephp

can anybody tell me how to delete records from the database?
I'm done with the rest part only deletion remains. I'm running the deletion command but
the data is not deleted from the database.Actuaaly i created an action in controller(delete_user) which contains the code for deleting the user from the database.
email value is stored in a session and i'm accessing it;s value using session read function
in the next controller.
function delete_user()
{
$email=$this->Session->read('User.email');
$this->User->delete($email, $cascade = true);
echo $this->Session->delete('User.email');
echo $this->Session->delete('User.username');
$this->redirect(array('action' => 'login'));
} );
i'm creating a link in home(View) page. and it is like this.
a href='/cakephp/cakephp/Users/delete_user'>Delete Profile</a>
i'm doing it right or wrong?
Please check the online documentation first before asking such a question.
Update 18/10/12
Try using CakePhp's magic find types:
$user = $this->User->findByEmail("bob#gmail.com");
$this->User->delete($user['User']['id']);
In your controller replace following code with delete action:
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
and in ctp file add the following link:
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', ID OF THE RECORD, null, __('Are you sure you want to delete # %s?', ID OF THE RECORD)); ?>
then your problem will be solved...
you just need to pass the id as a first parameter:
$this->User->delete($id, $cascade);
with this you can delete it without cascade:
$this->Todo->delete($this->request->data('Todo.id'));
you can hook into this befor with
function beforeDelete(){
}
and here is my full delete action:
function delete($id = null){
$this->Todo->recursive = 1;
// new
$todo = $this->Todo->read(null,$id);
if($id == null || $todo == null) {
$this->Session->setFlash('Todo existiert nicht.');
$this->redirect(array('action' => 'index'));
return;
}
$this->set('todo',$todo);
$this->Todo->delete($this->request->data('Todo.id'));
$this->redirect(array('action' => 'index'));
return;
}

Edit function is INSERT instead of UPDATE CakePHP 2.1

I'm not exactly new to CakePHP though this is my first app in 2.x. I'm using the baked controller & view and am having a problem with the edit function.
For starters, here is what was baked:
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(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
}
When this is left alone
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
I'm told that I have an invalid user, even when I know without a doubt that the user does exist.
If I change it to this:
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
The correct edit form comes up, and is populated with the correct data, but then upon save it tries to INSERT instead of Update.
Typically this is because CakePHP doesn't have an ID to work with but there is a hidden ID field in the form and I have even tried to force the issue by putting the following before the save.
$this->request->data['User']['id'] = $id;
Any ideas what's going on here?
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$user_data = $this->User->findById($id);
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'), 'flash');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'flash');
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
I got the same problem, code generated by bake, hidden id, etc..
Then I found that the field id on the database was not setted to autoincrement.
I just set to autoincrement and it works

redirect on conditions after saving a record

I have a users controller, where if I add a user I want to redirect based on the usertype a user selects on making his account
the situation:
users table
id
name
usertype_id
The user add form has a select box for user type, I have two types of users: teachers and students (each another table, model, controller) if the user chooses teacher I want to redirect to /teachers/add/$id if the user chooses student I want to redirect to: /students/add/$id
this is what I have atm, but that doesn't work obviously
<?php
class UsersController extends AppController {
var $name = 'Users';
function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$id = $this->User->id;
if ($this->User->usertype_id=='1')
{
$this->redirect(array('students/add/'.$id));
} elseif ($this->User->usertype_id=='2') {
$this->redirect(array('teachers/add/'.$id));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
$usertypes = $this->User->Usertype->find('list');
$this->set(compact('usertypes'));
}
}
?>
I'm pretty sure the problem is the assumption that, because $this->User->id exists, $this->User->usertype_id must also exist, which it does not. I ran into that issue when I first started working with CakePHP, too. :)
If the user type was passed via the add form, you need to check the data array:
Change
if ($this->User->usertype_id=='1')
To
if ($this->data['User']['usertype_id'] == '1')
If that doesn't work (I can't remember if $this->data is emptied after a successful save) then you should store the value prior to the save, like so:
function add() {
if (!empty($this->data)) {
$usertype_id = $this->data['User']['usertype_id'];
$this->User->create();
if ($this->User->save($this->data)) {
$id = $this->User->id;
if ($usertype_id == '1') {
$this->redirect(array('students/add/'.$id));
} elseif ($usertype_id == '2') {
// the rest remains the same
Addendum
Rather than using the concatenation in your redirect, This looks cleaner to me:
$this->redirect(array('controller' => 'teachers', 'action' => 'add', $id));
But I guess that's just preference.
Addendum 2
I have some additional advice about cleaning up your controller and moving all of the logic to the model. This way you can re-use the code from other controllers in the future, and your current controller will be easier to read. I would change the entire method to look like this:
// this is in /controllers/users_controller.php
function add() {
if (!empty($this->data)) {
$saved_user = $this->User->save_user($this->data);
if ($saved_user['success']) {
$this->redirect(array(
'controller' => $saved_user['controller'],
'action' => 'add',
$this->User->id
));
}
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
$usertypes = $this->User->Usertype->find('list');
$this->set(compact('usertypes'));
}
// this is in your model, /models/user.php
function save_user($data) {
$this->create;
$usertype_id = $data['User']['usertype_id'];
return array(
'controller' => ($usertype_id == '2') ? 'teachers': 'students';
'success' => $this->save($data),
);
}

Resources