CakePHP Unfilled radio button changed to an unwanted value on submit - php

I've got this form element:
$form->input('ChecklistResponseGovernmentInfo.driversLicenseIsOnline', array('type'=>'radio', 'empty'=> true, 'options'=>array(0 => 'No', 1 => 'Yes')))
This is the validation rule for it:
'driversLicenseIsOnline' => array(
'boolean' => array(
'rule' => array('boolean'),
'allowEmpty' => false,
),
),
And this is the database field for it (MySQL):
`driversLicenseIsOnline` tinyint(1) unsigned NOT NULL
When I first load a fresh copy of my form, the radio button set is unselected. If I submit the form without doing anything else, when the form reloads, the radio button is filled in as "No" and the validation flash message says "This field cannot be left blank".
The problem goes away when I stop using zero (0) as the value for "No", but I want Cake to store this value as a boolean, not as some other value that I would have to manually translate back and forth to boolean.
How do I stop Cake from automatically filling in a value for this element when it's submitted with no radio selected?

Stumbled onto this question while searching for the answer myself.
This nasty hack fixed it for me (in CakePHP 2.1 - should work in 1.3):
After you fail to validate, unset the value in $this->request->data if it's empty:
if ($this->Model->save($this->request->data) {
// data saved
}
else {
// data failed to save
// unset radio if empty
if ($this->request->data['Model']['radio_field'] == "") {
unset($this->request->data['Model']['radio_field'];
}
}
Ugh.

The way you have your radio buttons set up, there are actually 3 choices:
Nothing selected
'No' selected
'Yes' selected
Radio buttons should never have no choice selected (see point #9); (1) above shouldn't happen. So rather than answer your question directly, I'm going to say you should consider using a checkbox instead. Checkboxes are a natural fit for boolean values, and likely more usable in this case.
And Cake will assume you want a checkbox if the database field is tinyint(1), so you could then get rid of the options array in your FormHelper call.

Edit: ok, I don't think Cake automatically fill that value with 0, most likely it's a browser behavior. You can test that by debug($this->data) when the saving fails. (Just in case it does, you can unset that value there)

So I had a similar problem with a questionnaire, where it would be somewhat semantically correct for radio buttons to remain empty - when a yes or no question remains unanswered. In this case it doesn't seem right like this:
Do you smoke? [yes?]
And this is better:
Do you smoke? (yes)(no)
The way I solved this problem was 'options'=>array(1 => 'No', 2 => 'Yes')

Related

How to show a field after validateForm() is called in Drupal 8?

Inside a hook_form_FORM_ID_alter() function I show or hide a field based on another checkbox field is checked or not with the following code in Drupal 8.
$form['field_my_url']['#states'] = [
'visible' => [
':input[name="field_my_checkbox[value]"]' => ['checked' => TRUE],
],
];
In case user checks field_my_checkbox checkbox, enters an invalid URL in field_my_url and decides to uncheck field_my_checkbox checkbox, the field_my_url will then be hidden with the invalid URL remaining. It will fail the validation because the enter URL is not valid.
The user will then be redirected back with the error message. But because the field_my_checkbox checkbox was not checked, the field_my_url field will be hidden with the error message and the user cannot see that.
In this case, how can I show the field_my_url field if it failed the validation because it contains invalid URL in Drupal 8?
I have found a solution. It might not be efficient. But it solves the problem for now, since there is no one come up with any solution on this moment. If the validation failed. I just unset the '#states' from the field. By doing this, no #states visible will be applied and the field_my_url will be show as normal.
unsert($form['field_my_url']['#states']);

Default value not overridden upon form submission

I've got a hidden field inside a form, which I create using Drupal's form API like this:
$form['position'] = array(
'#type' => 'hidden',
'#default_value' => '57.149953,-2.104053',
'#attributes' => array(
'id' => 'geoposition',
)
);
When I load the page in which the form is rendered, I have a little bit of JavaScript that edits the hidden field like so:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, noPosition, 10);
}
function getPosition(position) {
var pos = document.getElementsByName("position");
pos.value = position.coords.latitude + "," + position.coords.longitude;
alert(pos.value);
}
Now, the last statement in this snippet actually outputs the correct value of the user's current position. However, when I submit the form, the value passed onto the server for manipulation is the default value, and not the updated value. The value to use after the form has been submitted is picked up like this:
$map_field .= 'src="http://maps.google.co.uk/maps?q='.$form_state['values']['position'].'&output=embed"></iframe>';
Any ideas?
Thanks,
This is what I wud do:
1) Disable to js for now.
2) Use xdebug to see the value before and after the form has been submitted. This should help to see if something is going wrong.
Cheers,
vishal
Rather than using #default_value, consider using #value - because that is the value that gets posted.
Eventually solved it by using the getElementById() method instead of getElementsByName() method. For some reason the name wasn't working. Thanks all for your help.

Populating posting.php message field from form submission on phpBB3 forum

I'm trying to add a form button that will take a variable string and insert it into $_POST['message'], such that when someone presses my 'post this on forum' button it takes them to the new topic page with my variable string already in the message textarea.
I've been messing with submit_post and have a form that submits a new post correctly when it's completed, however I don't want it to submit straight away; all I want is for it to load posting.php with my string already in the message field. Does anyone have any ideas?
You might have to modify the source of phpBB3 in order to do this. Unless posting.php is programmed to accept data from $_POST and insert it into the message textarea, you'll have to program it to do so.
As an alternative, you could try doing this with JavaScript: You could pass the text to posting.php in a cookie or a session variable which then displays in a hidden div or textarea or some other means (I'd need more specific information about your environment to provide specifics) and then insert that text into the textarea using JavaScript after the page loads. This should be more upgrade safe, but obviously requires users to have JavaScript enabled.
I found an alteration you can make to posting.php to let it accept get parameters
http://www.phpbb.com/community/viewtopic.php?f=46&t=2119831
Here it is for the sake of completion:
Find the following in posting.php:
if ($submit || $preview || $refresh)
Add the following on a line before it:
if( !$submit&& !$preview&& !$refresh&& !$save&& !$load&& !$delete&& !$cancel&& ( $mode== 'post'|| $mode== 'reply'|| $mode== 'quote' ) ) {
$post_data['post_subject']= utf8_normalize_nfc( request_var( 'subject', '', TRUE ) );
$message_parser->message= utf8_normalize_nfc( request_var( 'message', '', TRUE ) );
Voila! Test it with http://yourdomain/forum/posting.php?mode=post&f=2&subject=hello&message=world

sfValidatorChoice not working on multiple selection element

sfValidatorChoice is not working on multiple select element, my code
$this->form=new MyTestForm();
$options_array=array("php","python","java");
$widgetSchema["my_select"] =new sfWidgetFormChoice(array('choices' => $options_array,'multiple' => true,'expanded' => true ));
$validatorSchema["my_select"] = new sfValidatorChoice(array("choices" =>array_keys($options_array)));
Note: i have also tried using array_keys and by directly passing the array to sfValidatorChoice.
when i submit, it gives me Invalid error(when checked) and Required(when unchecked).
is there any error in parameters or is bug?
Firstly, you need to enable "multiple" in the validator as well as the widget:
"multiple" => true
To make having any selection optional, you need to set required to false:
"required" => false
Finally, I can't exactly remember how to use sfValidatorChoice (it's been a while), but I think it's best to make the values readable, so I'd do:
$options_array=array('php'=>'php','python'=>'python','java'=>'java');
I'm not certain this will fix the problem, but it may well do.

Content of form element not being saved to database while others are

I am working with a CMS like system, phpBMS, which defines a certain way of making forms, and defines the form elements to be used in such forms.
This is an example of the form template, and these are the fields that are defined.
Generally, it is pretty simple. If you have an inputField with the id of say, 'name', the content of that field will be saved to the name field in the table the form is assigned to.
Currently, I am using a different input field, inputSmartSearch, which works a bit like google suggest as it can search and automatically display results as you type.
I want to use the content of this field to go into a 'product' table, but I am unsure of how to set this up.
I am calling my smartsearch like so:
$theinput = new inputSmartSearch($db, "chooseproducts", "Choose Product",$therecord["product"], "Choose Product", TRUE, NULL, NULL, TRUE, $required=true);
$theinput->setAttribute("class","important");
$theform->addField($theinput);
When I look what is returned by _POST, I see:
Array ( [chooseproducts] => 75c72a6a-83d9-11df-951a-fa9c1ec271f2 [ds-chooseproducts] => Corona [quantity] => 2 [type] => cash)
I have setup the quantity and type fields like so
$theinput = new inputField("quantity",$therecord["quantity"],"Quantity",true, NULL, 1);
$theinput->setAttribute("class","important");
$theform->addField($theinput);
$theinput = new inputBasicList("type",$therecord["paymenttype"],array("Cash"=>"cash","Credit"=>"credit"), "Payment Type");
$theinput->setAttribute("class","important");
$theform->addField($theinput);
The content of the type and quanitity fields get insert into the database perfectly, but absolutely nothing gets inserted from the smartsearch field.
Why? How would I start to troubleshoot this?
I think in this case you would need to manually add this value to the array that is persisted to the database. So:
$variables["product"] = the value you want
So if you san. To persist the name assign Ds-chooseproducts. If you want to persist the id then use chooseproducts from the array.

Categories