Get ID from table and update the row in CakePHP - cakephp

I have Ipr_forms table in my Db i want to update the row but the following code give me job_id of that table.which is not my requirement.....i want table id to update the existing table
My controller code
$id =$this->request->data['IprForm']['id'];
$ipr_forms['job_id'] = $this->request->data['IprForm']['job_id'];
$ipr_forms['IprForm'] = $this->request->data['IprForm'];
$this->IprForm->id = $id;
//debug($id);
$ipr_forms_save = $this->IprForm->save($ipr_forms);
If i debug the id ,$id variable hold the job_id ....

here i can give you an example to edit any record in cakephp with multiple fields
just take look in function and you may have good idea
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to update your post.'));
}
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
or you can also refer detail cakephp.org link with title of editing posts

Related

on editing inserting a new row instead of updating the current row in cakephp 2x

I m having trouble in updating the student profile form,after i gave the user_id to the student profile.Every time when i try to edit the form, on saving it provide new id to the existing user. I don't know where I'm getting wrong. Plz help.Thanks in Advance.
Here is my add and edit function in Student Profiles controller:
public function add() {
if ($this->request->is('post')) {
$this->StudentProfile->create();
$data = $this->request->data;
$data['StudentProfile']['user_id'] = $this->Auth->user('id');
// code implemented below
//$this->loadModel('User');
if ($this->StudentProfile->save($data)) {
//Update user here if Profile saved successfully
//$this->StudentProfile->id = $this->Auth->user('id');
$this->Session->setFlash(__('Your account profile has been created'));
$this->redirect(array('controller' => 'studentprofiles', 'action' => 'index'));
}else{
$this->Session->setFlash(__('Your Profile was saved, but an error has occurred while updating the Users table'));
//Email your self the user ID here or something ??
}
}
$h=array(
'fields' => array('Height.height'),
'recrusive' => 0
);
$this->loadModel('Height');
$height = $this->Height->find('list',$h);
$this->set(compact('height'));
}
public function edit($id = null) {
if (!$this->StudentProfile->exists($id)) {
throw new NotFoundException(__('Invalid student profile'));
}
if ($this->request->is(array('post', 'put'))) {
$this->request->data['StudentProfile']['user_id'] = $this->Auth- >user('id');
// code implemented below
// $this->loadModel('User');
if ($this->StudentProfile->save($this->request->data)) {
//$this->StudentProfile->id = $this->Auth->user('id');
$this->Session->setFlash(__('The student profile has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The student profile could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
} else {
$options = array('conditions' => array('StudentProfile.' . $this- >StudentProfile->primaryKey => $id));
$this->request->data = $this->StudentProfile->find('first', $options);
}
$h=array(
'fields' => array('Height.height'),
'recrusive' => 0
);
$this->loadModel('Height');
$height = $this->Height->find('list',$h);
$this->set(compact('height'));
}
Can't believe I'm replying to my own question . Well In case anyone have the same above problem,the solution is just add the following code after this-
$this->request->data['StudentProfile']['user_id'] = $this->Auth->user('id');
// add this code to avoiding giving new id to existing user on edit:
$this->request->data['StudentProfile']['id'] = $id;
A better way of saving edited information is to set the ID on the model before the save like so
$this->StudentProfile->id = $this->Auth->user('id');
If you initiate a save after setting the above then the row will be edited and not add a new row.

About Model CakePHP

i have 2 table in database.there are categories and posts.
categories have id , name
posts have id , category
and i have 2 files.
PostsController.php
edit.ctp
i edit category by edit.ctp when i save its
image >> http://s704.photobucket.com/albums/ww41/018115496/edit.png
It is not save category's name but save a category's id into Posts.
image >> http://i704.photobucket.com/albums/ww41/018115496/index.png
This is my code
PostsController.php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public $uses = array('Post','Category');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function edit($id = null) {
$this->loadModel('Category');
$categories = $this->Category->find("list",array('field'=>array('Category.name')));
$this->set("categories", $categories);
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
}
and edit.ctp
<?php
echo $this->Form->create('Post');
echo $this->Form->input('category', array('options' => $categories));
echo $this->Form->end('Save Post');
?>
i think i because find("list") but i don't know how to solve.
Thank you.
I have fixed your problem, You need to replace this
//PostsController.php
public function edit($id = null) {
$this->loadModel('Category');
$categories = $this->Category->find("list",array('field'=>array('Category.name','Category.name')));
$this->set("categories", $categories);
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
When calling find('list'), the fields passed are used to determine what should be used as the array key and value, and optionally what to group the results by. By default, the primary key for the model is used for the key, and the display field (which can be configured using the model attribute displayField) is used for the value. Some further examples to clarify:
$justCategories = $this->Category->find('list', array(
'fields' => array('Category.name')
));
$Categories = $this->Category->find('list', array(
'fields' => array('Category.name', 'Category.name')
));
With the above code example, the resultant vars would look something like this:
$justCategories = Array
(
//[id] => 'name',
[1] => 'Books',
[2] => 'Baby',
[3] => 'Business & Industrial'
)
$Categories = Array
(
//[name] => 'name',
['Books'] => 'Books',
['Baby'] => 'Baby',
['Business & Industrial'] => 'Business & Industrial'
)
Read find(‘list’) in CakePHP

Changing single variable value in AppController

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.'));
}
}

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

Resources