multiple checkboxes with cakephp 1.2 - cakephp

I have a page with a list of books, and every row has a checkbox. (I'm using cakephp 1.2).
I want to let the user to save multiple books.
For now I have this checkbox in my view (in a cycle, where I get the list of all books):
<?php echo $form->input('salva', array('value' => $cdBiblio['CdBiblio']['codiceBiblio'], 'label' => '', 'type' => 'checkbox')); ?>
This form:<?php echo $form->create('cd_biblios', array('action' => 'save')); ?>
And this button:
<?php echo $form->end('Add All');?>
In the controller, I have something like this for debugging:
debug($this->data);
foreach($this->data['cd_biblios']['salva'] as $item) {
debug($item);
}
But it's not working.
I noticed that it takes only the last book id of the list with debug($this->data); and if I check more than 1 book, it show 0 or the last book id, for example:
Array (
[cd_biblios] => Array
(
[salva] => 0
) )
SOLVED:
In the view I use Danial's code.
In the controller I use this code:
if(!empty($this->data)) {
$item=$this->data;
debug($item);
$dim=count($item['Model']['field']);
$i=0;
for ($i=0;$i<$dim;$i++)
if ($item['Model']['field'][$i]!=0)
{
$data = $this->Session->read('libri');
$data[] = $item['Model']['field'][$i];
$this->Session->write('libri', $data);
}
$this->Session->setFlash(__('I libri sono stati salvati', true));
$this->redirect($this->referer());
}

In View:
<?php
foreach($array as $each_elem) {
echo $form->checkbox(
'Model.field',
array(
'id'=>'abcd_'.$each_elem['Model']['id'],
'value' => $each_elem['Model']['id'],
'hiddenField' => false,
'name' => 'data[Model][field][]',
'label' => false,
'div' => false,
));
}
?>
On submit the form, you will get the checked values in controller in $this->request->data

You have a conception problem.
Your checkboxes must be inside a form, because they are input tags. So, to send those values to the controller you'll need to submit that form. In your code, i see that "Add All" is just a link. And a link won't submit the form.
Change your link to a button :)
Hope this helps

Related

cakephp canot save form control field in database

i am trying to make an simple cakephp aplication!
I have a form that creates a new article.. my problem is that i have an input field for the artice slug but when i cakephp submits te form the slug field in database remains empty..
here is the add method from my articleController
public function add(){
$article = $this->Articles->newEntity(); //gffdgfd
if ($this->request->is('post')){
$this->Articles->patchEntity($article, $this->request->data());
if($this->Articles->save($article)){
$this->Flash->success(__('Your Article has been saved!'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Cannot save article! Please try again!!'));
}
$this->set('article', $article);
}
and my add.ctp
<h1>Add Article</h1>
<?php
echo $this->Form->create($article);
echo $this->Form->control('user_id', ['type' => 'hidden', 'value'=> 1 ]);
echo $this->Form->control('published', ['type' => 'hidden', 'value'=> 1 ]);
echo $this->Form->control('title');
echo $this->Form->control('slug');
echo $this->Form->control('body', ['rows' => 5 ]);
echo $this->Form->button(__('Save Article'), ['class' => 'button', 'style' => 'margin-right:10px; margin-left:10px']);
echo $this->Html->link('Back', ['action' => 'index'], ['class' => 'button']);
echo $this->Form->end();
?>
If slug field is present in your request data, then you should check if this field is accessible for assignment in your entity. Look at file src/Model/Entity/Article.php, on top of class body you will have an array named $_accessible - check if your slug field is present, and if not, set it to true:
protected $_accessible = [
/* other fields */
'slug' => true
];
Please check more about assignment of properties in docs: CakePHP 3 Entities - Mass Assignment

Form Dropdown Not Registering in Codeigniter

I have created a registration form that has a dropdown field, but I am unable to get it to link into the database to register the selection. I have form validation turned on, but it keeps saying that no value has been selected.
My other inputs work, as they're user entered. However, the values in this dropdown do not register as any value. Any assistance would be appreciated.
Thanks!
View
<div class = "form-group">
<?php echo form_label('Mobile Carrier'); ?><br/><!--Form Label-->
<?php
$data = array(
'None' => 'None',
'att' => 'AT&T',
'verizon' => 'Verizon',
'sprint' => 'Sprint',
'tmobile' => 'T-Mobile'
);
?>
<?php echo form_dropdown('Mobile Carrier', $data, 'None'); ?>
Controller
public function register(){
$this->form_validation->set_rules('mobile_carrier', 'Mobile Carrier', 'required'); }
User Model
public function create_user(){
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'phone_number' => $this->input->post('phone_number'),
'mobile_carrier' => $this->input->post('mobile_carrier'),
'username' => $this->input->post('username'),
'password' => $encrypted_pass
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}
you are assigning the wrong name attribute when creating the dropdown list:
<?php echo form_dropdown('Mobile Carrier', $data, 'None'); ?>
the name attribute must match your $this->input->post('mobile_carrier') in your model. so the correct use would be:
<?php echo form_dropdown('mobile_carrier', $data, 'None'); ?>
more information: https://www.codeigniter.com/userguide3/helpers/form_helper.html, scroll to form_dropdown([$name = ''[, $options = array()[, $selected = array()[, $extra = '']]]])

how to combine two HABTM saves in one form in CakePHP?

I have two models Business and User. They are related by a HABTM relationship.
Everything is working with the baked controllers, models and views.
Now I'm trying to combine the two models in one form so the user can enter a business name with is user info.
Here's the form :
Form->create('User'); ?>
Form->input('Business.name', array('label' => __('Business name')));
echo $this->Form->input('User.email');
echo $this->Form->input('User.firstname');
echo $this->Form->input('User.lastname');
echo $this->Form->input('User.password');
echo $this->Form->input('User.phone_cell', array('type' => 'text'));
echo $this->Form->input('User.phone_home', array('type' => 'text'));
echo $this->Form->input('User.phone_work', array('type' => 'text'));
?>
Form->end(__('Submit')); ?>
The only way I was able to make it work was to save the User first and then get the user id and save the business after by adding the user array with the new id.
if ($this->User->save($this->request->data)) {
$this->request->data['User'] = array('User' => array(0 => $this->User->id));
if ($this->User->Business->save($this->request->data)) {
// User saved
} else {
// User not saved
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
I tried the saveAll method without success. Is is possible to optimize this the CakePHP way for a single save ?
Thanks
I was able to get it to work myself with a couple models named User and Group. Here's some snips from my code to show how I did it:
UsersController.php
public function edit($id = null)
{
$this->User->id = $id;
if ($this->request->is('get')) {
//On page load load the user data
$this->request->data = $this->User->read();
} else {
//Saving
if ($this->User->save($this->data)) {
//....snipped...
} else {
$this->Session->setFlash('Unable to update the user.');
}
}
//Build $groups array for form
// Only admins can assign admin rights
if ($this->isMember('Admin')) {
$this->set('groups',$this->User->Group->find('list'));
} else {
$this->set('groups',$this->User->Group->find('list',array(
'conditions' => array(
'Group.name !=' => 'Admin'
)
)));
}
//...more snipping...
}
edit.ctp (View)
echo $this->Form->create('User', array('action' => 'edit'));
echo $this->Form->input('User.username');
echo $this->Form->input('Group',array(
'type' => 'select',
'multiple' => true,
'label' => "Group (Select multiple entries with CTRL)",
'size' => count($groups)
)
);
//More snipping
With that example to work from, how are you validating that the Business.name entered is valid and can be matched to the HABTM relation? Mine forces a selection list in this case. My Model is extremely simple so I didn't include that.
What are your outputs to debug($this->data); vs. debug($this->request->data)?

Cakephp 1.3 select field options from list or enter new

I have a cakephp 1.3 app which get's a person's consent to participate in a study. I'm trying to link inclusion criteria and exclusion criteria for the study on the Add study page. The HABTM relationship is setup and working(If there's only one way to select them) What I'm trying to do now is display the current Inclusion Criteria as a list of checkboxes the person adding the study can select, but I also want a field where new criteria can be entered as a comma seperated list. Right now it will save the checkboxes, but I want it to also add the text entered in the field as well. Screen showing the Add study as it sits now is below. I don't really know how I would go about doing that. Is there a way to do this or will I have to take the data entered, sort through it and then add it to $this->data[inclusion field data]? An example would be nice. :) I've added the code I have so far below the image.
Controller:
/**
* Add a study.
*/
function add() {
if (!empty($this->data)) {
//get the inclusions from the text data
//Sort through the comma seperated list and add it to $this->data['Study']['Inclusions']???
$this->Study->create();
if ($this->Study->save($this->data)) {
$this->Session->setFlash(__('The study has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The study could not be saved. Please, try again.', true));
}
}
$this->set('inclusions', $this->Study->Inclusion->find('list', array(
'fields' => array('id', 'name'),
'order' => 'Inclusion.name',
'recursive' => 0,
)));
$this->set('exclusions', $this->Study->Exclusion->find('list', array(
'fields' => array('id', 'name'),
'order' => 'Exclusion.name',
'recursive' => 0,
)));
$this->set('forms', $this->Study->Form->find('list', array('order' => 'Form.name','recursive' => 0,)));
}
View:
<div class="studies form">
<?php echo $this->Form->create('Study', array('type' => 'file'));?>
<fieldset>
<legend><?php __('Add Study'); ?></legend>
<?php
echo $this->Form->input('studyname', array('label'=>'Study Name','required' => true));
echo $this->Form->input('studynumber', array('label'=>'Study Number','required' => true));
echo $this->Form->input('file', array('label'=>'Select Electronic Consent','type' => 'file'));
echo $this->Form->input('consent_form_date');
?>
<fieldset class="inclusion">
<legend><?php __('Inclusions'); ?></legend>
<div class="IncExc">
<?php
echo $this->Form->input('Inclusion',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $inclusions,
'selected' => $html->value('Inclusion.Inclusion'),
));
?>
</div>
<?php
echo $form->input('Inclusion.inclusions',array(
'type' => 'text',
'label' => __('Add New Inclusions',true),
'after' => __('Seperate each new Inclusion with a comma. Eg: family, sports, icecream',true)
));
?>
</fieldset>
<fieldset>
<legend><?php __('Exclusions'); ?></legend>
<div class="IncExc">
<?php
echo $this->Form->input('Exclusion',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $exclusions,
'selected' => $html->value('Exclusion.Exclusion'),
));
?>
</div>
</fieldset>
<fieldset style="width: 700px;">
<legend><?php //__('Forms'); ?></legend>
<?php /*
echo $this->Form->input('Form',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $forms,
'selected' => $html->value('Form.Form'),
));
*/ ?>
</fieldset>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
You are trying to do pretty much the same as he wanted to do: Saving tags into a database table in CakePHP
What you have to do is:
Check if the manual inclusion field is empty or not. If the field is empty ignore it and go to step 5
If the field is not empty, split it at comma or whatever sign you want to use as a seperator. You can now validate it if you want to.
Use all the inclusions of step 3 and save them in your custom or real inclusion table. You should keep track of those custom entries in some way, so you don't mess them up with those you provided. Save all the ids generated while saving within an array.
Merge the collected ids of step 3 with those you got from the form which were given by you.
Save all collected and given data to database
The answere in the post given above including the code there can be used to do that. You should get along with it pretty well if you read the whole post + code comments ;)
If you have any further questions, just ask ;)
Greetings
func0der

CakePHP drop down, selected item redirect to view for item

I would like to have the drop down list drugs, redirect to the view for the specific drug chosen. So say they click the drug "Acetamenophen" I want it to send them to the view for that drug. Can I do that without adding a submit button?
Code I have for the drop down:
<?php
echo $form->input('Drug.generic', array('type' => 'select', 'label' => 'Quick Select:',
'empty' => 'Select', 'options' => $alldrugs)
);
?>
Index controller action(View the drop down is on)
function index() {
$this->set('drugs', $this->Drug->find('all'));
$this->set('alldrugs', $this->Drug->find('list', array('fields' => array('id','generic'), 'order' => 'Drug.generic', 'recursive' => -1,)));
}
You can store you root url in a js variable in default.ctp like following:
put this code within default.ctp <head></head> section.
<script>
var _ROOT = "<?php echo $this->Html->url('/', true); ?>";
</script>
And within the <head> tag append this line before </head> end:
<?php echo $this->Html->script(array('jquery', 'drug_list')); ?>
Then use the _ROOT like following:
window.location = _ROOT + 'drugs/view/' + val;
Place jquery library and make a YOURNAME.js file in app/webroot/js folder and place following code with YOURNAME.js file.
YOURNAME is as you like
$(function() {
$('#ID_OF_YOUR_SELECT_BOX').change(function() { // replace the ID_OF_YOUR_SELECT_BOX with the id to your select box given by Cake
var val = $(this).val(); // val is the drug id
window.location = _ROOT + 'drugs/view/' + val;
});
});
i'd put the select inside a form without the submit button, and add a onclick to the select (you don't actually need a whole framework for it):
<?php
echo $form->input('Drug.generic', array('type' => 'select', 'label' => 'Quick Select:',
'empty' => 'Select', 'options' => $alldrugs, 'onchange'=>'this.form.submit();')
);
?>
of course in the controller you'd have to check the this->data and redirect the user to the correct page depending on the select, or if you dont want to redirect the user, just change the condition on the find().
Hope this helps,
With a mix of jQuery and PHP, you can redirect directly to the action you want:
<?php
echo $form->input('Drug.generic', array('type' => 'select', 'label' => 'Quick Select:',
'empty' => 'Select', 'options' => $alldrugs, 'id' => 'drug_select')
);
?>
$(document).ready(function(){
$("#drug_select").change(function(){
var drug_id = $(this).val();
if(drug_id.length > 0)
{
window.location = "<?php echo Router::url(array('controller' => 'drugs', 'action' => 'view'), true) ?>/" + drug_id;
}
});
});

Resources