Deleting Multiple selected items from table - cakephp

In my table I have a column with a check box for each row. I want to be able to delete all the selected items. I found the code from this website and modified it for my own stuff.
Link
I followed the website's naming convention for the check boxes and it is as follows:
<td> <?php echo $this->Form->checkbox('LocalClocks.id.['.$LocalClock['LocalClock']['id'].']', array('value' => $LocalClock['LocalClock']['id'])); ?></td>
This is the code in my controller for the deleteSelected() function:
public function deleteSelected()
{
foreach($this->data['LocalClocks'] as $key => $value)
{
if($value != 0)
{
$this->LocalClock->del($value);
}
}
$this->redirect($this->referer());
}
This is the code for the actual delete button (just in case it is needed):
<?php echo $this->Form->postLink('Delete Selected', array('action' => 'deleteSelected'), array('confirm' => 'Are you sure?')); ?>
There are a couple things I think might be the problem:
The code was written for an older version of cake, I think the website said 1.3, but I don't know what to update/correct in the existing code to make it work.
The delete button is the same as the one on cakephp's website on the blog tutorial. The only change I made was removing the id of the item to delete, because im not deleting a single item but multiple items.
Any help would be great.

Your checkbox input should be something like this
echo $this->Form->checkbox('LocalClocks.'.$LocalClock['LocalClock']['id'], array(
'value' => $LocalClock['LocalClock']['id'],
'hiddenField' => false
));
This will create a data array that will look like this
array(
'LocalClocks' => array(
1 => 1,
42 => 1
)
);
And will omit any unchecked ones from the data array because we're not using the hidden field. Finally, just a couple changes to your action
public function deleteSelected()
{
foreach($this->request->data['LocalClocks'] as $key => $value)
{
$this->LocalClock->delete($key);
}
$this->redirect($this->referer());
}
I prefer using Model::delete() to Model::deleteAll() because it runs the callbacks, where deleteAll does not.
Finally, your link will actually be a submit button. This will POST the data to the controller.
echo $this->Form->end('Submit');
If you want to use ajax, use the JsHelper to submit it instead. The following creates an Ajax submission that updates the dom element #mytable with the results of the action (in this case the referer that you redirect to).
echo $this->Js->submit('Submit', array(
'update' => '#mytable'
));
echo $this->Form->end();

once you got the list of your checked boxes; rather than using foreach loop to delete your ids one by one try this:
$this->Model->deleteAll(array('Model.column' => array($keys)));

Related

Error in writing a function in Cakephp

I'm working with cakephp for project development. I wrote a function to get data from the database and do a summation.I have created a table called user with height and weight in it. I want to retrieve that data,add them, and to return that. Here is the function I wrote.
public function calculate()
{
$Height=$this->set('user',$this->User->find('first'));
$Weight=$this->set('user1',$this->User->find('first'));
$sum=($Height+$Weight);
$this->set('SUM',$sum);
}
In the view I wrote the following code.
<div class="page-content">
<?php echo $user['User']['weight']; ?>
<?php echo $user1['User']['height']; ?>
<?php echo $SUM ?>
</div
Height and weight values are getting displayed. But the sum value is displayed as zero. Please help me to fix this.
I found a better way to do the above calculation. I used the following code in the controller.
public function calculate($id=null)
{
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user1',$this->User->find('first', array('fields' => ('height'),'conditions' => array('User.id' =>$id))));
$this->set('user',$this->User->find('first', array('fields' => ('weight'),'conditions' => array('User.id' =>$id))));
}
My view looks similar to the one mentioned above. This works fine with me...
First you need get the field from find. (You can use find condition to filter de user id for example).
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $id),
'fields' => array('User.height', 'User.weight') // fields from your DB
));
So, you can do a pr($user) to see the data and know what use.
After do the sum and set to the view. Cakephp Set

how to get the selected values from a drop down list in cake php

I’m new to cake php. I need to get the user selected value from a drop down list in cake php. my view code is :
echo $this->Form->create('order');
echo $this->Form->input('status', array('options' => $options, 'default' => '--Select--'));
please help me to get the values(not key).
You can simply get the user selected value into your controller's method using:
$selected_value = $this->request->data['order']['status'];
You can either check the posted data into your controller's method using:
if($this->request->is('post'))
{
pr($this->request->data);die;
$selected_value = $this->request->data['order']['status'];
}
Do like this...
echo $this->Form->input('type', array(
'options' => array('Appartment', 'Villa' , 'Residential' ,'Kiosk', 'Commercial'),
'empty' => '(choose one)'

CakePHP update multiple form fields from selectbox change

I'm using CakePHP 2.2. I'm adapting a method of dynamically updating a selectbox which I got from: http://www.willis-owen.co.uk/2011/11/dynamic-select-box-with-cakephp-2-0/#comment-10773 which works without issue. It updates the 'hotels' selectbox contents when the users selects a 'region' from another select box.
On the same form, I want to automatically populate multiple 'team' fields with address details from the 'hotels' model when a user selects a 'hotel' from the selectbox.
The user can then modify the address ... all of this before the user clicks submit on the 'team' add view.
In Team\add.ctp view I have the following code:
echo "<div id='address'>";
echo $this->Form->input('address_1');
echo $this->Form->input('address_2');
echo $this->Form->input('address_3');
echo $this->Form->input('city');
echo $this->Form->input('postcode');
echo $this->Form->input('country');
echo "</div>";
...
$this->Js->get('#TeamHotelId')->event('change',
$this->Js->request(array(
'controller'=>'hotels',
'action'=>'getAddress'
), array(
'update'=> '#address',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true))
)
)
);
In my HotelsController.php I have:
public function getAddress() {
$hotel_id = $this->request->data['Team']['hotel_id'];
CakeLog::write('debug', print_r($hotel_id, true));
$address = $this->Hotel->find('first', array(
'recursive' => -1,
'fields' => array('hotel.address_1', 'hotel.address_2', 'hotel.address_3', 'hotel.city', 'hotel.postcode', 'hotel.country'),
'conditions' => array('Hotel.id' => $hotel_id)
));
CakeLog::write('debug', print_r($address, true));
$this->set('hotels', $address);
$this->set(compact('address'));
$this->layout = 'ajax';
}
hotels\get_address.ctp:
<?php
echo $this->Form->input('Team.address_1', array('value'=> $address['Hotel']['address_1']));
echo $this->Form->input('Team.address_2', array('value'=> $address['Hotel']['address_2']));
echo $this->Form->input('Team.address_3', array('value'=> $address['Hotel']['address_3']));
echo $this->Form->input('Team.city', array('value'=> $address['Hotel']['city']));
echo $this->Form->input('Team.postcode', array('value'=> $address['Hotel']['postcode']));
echo $this->Form->input('Team.country', array('value'=> $address['Hotel']['country'])); ?>
This now works and the code has been updated.
You can not do in that way as you are trying to accomplish. However, there is a way in which you can update as you want by passing an id from dropdown using ajax and populating all the other fields on the basis of that id. Please make sure in 'update'=>#id you should put the div id of a div containing all the fields you want to show on the page where you want your contents to appear on ajax request.
Note: Please follow the Richard link which you have given i.e. www.willis-owen.co.uk, it will definitely help you that you are trying to do.

Validation problems with multiple checkboxes (HABTM) on CakePHP form

Short version
I have some HABTM checkboxes on a form. Validation is working correctly (at least one checkbox needs to be checked for validation to pass) but the CakePHP error message divs aren't being generated as they should be.
Long Version
I have a from which allows users to fill in their name and email address and then choose from a list of brochures (checkboxes) they'd like to receive.
The form looks like this:
<?php
echo $this->Form->create('Request',array('action' => 'index'));
echo $this->Form->input('id');
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('Brochure',array(
'label' => __('Information Required:',true),
'type' => 'select',
'multiple' => 'checkbox',
'options' => $list,
'selected' => $this->Html->value('Brochure.Brochure'),
));
echo $this->Form->submit('Submit');
echo $this->Form->end();
?>
In my controller, $list is set as like this:
$this->Request->Brochure->find('list',array('fields'=>array('id','name')));
After reading the 2nd answer (posted by user448164) in HABTM form validation in CakePHP on Stack Overflow, I set my Request model up like this:
<?php
class Request extends AppModel {
var $name = 'Request';
function beforeValidate() {
foreach($this->hasAndBelongsToMany as $k=>$v) {
if(isset($this->data[$k][$k]))
{
$this->data[$this->alias][$k] = $this->data[$k][$k];
}
}
}
var $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => 'Please enter your full name'
),
'email' => array(
'rule' => 'email',
'message' => 'Please enter a valid email address'
),
'Brochure' => array(
'rule' => array('multiple', array('min' => 1)),
'message' => 'Please select 1'
),
);
?>
This actually works 99% well. If none of the checkboxes are checked, validation fails as it should do. However, the only problem is that Cake isn't setting the "error" class on the <div>, nor is it creating the <div class="error-message">Please select 1</div> as it should.
For name and email, there is no problem - the error divs are being created properly.
So, to clarify, validation is working for my HABTM checkboxes. The only problem is that the error divs aren't being generated.
I'm posting this here as this is actually a much better question than the related question you found.
I was banging my head against a wall trying to handle the same problem of getting the validation error to show up in the page. I'm using CakePHP v1.2 and I hit a similar problem although I have actually split out the HABTM into the individual tables i.e. Request->BrochuesRequest->Brochure. This is because I can't have it deleting and re-adding the joining table rows at will.
Firstly I think the accepted answer from your linked question assumes that you are doing a save / saveAll when the beforeValidate call is triggered, however I was doing it through a validates call. The difference is that you need to call the Request->set method first. It was an article by Jonathan Snook on Multiple Validation Sets pointed me to that issue.
The second issue is actually getting the error message to appear was down to the $field value you use when calling invalidate. For ages I was including the model as well as the field assuming that this was how it matched the invalidate call to the input, i.e. you have $form->input('BrochuresRequest.brochures_id') so you need $this->BrochuresRequest->invalidate('BrochuresRequest.brochures_id').
However that is wrong you just want $this->BrochuresRequest->invalidate('brochures_id').
<?php
// requests/add view
echo $form->input('BrochuresRequest.brochures_id', array('multiple' => true));
// requests_controller
function add() {
if (!empty($this->data)) {
$this->Request->create();
// critical set to have $this->data
// for beforeValidate when calling validates
$this->Request->set($this->data);
if ($this->Request->validates()) {
$this->Request->saveAll($this->data);
}
}
}
// request model
function beforeValidate() {
if (count($this->data['BrochuresRequest']['brochures_id']) < 1) {
$this->invalidate('non_existent_field'); // fake validation error on Project
// must be brochures_id and not BrochuresRequest.brochures_id
$this->BrochuresRequest->invalidate('brochures_id', 'Please select 1');
return false;
}
return true;
}
?>
A few of the other things that I picked up on the way through:
You don't need a separate $form->error in the view
I couldn't for the life of me get the 'multiple' validation rule to work in the model
The accepted answer checks for an isset but I believe that this isn't required and masked the problem of there being no $this->data being passed through.
The beforeValidate should return false if you want it to prevent any save action.

How to create a ground of checkbox in Cakephp? and how to store it?

I have a field called Hobbies, I wish to store all the hobbies selected by the user to be stored in the database as CSV. How can I do this in Cakephp?
Paste into view (ie, views/users/add.ctp)
<?php echo $form->create('User', array('action' => 'add')) ?>
<?php echo $form->input('User.hobbies', array('type' => 'select',
'multiple' => 'checkbox',
'options' => array('sports' => 'sports',
'movies' => 'movies',
'games' => 'games'))) ?>
<?php echo $form->end('Save') ?>
Paste into Users controller (just a standard save method, nothing special here)
function add() {
if(!empty($this->data)) {
if($this->User->saveAll($this->data, array('validate' => 'first'))) {
$this->Session->setFlash('User saved successfully');
} else {
$this->Session->setFlash('User failed to save');
}
}
}
Paste into User model
function beforeValidate() {
// join hobbies into csv
if(!empty($this->data['User']['hobbies'])) {
$this->data['User']['hobbies'] = join(',', $this->data['User']['hobbies']);
}
return true;
}
Notes:
If you need to separate the hobbies back out when reading the User model, you could use the "afterFind" callback or check out the Serializable Behaviour http://blog.matsimitsu.nl/code/206/serializeable-behavior-for-cakephp that automatically serializes and deserializes whenever you try to add or pull out an array to/from the db.
You could add the beforeValidate code to the beforeSave callback instead, just depends what kind of validation you want to perform. having the code in beforeValidate will let you do a basic notEmpty check, however in beforeSave will mean you can check individual items are present in the array.
References:
http://book.cakephp.org/view/76/Callback-Methods
http://book.cakephp.org/view/189/Automagic-Form-Elements

Resources