display radio buttons using FormHelper - forms

I am using CakePHP3
I am unable to decipher the documentation on using radio buttons to create for a list of results.
There is create radio button.
Which I tried this way:
foreach ($userGroups as $group_id => $group) {
echo $this->Form->radio("UserGroup.$group_id.id", ['value' => $group_id, 'label' => $group]);
}
There is using select pickers.
Which says all you need to do is set the type to radio. But I checked the api and it looks like it will unset the type.
Anyway, I tried
echo $this->Form->select("user_circle_id", $userGroups, ['type' => 'radio']);
Nothing works.
Please advise.
UPDATE:
$userGroups = [1 => 'Group 1', 2 => 'Group 2']; // basically primary key is keys and the display fields are the values.

Use following syntax :
$selectedStatus = 1;
$attributes = array('legend'=>false,'value'=>$selectedStatus,'class'=>'sortByStatusCourse','name'=>'sortByStatusCourse');
$options = array("1"=>"Active","0"=>"Inactive");
echo $this->Form->radio('is_active', $options,$attributes);
Code explanation :
We are passing parameters to cakePHP core so that it will output Radio button in HTML.
echo $this->Form->radio :
Here 1st param is Name on field in Database. 2nd param is What are the options for radio buttons , its value and text .3rd param is what are its attributes like what should be its default value here I explicitely set it to 1 so it will already tick radio with Activetext.
According to your code : echo $this->Form->radio("UserGroup.$group_id.id", ['value' => $group_id, 'label' => $group]);
I think order of param is wrong as you pass VALUE in 2nd param which should be 3rd param.Check my code.

Related

How to submit the value of a disabled form field?

This page actually a preview where user can't change anything,that he has given before.I have tried bellow code,
echo $this->Form->input('exchange_type', array(
'disabled' => 'disabled',
'empty' => '--Please Select--',
'options' => array(
'6' => 'POINT_TO_PRODUCT',
'7' => 'POINT_TO_GIFT',
'2' => 'POINT_TO_GAME'
)
));
Here field has disabled but it's sending null value to database.I am trying to send actual value that user has been selected.How can I do this ?
That's how HTML works, values of disabled elements are not being sent.
What you can do is using a hidden field, that's what the form helper automatically does when using for example checkboxes, in order to ensure that there's always a value being sent, as unchecked checkboxes do not submit any value, just like disabled inputs.
The hidden field should have the same name as the actual field, and it should be placed before the actual field, that way the hidden value will only be sent in case the following element is disabled.
echo $this->Form->hidden('exchange_type');
echo $this->Form->input('exchange_type', array(
'disabled' => true,
// ...
));
That would pick up the previously POSTed value for both the hidden input and the select input, and the hidden input would be submittable.
See also Cookbook > Helpers > FormHelper > FormHelper::hidden()

Retrieving values of Form::select

I have a select box with an array of data to populate it like this:
{!! Form::select('language',$languageArray,'null', ['id'=>'language','multiple',]) !!}
I am passing $languageArray with view , and is simply an array of values like ['A','B','C']...
Now while fetching the selected values i am getting numeric value of selected options. Is there a way to change the values from numeric indexes to Text written in option. i did it using an associative array as second argument like this:
['english' => 'English',
'french' => 'French',
'so on ...' => 'So On ..']
But it creates a long list and view seems to be overloaded with data is there a better way for achieving below output ???
<select name="language">
<option value="english" ">English</option>
<option value="french">French</option>
....
I suggest you to use Config values ,
Create a file like languages.php in config folder.
<?php
return ['english' => 'English',
'french' => 'French',
'so on ...' => 'So On ..'
'german' => Lang::get('languages.german')
];
View :
{!! Form::select('language',Config::get('languages'),'null', ['id'=>'language','multiple',]) !!}
As you can see, in this way you can use config values in another view too and support multi language(its important too.. look at 'german')
Last Option is creating your own Form macro for example,
Form::macro('slugiySelect', function($name , $list , $selected = null , $options = [])
{
$options = [];
foreach($list as $row)
$options[Str::slug($row)] = $row;
return Form::select($name , $options , $selected , $options);
});
In this macro your options array is slugify with Laravel string function and uses as a key , I kept value as yours. You can do it with your way.

Unit tests: manipulate dropdown options to pass form validation

I have a form with a mandatory dropdown, but initially is empty. I populate it using jquery (based by an autocomplete field results, I add the option on PRE_SUBMIT event) and is working fine.
The problem is that I can't submit the form in units tests, the list of possible values for my dropdown is empty and I got this error:
InvalidArgumentException : Input "myform[parent_id]" cannot take "10"
as a value (possible values: ).
This is my code in unit tests:
$form = $crawler->filter('#myForm')->form();
$params = array(
'myform[title]' => 'sample title',
'myform[parent_id]' => '10',
'myform[date]' => $date->format('Y-m-d')
);
$form->setValues($params);
$client->submit($form);
There is any way to manipulate / populate this dropdown to pass the validation?
Thanks!

CakePHP - input select not taking select options from a variable

I am developing an application with CakePHP 2.3.2 and I am having some trouble with an input select on a form. I am creating an array, in my Controller, which contains a list of states. In my View I find that when I use this variable in the 'options' field of the input I do not get any select options. If I do a print_r on the variable, in the view, I see exactly what I think I should be seeing for the 'options' field. I have even tried copying this print_r output and putting it in the 'options' field and then the input select works fine.
Here is what I have
In Controller
$options = 'array(1 => \'NSW\',2 => \'ACT\',3 => \'NT\');
$this->set('all_states, $options);
In View
<?php
$options = $all_states;
echo $this->Form->create('Refine', array('url => '/ServiceDirectoryResults/view/refine'));
echo $this->Form->input('field' ,array(
'type' => 'select',
'label' => false,
'options' => $options
));
echo $this->Form->end('Refine Search');
?>
When I run this I see a select with no select options
If I add print_r($options) after the echo $this->Form->end('Refine Search'); I see
array(1 => 'NSW',2 => 'ACT,3 => 'NT')
Which is what I would expect as it is the content of the $options variable which was the $all_states variable passed from the controller. If I take this output from the print_r and replace the $option with it in the input select the select drop down works fine and I see the three options. For some reason I can't work out the select is working fine if I hard code the select options but it will not work if I pass a variable containing the array to the input select.
I would really appreciate if if someone could give me a clue what I am doing wrong here.
Kind Regards
Richard
you might try it like below:
echo $this->Form->input('field', array('type'=>'select','label' => false,
'options' => $options,'default'=>'2'));
to the following HTML being generated:
<option value="2" selected="selected">ACT</option>
option two is shown instead any other one.
Likely issue:
Arrays should not be made as strings like you have:
$options = 'array(1 => \'NSW\',2 => \'ACT\',3 => \'NT\');
Instead, just make an array:
$options = array(1 => 'NSW', 2 => 'ACT', 3 => 'NT');
Other notes:
Why are you setting $options to $all_states only to set it back?
Missing quotes all over - make sure if you start quotes, that you also end them
not good practice to hard-code your URLs (like in your Form->create)

Add Database Row Button Cakephp

The Controller:
function add(){
if (!empty($this->data)) {
$qnote = $this->Qnote->save($this->data);
if (!empty($qnote)) {
$this->data['Step']['qnote_id'] = $this->Qnote->id;
$this->Qnote->Step->save($this->data);
}
$this->Session->setFlash('Your note has been saved.');
$this->redirect(array('action' => 'index'));
}
}
The Form.
<?php
$userID = Authsome::get('id');
echo $form->create('Qnote', array('action'=>'add'));
echo $form->input('Qnote.id', array('type' => 'hidden'));
echo $form->input('Qnote.user_id', array('value' => $userID, 'type' => 'hidden'));
echo $form->input('Qnote.subject');
echo $form->input('Qnote.body', array('rows' => '3'));
echo $form->input('Step.id', array('type' => 'hidden'));
echo $form->input('Step.user_id', array('value' => $userID, 'type' => 'hidden'));
echo $form->input('Step.body', array('rows' => '3'));
echo $form->end('Save Notes');
?>
This Form Adds Data in 2 Models.
Model 1 = Qnote;
Model 2 = Step;
I am able to add Data to the Models.
I was wondering I could add a button to the form
The Button would allow users to add multiple Step.data to the Step model.
Some like a +1 Button.
Basically I want to add multiple steps Per Qnote.
Could someone point me in the right direction how i can achieve this.
This is something I would do with jQuery. Basically all you need to do is using jQuery to dynamically add more inputs in the CakePHPs conventions: Step.0.user_id for example.
What you need to do now on a +1: you need to count the zero up, so you will get Step.1.user_id and so on.
First option: Use a jQuery-Script for doing this
var count = 1;
$('#add_step').click(function() {
var new_form = $('.Step').eq(0).clone();
$('input, textarea, select, radio', new_form).filter('[name^="data"]').each(function() {
var name = $(this).attr('name');
var new_name = name.replace(/\[\d*\]/, '['+count+']');
$(this).attr('name', new_name).attr('value', '');
});
$('#YourForm').after(new_form);
count+;
return false;
});
In this case you're cloning a div with the class step which holds your inputs for the model Step. You then replace the name-attribute to replace the zeros through the new value of the variable count. count++ enables you to add as many steps as you want.
This is an jQuery only solution and may require additional work for your environment.
Second option: Use AJAX with an element
You could also write a function in your StepsController which renders an element which holds your form and takes care of the counter.
Third option: Use a URL-parameter to decide how many options you want
If you have an URL like /qnote/add/3 you could use the 3 as a parameter in a for-loop to iterate through these form-inputs.
You need to take care, that eventually already typed in values are sent with the form when adding another Step so that these don't get lost.
Hope this helps to get on the right way.