I need to update a particular row. This doesn't seem to work. Any help is appreciated.
View updated:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Post');
?>
Controller updated:
public function index($id = 0){
$this->Setting->id = $id;
if (empty($this->request->data)) {
$this->request->data = $this->Setting->read();
} else {
if ($this->request->is('post')) {
$this->request->data['Setting']['id'] = $id;
$this->Setting->save($this->request->data);
$this->Session->setFlash('This should have saved...');
}
}
}
Edit:
blog_state is a boolean, and works fine. It loads the value from the DB normally and saves it to the new row normally. (I need it to update the existing row it is being pulled from, which is where my problem is)
Update your view:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Page');
?>
You will also need to make sure you set the id in the function so it will populate the value correctly. The record cannot be updated unless it knows the PK ID it is updating.
The way you can accomplish this is by setting it in the request data:
$this->request->data['Setting']['id'] = $id;
Then it will automatically be set in the view.
UPDATE
It looks like your logic may be flawed. The form will not necessarily pass the ID back on the URL. So update you form like so and check again if it works. It looks like the way you currently have it it will set ID to null which will create a new record.
public function index($id = 0){
if (empty($this->request->data)) {
$this->Setting->id = $id;
$this->request->data = $this->Setting->read();
} else {
if ($this->request->is('post')) {
$this->Setting->save($this->request->data);
$this->Session->setFlash('This should have saved...');
}
}
}
Well you need to know what row it is effecting (this will usually be argument to your function).
public function index() {
// Things here
}
This will create the index page for that controller.
Create an edit function like
public function edit($id = null) {
$this->Setting->id = $id;
if (!$this->Setting->exists()) {
// Exception.
}
if ($this->Setting->save($this->request->data)) {
$this->Session->setFlash(__('Saved'));
}
}
Then you can access it like http://example.com/setting/edit/45
Make sure you have primary key id column in your DB if not override the your chosen primary key in model like below.
<?php
class Test extends AppModel{
public $primaryKey = 'primarykey column name';
}
?>
Related
This my database:
http://gyazo.com/c6a86127d6f91aae947cf45ee535cecd
Example:
http://gyazo.com/c23fec3fabb7e4504c42453980fbc372
When I press the edit button , they able to retrieve the data however the page show me empty field instead of the field that have old data.
Secondly, unable to undate because they keep send empty id_field back to controller.
p.s. add,edit,delete method work totally fine.
Below are my code:
Model
<?php
App::uses('AppModel', 'Model');
class EventDate extends AppModel {
public $useTable = 'eventdate';
public $primaryKey = 'eventDate_id';
public $validate = array(
'event_date' => array(
'rule' => array('date','ymd'),
'message' => 'Enter a valid date in YY-MM-DD format.',
'required' => true,
'allowEmpty' => false
)
);
}
Controller
public function edit($id = null) {
//Retrieve from database
$post = $this->EventDate->findByEventdateId($id);
$this->set('edate', $post) ;
// debug($post);
//Without Id
if (!$id) {
throw new NotFoundException(__('Invalid Event Date'));
}
//If Not Exist the id
if (!$post) {
throw new NotFoundException(__('Invalid Event Date'));
}
//After press the submit
if ($this->request->is(array('post','put'))) {
$this->EventDate->eventDate_id = $id;
debug($_POST);
if ($this->EventDate->save($this->request->data)) {
$this->Session->setFlash(__('The Event has been saved.'));
return $this->redirect(array('action' => 'index'));}
else
{$this->Session->setFlash(__('The Event could not be saved. Please, try again.'));}
}
//Set the data same as retrieved
if (!$this->request->data) { $this->request->data = $post;}
}
edit.ctp
<h2>Edit Event</h2>
<?php
echo $this->Form->create('eventdate');
//echo $this->Form->input('eventDate_id', array('type' => 'hidden'));
echo $this->Form->hidden('eventDate_id');
echo $this->Form->input('event_date',array(
'label' => 'Event Date',
'type' => 'text',
'id' => 'datepicker'));
echo $this->Form->end('Save Post');
?>
Below link is the debug($_Post) been shown:
http://gyazo.com/5e569e6cc6b3026fc8896c315197a938
Should be:
echo $this->Form->create('EventDate'); // notice the capital CamelCase
Side note: The info that displays in the fields will be out-of-date, since you 1) get the data from the DB and set to var, THEN do the save based on posted data.
Another side note: There are quite a few things that you're doing that are non-standard and not consistent w/ the recommended conventions. Cleaning that up will make it easier to work with AND easier to receive help.
i have trouble in creating method in controller of cakephp to update the my existing row in a table, can anyone suggest me appropriate model method to update the row in table
<?php
class UsersController extends AppController
{
public function update($id)
{
if(isset($_REQUEST['update']))
{
// method of model to update the row
}
else
$this->set('user',$this->User->find('first',array('conditions'=>array('id'=>$id))));
}
}
?>
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array
$this->User->id = $id;
$this->User->save($this->request->data);
Try the code.......
<?php
class UsersController extends AppController {
public function update($id = null) {
if ($id) {
if ($this->request->is('post')) {
$this->User->id = $id;
$this->User->save($this->request->data);
} else {
$this->set('user', $this->User->find('first', array('conditions' => array('id' => $id))));
}
}
}
}
?>
#burzum after reading the tutorial which link provide by you i found the solution to the my problem, in model updateAll() method available in model by using this i have update row of the table.
public function update($id)
{
if(isset($_REQUEST['update']))
{
$this->User->id=$id;
if($this->User->updateAll(array('User.fname'=>"'".$_REQUEST['fname']."'",'User.lname'=>"'".$_REQUEST['lname']."'",'User.email'=>"'".$_REQUEST['email']."'"),array('id'=>$id)))
echo '<script>alert("update successfully")</script>';
else
echo '<script>alert("failes to update ")</script>';
}
else
$this->set('user',$this->User->find('first',array('conditions'=>array('id'=>$id))));
}
I'm pretty new to cakePHP and I've been stuck on this problem for a few days now. My Products index view displays a list of products we have in inventory and includes a "Checkout" action with every product that points to the Checkout/add view. The problem is the product_id from the product that needs to be checked out does not get passed to the add checkout page and I can't figure out how to make this happen. If anyone has any suggestions I could really use some help.
Here is my CheckoutController add action:
public function add() {
if ($this->request->is('post')) {
$this->Checkout->create();
if ($this->Checkout->save($this->request->data)) {
$this->Session->setFlash(__('The checkout has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The checkout could not be saved. Please, try again.'));
}
}
$products = $this->Checkout->Product->find('list');
$users = $this->Checkout->User->find('list');
$this->set(compact('products', 'users'));
}
Checkout Add View
<?php echo $this->Form->create('Checkout');?>
<fieldset>
<legend><?php echo __('Add Checkout'); ?></legend>
<?php
echo $this->Form->input('product_id');
echo $this->Form->input('start_time');
echo $this->Form->input('end_time');
echo $this->Form->input('user_id');
echo $this->Form->input('description');
?>
</fieldset>
Link from the Products index page
<?php echo $this->Html->link(__('Checkout'), array('controller' => 'Checkouts','action' => 'add', $product['Product']['id'])); ?>
Cake will pass the product_id as the first argument of your action; Default Cake 'Routes' will match this url;
/mycontroller/myaction/param1/param2/param3
To this action:
MycontrollerController::myaction(param1, param2, param3)
You can pass this value to the form by adding an argument to the add() action and adding it to the 'request' if the form is not posted. Like this;
public function add($productId = null) {
if ($this->request->is('post')) {
$this->Checkout->create();
if ($this->Checkout->save($this->request->data)) {
$this->Session->setFlash(__('The checkout has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The checkout could not be saved. Please, try again.'));
}
} else {
$this->request->data['Checkout']['product_id'] = $productId;
}
$products = $this->Checkout->Product->find('list');
$users = $this->Checkout->User->find('list');
$this->set(compact('products', 'users'));
}
This will automatically propagate the 'value' of the product_id drop down
from your links on the products index page it seems that
public function add()
should read
public function add($product_id)
furthermore you should set the $product_id into the view, and also
fill it into the inputbox echo $this->Form->input('product_id', array('value'=>$product_id));
Having trouble geting cakephp to update a record.
Controller Code:
public function viewBenefit($id) {
if ($this->request->is('post')) {
$this->set('post', $this->request->data);
$this->Benefit->id = $id;
if ($this->Benefit->save($this->Benefit->data)) {
$myVars['Sucsess'] = TRUE;
$this->Session->setFlash('Updates Saved');
} else {
$myVars['NewID'] = 0;
$myVars['Sucsess'] = False;
$this->Session->setFlash('There was an error.');
}
}
$this->Benefit->recursive = 2;
$this->Benefit->id = $id;
$this->set('benefit', $this->Benefit->read());
}
Relevant View Code:
<?php echo $this->Form->create('Benefit',array('action'=>'edit','url' => '#')); ?>
<?php echo $this->Form->input('id',array('type'=>'hidden')) . "\n"; ?>
<?php echo $this->Form->input('short_description',array('type'=>'textarea')) . "\n"; ?>
<?php echo $this->Form->end(); ?>
NOTE: The Form is sumbitted via JS
POST Data (via debug($post); )
array(
'Benefit' => array(
'id' => '1952e98e-f589-47d4-b458-11a1bd58ba3b',
'short_description' => '<p>This is great sample insurance 321321</p>'
)
)
SQL UPDATE statment:
UPDATE `c16memberdev`.`benefits` SET `modified` = '2012-12-04 10:45:16' WHERE `c16memberdev`.`benefits`.`id` = '1952e98e-f589-47d4-b458-11a1bd58ba3b'
As you can see the field "short_description" does not get added to the SQL statement, and therefore the data not added to the database. Thanks for your help.
Try changing
$this->Benefit->save($this->Benefit->data)
to
$this->Benefit->save($this->request->data)
I am trying to make the login work... but when i register (using the add) function i used to have a md5, then i changed it to $this->Auth->password, and then i tried without that line.. well it logins fine the first time.. but then for some reason it changes the hash again on login it never matches the database.. i dont know how to fix this.. here is my code
<?php
class UsersController extends AppController {
var $uses = array("User");
var $components = array('Auth', 'Session');
function index()
{
$this->set('users', $this->User->find('all'));
$this->layout = 'master_layout';
}
function beforeFilter() {
$this->Auth->allow('add');
}
function add() {
if (!empty($this->data)) {
//pass is hashed already
//->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your were registered!.');
$this->redirect(array('action' => 'index'));
}
}
$this->layout = 'master_layout';
}
//IF THE DATABASE IS SET UP CORRECTLY CAKE AUTHENTICATES AUTOMATICALLY NO
//LOGIC IS NEEDED FOR LOGIN http://book.cakephp.org/view/1250/Authentication
function login() {
$this->layout = 'master_layout';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
VIEW
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
you shouldnt use password as field name on forms.
this way even empty strings will be saved and will mess up already saved ones. depending on your beforeSave method the empty string might even be saved as hash (cloaking that its actually an empty password).
see
http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/