CakePHP - Multiple row edits - cakephp

How can I do edits to a table on multiple rows?
I followed the tutorial here http://matsimitsu.com/blog/2008/01/06/saveall-with-cakephp.html but it doesn't seem to work.
Here is what I'm doing, but it's not working.
Thanks,
Tee
function editAll() {
$this->data = $this->Settings->find('all', array('conditions' => $conditions));
}
Then in the view, this is what I have
foreach ($this->data as $setting):
echo $form->input('Setting.' . $setting['Setting']["id"] . '.value', array('value' => $setting['Setting']["value"]));
endforeach;
Then in the add function I have
function add() {
if (!empty($this->data)) {
$this->Setting->create();
if ($this->Setting->saveAll($this->data)) {
$this->Session->setFlash(__('The Setting has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Setting could not be saved. Please, try again.', true));
}
}
}

You need to include the id field, so the data in your controller will look like this:
'Setting' => array(
0 => array(
'id' => 42,
'value' => 'foo'
),
1 => array(…)
)
So in the view, do this:
foreach ($this->data as $i => $setting) {
echo $this->Form->hidden("Setting.$i.id", array('value' => $setting['Setting']['id']));
echo $this->Form->input("Setting.$i.value", array('value' => $setting['Setting']['value']));
}

Related

cakephp 2, edit record in modal by bootstrap

How to edit a record with Cakephp and modal bootstrap?
Because when I edit a contact, I get the error 500?
missing view The view for UserContactsController:: admin_modal_edit()
was not found.
In to controller admin_modal_edit() I have set $this->layout = NULL;
These are the files of the app.
File: user/view.ctp with list of contact and the modal for add or edit.
BUTTON FOR EDIT OR DELETE
<?php echo $userContact['UserContactType']['title']; ?>: <?php echo $userContact['contact']; ?>
<?php echo __('Edit'); ?>
BOOTSTRAP MODAL
<?php
echo $this->Form->create('UserContact', array('url' => array('admin' => true, 'prefix' => 'admin', 'plugin' => 'user', 'controller' => 'user_contacts', 'action' => 'modal_edit')));
?>
<?php echo $this->Form->input('UserContact.id', array('class' => 'form-control')); ?>
<?php echo $this->Form->input('UserContact.user_id', array('default' => $user_id, 'type' => 'hidden')); ?>
<?php echo $this->Form->input('UserContact.user_contact_type_id', array('class' => 'form-control', 'empty' => true)); ?>
<?php echo $this->Form->input('UserContact.contact', array('class' => 'form-control')); ?>
<?php echo $this->Form->submit(__('Save'), array('div' => false, 'class' => 'btn btn-success')); ?>
<?php echo $this->Form->end(); ?>
File: controller/UsersController.php that generates view.ctp
public function admin_view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$user_id = $id;
$options = array(
'contain' => array('UserContact' => 'UserContactType', 'UserGroup', 'UserState', 'UserGender', 'UserAddress' => 'UserAddressType', 'UserPaymentType', 'Item', 'Comment'),
'conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
// blocco find list
$userContactTypes = $this->UserContactType->find('list');
$userAddressTypes = $this->UserAddressType->find('list');
$this->set(compact(array('userContactTypes', 'userAddressTypes', 'user_id')));
}
File: controller/UserContactsController.php for the modal
public function admin_modal_edit() {
$id = $this->request->query('id');
$this->layout = NULL;
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}
Your issue is that CakePHP is trying to render the 'admin_modal_edit.ctp' View template.
If you don't want CakePHP to render anything set autoRender to false:-
public function admin_modal_edit() {
$this->autoRender = false;
}
This will prevent CakePHP from looking for a View template to render.
$this->layout = null does not stop Cake from attempting to render templates. Which I suspect is what you're trying to achieve.
This error is showing because cakephp is complaining about the function admin_modal_edit for not having a view since it cannot find the admin_modal_edit.ctp in the view folder of your controller.
To fix this, add this
$this->autoRender = false
to your function admin_modal_edit to disable the rendering of view for that function.
So your function should look like this.
public function admin_modal_edit() {
/** -------------- **/
$this->autoRender = false;
/** -------------- **/
$id = $this->request->query('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}

CakePHP Edit Not Loading foreign Table Data

I am trying to get my edit to work I need the contact detail data to load when the user data loads. I have set the data in a similar manner to how I am retrieving the list of roles. I also don't know how to retrieve according to the model currently I was hard-coding it to retrieve 28. Would greatly appreciate any help provided.
public function edit($id = null) {
//Populate roles dropdownlist
$data = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set('roles', $data);
$data2 = $this->User->ContactDetail->find('first', array(
'conditions' => array('ContactDetail.id' =>'28')));
$this->set('contactdetails', $data2);
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
my view is set up in the following manner
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Edit User'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role_id');
echo $this->Form->input('ContactDetail.name');
echo $this->Form->input('ContactDetail.surname');
echo $this->Form->input('ContactDetail.address1');
echo $this->Form->input('ContactDetail.address2');
echo $this->Form->input('ContactDetail.country');
echo $this->Form->input('ContactDetail.email');
echo $this->Form->input('ContactDetail.fax');
?>
<label>Are you interested in buying property in Malta?</label>
<?php
$interest_buy = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_buy_property',array('type'=>'radio','options'=>$interest_buy,'value'=>'0','legend'=>FALSE));
?>
<label>Are you interested in renting property in Malta?</label>
<?php
$interest_rent = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_rent_property',array('type'=>'radio','options'=>$interest_rent,'value'=>'0','legend'=>FALSE));
echo $this->Form->input('ContactDetail.mobile');
echo $this->Form->input('ContactDetail.phone');
echo $this->Form->input('ContactDetail.postcode');
echo $this->Form->input('ContactDetail.town');
echo $this->Form->input('ContactDetail.newsletter',array('type'=>'checkbox','label'=>'Would you like to register for the newsletter?' ,'checked'=>'1','legend'=>FALSE,));
?>
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
User Model
public $primaryKey = 'id';
public $displayField = 'username';
public function bindNode($user) {
return array('model' => 'Role', 'foreign_key' => $user['User']['role_id']);
}
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password(
$this->data['User']['password']
);
return true;
}
public $belongsTo = array(
'Role' => array('className' => 'Role'));
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id'));
public $actsAs = array('Acl' => array('type' => 'requester', 'enabled' => false));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['role_id'])) {
$roleId = $this->data['User']['role_id'];
} else {
$roleId = $this->field('role_id');
}
if (!$roleId) {
return null;
} else {
return array('Role' => array('id' => $roleId));
}
}
}
ContactDetail Model
public $primaryKey = 'id';
public $displayField = 'name';
If I get you right, you have 1 contact details row for each user. In this case, you need to define in your User model:
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id',
),
);
Like this, your ids will be synced in both tables. If you don't want to make the id a foreign key, you don't have to, it's just a suggestion.
Next, when you retrieve your data in the controller, you can do:
$this->User->Behaviors->load('Containable');
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array('ContactDetail'),
));
Now I don't know if there is an automated way to do this, but I sort my data manually to fill in the inputs. I am guessing you will get a structure like array('User' => array(), 'ContactDetail' => array()).
$user['User']['ContactDetail'] = $user['ContactDetail'];
unset($user['ContactDetail']);
$this->request->data = $user;
Then in your view just set the fields as the input array:
$this->Form->create('User');
$this->Form->input('User.some_user_field');
$this->Form->input('User.ContactDetail.some_contact_detail_field');
This should fill in your fields. When you go save your data, if your array is structured like this, you can use saveAssociated():
$this->User->saveAssociated($this->request->data, array('deep' => true));
EDIT
In case your relation is defined as User hasMany ContactDetail, then you need to structure your data like this:
$this->request->data = array(
'User' => array(
// user data
'ContactDetail' => array(
[0] => array(
//contact data
),
),
),
);
And in your view:
$this->Form->input('User.ContactData.0.field')
This is for 1 row only, If you need more rows on the child table with 1 input, do your logic accordingly.
Once your User model hasOne ContactDetail, you don't need retrieve the information twice, since you've done in $this->request->data line, all association model will retrieve too.
So, your Controller looks like this:
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
// Roles
$roles = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set(compact('roles');
if ($this->request->is(array('post', 'put'))) {
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $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);
}
}
And your View, for ContactDetail's fields looks like this:
echo $this->Form->input('ContactDetail.name');
And so for all the fields related to the model ContactDetail. You can find more details here: Saving Your Data.
User model:
public $hasOne = array(
'ContactDetail' => array(
'className' => 'ContactDetail',
'foreignKey' => 'user_id',
'dependent' => true
)
);
The best solution I have found is by setting
public $belongsTo = array(
'Role' => array('className' => 'Role')
, 'ContactDetail' => array('className' => 'ContactDetail'));
This way the contact detail data loads. Although the data once saved does not update contactdetails.
For me to save I used
$this->User->saveAll($this->request->data)
this worked fully

cakephp dropdown box data not saving to database

hi all the data from my dropdown box isn't saving correctly to the database, its saving to the foreign key template_id as null
here is the function
function add(){
$this->Session->setFlash("Please create your required fields.");
$templates = $this->Template->find('all', array('fields' => array('Template.id' )));
$this->set('templates', $templates);
if($this->request->is('post'))
{
$this->Field->create();
if ($this->Field->save($this->request->data))
{
if($this->request->data['submit'] == "type_1")
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'fields','action' => 'add'));
}
if($this->request->data['submit'] == "type_2")
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'templates','action' => 'index'));
}
}
else
{
$this->Session->setFlash('The field could not be saved. Please, try again.');
}
}
}
here is the view
<?php
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->input('name', array('label'=>'Name: '));
echo $this->Form->input('description', array('label'=>'Description: '));
echo $this->Form->input('template_id',array('label'=>'Template ID: ', 'options' => $templates));
echo $this->Form->button('Continue adding fields', array('name' => 'submit', 'value' => 'type_1'));
echo $this->Form->button('Finish adding fields', array('name' => 'submit', 'value' => 'type_2'));
echo $this->Form->end();
?>
sorry guys it was a long day, it is saving the correcting information.

cakephp database not saving the correct information

my function puts the correct value into the form for my view but doesn't save the correct value in the database. The database is saving the accounts_users.id NOT the accounts_users.account_id to my the code looks like it should be entering the persons accounts_users.account_id. I see the correct information in the dropdown box in the form
add function
function add(){
$accounts=$this->User->AccountsUser->find('list', array(
'fields'=>array('id','account_id'),'conditions' => array(
'user_id' => $this->Auth->user('id'))));
if($this->request->is('post')){
$this->Template->create();
if ($this->Template->save($this->request->data)) {
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'Fields','action' => 'add'));
} else {
$this->Session->setFlash('The template could not be saved. Please, try again.');
}
}
here is the add view
<?php
echo $this->Form->create('Template', array('action'=>'add'));
echo $this->Form->input('name',array('label'=>'Template Name: '));
echo $this->Form->input('account_id',array('label'=>'Business: ', 'type' => 'select', 'options' => $accounts));
echo $this->Form->input('description',array('label'=>'Short Description Of Template: '));
echo $this->Form->end('Click Here To Submit Template');
?>
Try the following code:
function add(){
$accounts=$this->User->AccountsUser->find('list', array(
'fields'=>array('account_id','account_id'),'conditions' => array(
'user_id' => $this->Auth->user('id'))));
if($this->request->is('post')){
$this->Template->create();
if ($this->Template->save($this->request->data)) {
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'Fields','action' => 'add'));
} else {
$this->Session->setFlash('The template could not be saved. Please, try again.');
}
}

cakephp redirect button

hi all i have page that has two buttons, one should allow the person go to the add page and continue adding to the database otherwise if they click the other button it goes to the index page.
currently they both just add the entered information into the database and refresh the page, so when a person clicks the type_2 button they aren't being taken to the index page.
here is the if statement in controller
if ($this->Field->save($this->request->data))
{
if($this->params['form']['type_1'] == 'type_1')
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'Fields','action' => 'add'));
}
else if($this->params['form']['type_2'] == 'type_2')
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'Templates','action' => 'index'));
}
}
here is the view
<?php
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->input('name', array('label'=>'Name: '));
echo $this->Form->input('description', array('label'=>'Description: '));
echo $this->Form->input('templates_id', array('label'=>'Template ID: ', 'type' => 'text'));//this would be the conventional fk fieldname
echo $this->Form->button('Continue adding fields', array('name' => 'type', 'value' => 'type_1'));
echo $this->Form->button('Finish adding fields', array('name' => 'type', 'value' => 'type_2'));
echo $this->Form->end();
?>
Your if conditions are wrong, you're checking for indices ['form']['type_1'] and ['form']['type_2'], this should be ['form']['type'] in both occasions, and then you check for their value, so it becomes:
if ($this->Field->save($this->request->data))
{
if($this->params['form']['type'] == 'type_1')
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'Fields','action' => 'add'));
}
else if($this->params['form']['type'] == 'type_2')
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'Templates','action' => 'index'));
}
}
had to use request instead of params
if ($this->Field->save($this->request->data))
{
if($this->request->data['submit'] == "type_1")
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'fields','action' => 'add'));
}
if($this->request->data['submit'] == "type_2")
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'templates','action' => 'index'));
}
}

Resources