cakephp post data field missing from SQL update statement - cakephp

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)

Related

edit 2 models with one view and controller cakephp

I have 2 models. Typology and TypologyPicture. and 2 controllers Typologies and TypologyPictures. I want to edit both typology and typologyPcture from one controller.
<?php echo $this->Form->create('TypologyPicture', array('type'=>'file')); ?>
<legend><?php echo __('Edit Typology Picture'); ?></legend>
<?php echo $this->Form->input('id'); ?>
<!-- Here is the first part for the update Typolohgy -->
<?php echo $this->Form->input('Typology.item_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.title'); ?>
<?php echo $this->Form->input('Typology.description');?>
<?php echo $this->Form->input('Typology.thumbnail',array('type'=>'file')); ?>
<?php echo $this->Form->input('Typology.typology_category_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.typology_condition_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.price',array('placeholder'=>'Price')); ?>
<!-- Here is the second part for the update Typpology Picture -->
<?php echo $this->Form->input('pic_path', array('label'=>'Picture','type'=>'file')); ?>
<?php echo $this->Form->end(__('Submit')); ?>
This is the view. which contain the field for typology (item_id|title|description|thumbnial|typology_category_id|typology_condition_id)
and the field for typologypictures (pic_path)
The controller (that is at TypologyPicturesController) is:
public function edit($id = null) {
if (!$this->TypologyPicture->exists($id)) {
throw new NotFoundException(__('Invalid typology picture'));
}
if ($this->request->is(array('post', 'put'))) {
if(empty($this->data['TypologyPicture']['pic_path']['name'])){
unset($this->request->data['TypologyPicture']['pic_path']);
}
if ($this->TypologyPicture->saveAll($this->request->data)) {
$this->Session->setFlash(__('The typology picture has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The typology picture could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('TypologyPicture.' . $this->TypologyPicture->primaryKey => $id));
$this->request->data = $this->TypologyPicture->find('first', $options);
$opt = array('conditions' => array('Typology.id' => $this->request->data['TypologyPicture']['typology_id']));
$this->request->data = $this->Typology->find('first', $opt);
}
if ( AuthComponent::user('role')==='admin' ||AuthComponent::user('role')==='superadmin' ){ //if the user is admin or superadmin, show all on dropdown
$items = $this->Typology->TypologyItem->find('list');
} else {// else if the user is author, show only item created by him.
$items = $this->Typology->TypologyItem->find('list', array('conditions' => array('TypologyItem.user_id' => AuthComponent::user('id'))));
}
$typologyCategories = $this->Typology->TypologyCategory->find('list');
$typologyConditions = $this->Typology->TypologyCondition->find('list');
$users = $this->Typology->TypologyUser->find('list');
$this->set(compact('items', 'typologyCategories', 'typologyConditions', 'users'));
if ( AuthComponent::user('role')==='admin' ||AuthComponent::user('role')==='superadmin' ){
$typologies = $this->TypologyPicture->ItemTypologyPicture->find('list');
} else {
$typologies = $this->TypologyPicture->ItemTypologyPicture->find('list', array('conditions' => array('ItemTypologyPicture.user_id' => AuthComponent::user('id'))));
}
$this->set(compact('typologies'));
}
And when i try to edit, it opens the form, the fields are filled properly, but wheni press save there is new row inserted at typologyPicture and no change at all to Typology.
So what i want is that when the user press submit only the correspondings rows are updated and not to insert new rows.....

Edit 2 controller from one controller (Correct)

i have small problem so i need some help. maybe its very easy but i just need a push... so i am withing one controller
public function edit($id = null) {
if (!$this->TypologyPicture->exists($id)) {
throw new NotFoundException(__('Invalid typology picture'));
}
if ($this->request->is(array('post', 'put'))) {
if(empty($this->data['TypologyPicture']['pic_path']['name'])){
unset($this->request->data['TypologyPicture']['pic_path']);
}
if ($this->TypologyPicture->save($this->request->data)) {
$this->Session->setFlash(__('The typology picture has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The typology picture could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('TypologyPicture.' . $this->TypologyPicture->primaryKey => $id));
$this->request->data = $this->TypologyPicture->find('first', $options);
//$options1 = array('conditions' => array('Typology.id' => $id));
$opt = array('conditions' => array('Typology.id' => $this->request->data['TypologyPicture']['typology_id']));
$this->request->data = $this->Typology->find('first', $opt);
}
if ( AuthComponent::user('role')==='admin' ||AuthComponent::user('role')==='superadmin' ){ //if the user is admin or superadmin, show all on dropdown
$items = $this->Typology->TypologyItem->find('list');
} else {// else if the user is author, show only item created by him.
$items = $this->Typology->TypologyItem->find('list', array('conditions' => array('TypologyItem.user_id' => AuthComponent::user('id'))));
}
$typologyCategories = $this->Typology->TypologyCategory->find('list');
$typologyConditions = $this->Typology->TypologyCondition->find('list');
$users = $this->Typology->TypologyUser->find('list');
$this->set(compact('items', 'typologyCategories', 'typologyConditions', 'users'));
if ( AuthComponent::user('role')==='admin' ||AuthComponent::user('role')==='superadmin' ){
$typologies = $this->TypologyPicture->ItemTypologyPicture->find('list');
} else {
$typologies = $this->TypologyPicture->ItemTypologyPicture->find('list', array('conditions' => array('ItemTypologyPicture.user_id' => AuthComponent::user('id'))));
}
$this->set(compact('typologies'));
}
so as you see from contact controller i want to access the contact that i want to edit and its its pictures that are stored in contact_picture table. contact by itself has like an icon or an avatar, and in contact picture are stored the gallery. so here the problem is that i get all the data as it supposed to, but the image of the contact (avatar, or icon) doesent dispay, the path is retrived correctly but it just doesent display the image.
So what im asking is that if there is another way or easy way or even better way to do that i would really appruciate it...really.
Thanks in advance!
EDIT: The View Part:
<?php echo $this->Form->create('TypologyPicture', array('type'=>'file')); ?>
<legend><?php echo __('Edit Typology Picture'); ?></legend>
<?php
$dir = "/img/uploads/typology/images/";
echo $this->Form->input('id'); ?>
<?php echo $this->Form->input('Typology.item_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.title'); ?>
<?php echo $this->Form->input('Typology.description');?>
<?php echo $this->Form->input('Typology.thumbnail',array('type'=>'file')); ?>
<?php echo $this->Form->input('Typology.typology_category_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.typology_condition_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.price',array('placeholder'=>'Price')); ?>
<!-- Here is the second part of the update -->
<?php echo $this->Form->input('pic_path', array('label'=>'Picture','type'=>'file'));
echo $this->Form->input('hiddenimage', array('type'=>'hidden','value'=> $this->Form->value('pic_path') ));
$Image = $this->Form->value( 'pic_path');
if(empty($Image) || $Image==NULL)
{$Image = "/img/uploads/noimg.jpg";}
else {$Image = $dir . $Image; }
echo $this->Html->image($Image,array('align'=>'absbottom','style'=>'max-height:100px'));
?>
<?php echo $this->Form->end(__('Submit')); ?>
So when i do echo to the image it doesent display correctly... if i remove the typology model part like a normal edit, it displays normal...
try by removing the img part from $dir and $Image;
$dir = "/img/uploads/typology/images/";
should be
$dir = "uploads/typology/images/";
and
{$Image = "/img/uploads/noimg.jpg";}
should be
{$Image = "uploads/noimg.jpg";}

Selecting a default value for a dropdown (key-value array) in cakePHP

Here is the dropdown in a form:
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
The $customers is a key-value array like this:
array(
(int) 2 => 'Best customer',
(int) 5 => 'Good customer',
(int) 9 => 'Customer')
I need one value to be pre selected once the dropdown is created. I have tried to select a default value as the int id and as the customer name but none of them worked.
Here is the controller edit function:
function edit($id = null) {
$this->Project->id=$id;
$this->Project->recursive = 0;
$customers = $this->Customer->find('list', array('conditions'=>array('company_id'=>$this->Auth->user('company_id'))));
$this -> set('customers', $customers);
if(!$this->Project->exists()){
throw new NotFoundException('Invalid project');
}
if($this->request->is('post')|| $this->request->is('put')){
if($this->Project->save($this->request->data)){
$this->Session->setFlash('The project has been edited');
$this->redirect(array('controller'=>'projects', 'action'=>'view', $id));
} else{
$this->Session->setFlash('The project could not be edited. Please, try again');
}
}else{
$this->request->data = $this->Project->read();
$this->request->data['Project']['customer_id'] = 'New customer';
}
}
And here is the edit form:
<?php echo $this->Form->create('Project');?>
<fieldset>
<legend><?php __('Edit Project'); ?></legend>
<?php
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
echo $this->Form->input('name');
echo $this->Form->input('project_nr', array('type'=>'text', 'label'=>'Case number'));
echo $this->Form->input('address');
echo $this->Form->input('post_nr');
echo $this->Form->input('city');
echo $this->Form->input('start_date', array('label'=>'Start Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('finish_date', array('label'=>'End Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('company_id', array('value' => $current_user['company_id'], 'type'=>'text', 'type'=>'hidden'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
The best approach is to leverage the controller for this
if ($this->request->is('post')) {
$this->Model->create();
if ($this->Model->save($this->request->data)) {
...
} else {
...
}
} else {
/* Now here you can put your default values */
$this->request->data['Model']['field'] = ...;
}
For details see http://www.dereuromark.de/2010/06/23/working-with-forms/

Updating a row in cakephp

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';
}
?>

Avoiding redirect and perssisting the session

I am trying to finish this website in cake php that was previously in regular php, but as newbie in the cakephp world.. I have found some difficulties such as these.
1) .When I click on login, it transfers me to another page although i have specified no redirects in app controller except when there is a registration. The login is at the top and its viewable through out all the pages, but if i click login, it redirects me to the login page (which i do not want).
2.) After I login, it brings in the session with the user name saying welcome 'username' but then if I go to another page, it seems like it forgets the session and brings back the inputs for the login form at the top of the page.
Here is my code
app_controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
$this->Auth->allow('add','get_categories','get_home', 'get_others', 'pages');
$this->Auth->autoRedirect = false;
}
}
?>
UsersController
<?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 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' => 'get_home'));
}
}
$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';
if ($this->data) {
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$this->data['User']['password'] = '';
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
elements/loginform.ctp
<?php
if ($this->Session->read('Auth.User.username')):?>
<?php
echo "Welcome".' ' ;
echo $this->Session->read('Auth.User.username');
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>
UPDATE
I added the following to the app_controller
<?php
class AppController extends Controller {
var $helpers = array('Html', 'Form', 'Javascript', 'Session');
var $components = array('Auth', 'Session');
function beforeFilter() {
//new addition
$this->set('userData', $this->Session->read());
$this->Auth->allow('add','get_categories','get_home', 'get_others', 'pages', '*');
$this->Auth->autoRedirect = false;
}
}
?>
WHEN I LOGIN I GET THIS ARRAY
Array ( [Config] => Array
( [userAgent] => 8f12200c2d48fa7955465842befe1c9e
[time] => 1323562284 [timeout] => 10 )
[Auth] => Array (
[User] => Array (
[id] => 63
[user_role] => 2 [
[user_fname] => test
[user_lname] => test
[user_email] => test#test.com
[user_phone] => 677-988-7777
[user_cellphone] => 555-456-9999
[user_address1] => 1st Avenue
[user_address2] =>
[user_city] => Citiland FL
[user_zip] => 55555
[username] => admin2 ) ) )
BUT WHEN I NAVIGATE TO A NEW PAGE
Array ( [Config] => Array (
[userAgent] => 8f12200c2d48fa7955465842befe1c9e
[time] => 1323562591 [timeout] => 10 ) )
ADDED PRINT_R TO elements/loginform TO SEE THE VARIABLE CONTENTS ACROSS ALL PAGES
<?php
print_r($userData);
if ($this->Session->read('Auth.User.username')):?>
<?php
echo "Welcome".' ' ;
echo $this->Session->read('Auth.User.username');
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>
1) This is because in your UsersController you have a redirect after the user is logged in.
Your login function should instead read:
function login() {
$this->layout = 'master_layout';
if ($this->data) {
if ($this->Auth->login($this->data)) {
// Retrieve user data
$results = $this->User->find(array('User.username' => $this->data['User']['username']), array('User.active'), null, false);
/*This is the offending line, I've commented it out, but you could have it redirect somewhere else (it might be a good idea to redirect to the index action, for example, or just delete it:*/
//$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$this->data['User']['password'] = '';
}
As for 2), I believe it may be because you are not setting the data afterwards, so that while it exists in a tmp directory on the server (using the Session component) it is not actually being passed along to the view. So basically I think it's because you can't call Session methods in the view. Even if I'm not entirely correct about that, what I'm suggesting to do should work: Instead of calling session methods in the view, call them in the controller, set them in a variable for the view to access using $this->set();, then test against that variable in the view.
If you need to do this for ton of views and actions, you could consider adding something like this to your controller or even your app controller:
function beforeFilter() {
// Get session data for appllication use
$this->appuserstuff = $this->Session->read();
}
function beforeRender() {
// Make app variables available to view
$this->set('userData', $this->appuserstuff);
}
Alternatively, if you just need this in a couple actions, you could just set the user data in those actions with a:
$this->set('userData', $this->Session->read());
Now I'd recommend that you do a <?php debug($userData); ?> in one of your views so you can see how the data is structured in the array when it is set, so that you can user or test conditionals against. Finally, you could replace the direct calls to Session in your view with instead checks against the array of data:
Please note that I'm not sure how your specific array is structured so do a debug as recommended above and plug in your own keys for it to work:
<?php
if (!empty($userData['User'])):?>
<?php
echo "Welcome".' ' ;
echo $userData['User']['username'];
echo " ";
echo $html->link('logout', array('action'=>'logout'));
?>
<?php else : ?>
<div class="types form">
<?php echo $form->create('User', array('controller' => 'Users','action' => 'login')); ?>
<?php echo $form->input('username', array('label' => 'username')); ?>
<?php echo $form->input('password',array('type'=>'password', 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
</div>
<?php endif; ?>

Resources