Default value not overridden upon form submission - php

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.

Related

Onchange in Symfony2 form

This is my input type
->add(‘year’, ChoiceType::CLASS, array(‘choices’ => $array, ‘attr’ => array(‘onchange’ => ‘this.form.submit()’)));
Onchange page is reloading and data is submitted. Then in controller I can access value like this:
$_POST[‘year’].
The thing is I would like to get $_POST in symfony’s way:
$form[‘year’]->getData();
I don’t know why only $_POST[‘year’] works and no result with $form[‘year’]->getData().
You can use for POST request :
$request->request->get('year');
For GET request:
$request->query->get('year');
For FILE queries:
$request->files.
You can get a single item from the form data like;
$year = $form->get('year')->getData();
In this example 'year' is the name given to the field you are asking for (as per your form builder)

Store input from a text field in a PHP variable?

I'm fairly new to this, but I'm trying to costumize a plugin called democracy_poll for wordpress. It's a poll form where you can add your own answer. The answers get stored in the database, and what I need is to make the email input field I have created to output its value together with the answer (so I can contact the winner)
So like I said I have added an Email input field and would like to store the users input in a variable so I can see the input user email together with the answer they gave in the database.
I have added a new column in the database called author and added 'author' at the end of this code in the php file:
$exists = $wpdb->query(
$wpdb->prepare(
"SELECT aid FROM $wpdb->democracy_a " .
"WHERE answer = '%s' AND qid = $this->id",
$new_answer
)
);
if (!$exists)
if (
$wpdb->insert(
$wpdb->democracy_a,
array(
'qid' => $this->id,
'answer' => $new_answer,
'votes' => 0,
'added_by' => 1,
'author' => $author
)
)
)
with this, if
$author = "hello#email.com"
hello#email.com appears in the new column in the database next to the users answer.
So I'm wonder how to get the value from my email input box and store it in a php variable that I can use here?
My best guess so far has been $_POST["name"] but no luck :(
Thanks in advance!
W
You haven't posted any code of your HTML.
But, if you are using the value "name" in name attribute such as <input type="text" name="name"> then your $_POST["name"] will not work as "name" is a reserved name (or variable) for WP internal usage.
I suggest you to replace value in name attribute with something else like <input type="text" name="nameUnique"> and give it a go!
Thank you for your answers! We finally figured it out.
We had to define the variable for the email input in an ajax function,
then run a preg_match in the php file that handled the ajax data, against all the variables in the array to get the email address.
As I said I'm still new at this and it's very difficult for me to give you a detailed answer to my own question even though it was just solved.
I hope to keep learning and be able to contribute more in the future,
thanks again!!
W

optional_param in form

I have a question about the optional_param function in a form in PHP (version 5.3.14)
After looking over why certain fields were not being saved in a form I have, I realised that this data...
$checkdata = optional_param('items', array(), PARAM_INT)
Only saves up to 996 places (items) from the form (they are select items and there are many)....
Is this a setting or a something I can change? or alternatively something wrong from my end?
Thanks in advance
Solution : A moodle function (platform i am working with)
Thanks Pekka
this function is a moodle function. It gets a parameter from the current page URL.
For an example url:
http://moodle.dev/course/view.php?id=2&items=4
(this is chosen totally arbitrary)
Using this code:
$checkdata = optional_param('items', array(), PARAM_INT)
Will save the "items" value (here it's 4) in $checkdata. If items does not exist in the url it will do $checkdata = array()

Do query strings need to be manually sent to POST requests

This is a CakePHP / General PHP question.
In my application I use a query string like /login?continue=/admin/posts
This query string is used to redirect users to the URL in the query, but it doesn't work so it seems as though the app can't see the string...
This has got me wondering as basically when you arrive at the page with the string it's a GET request where as when you login, it becomes a POST or XML request (if using AJAX). Do I need to add the query string manually to the form for the POST to see it?
Either in the form action or a hidden input? Or am I barking up the wrong tree?
I'm currently grabbing the query like so:
if(isset($this->params['url']['continue']))
{
$pathtoredirect = $this->params['url']['continue'];
}
else
{
$pathtoredirect = $this->Auth->redirect();
}
But that's within the POST request so perhaps the query is lost... and adding it to a hidden input would not solve the problem with the current code so I would either change the code to look at the hidden field or pass the query with the action on the form?
e.g. <form action="/login?continue=/admin/posts" method="post">
Am I correct in thinking this? And would anyone be able to offer solutions or pros and cons of the two methods I mention?
In short I'm asking how to add the query string to my form action value
It currently looks like:
php echo $this->Form->create('User',
array(
'id' => 'loginform',
'type' => 'post',
'url' => array
(
'admin'=>false,
'controller' => 'users',
'action' => 'login'
)
)
);
So how would I add the query string to the form?
Thanks
When receiving a POST request you can receive both POST and GET variables through the superglobals $_POST and $_GET.
You can either send your paramater in $_GET by including it in the form's action attribute or send it in $_POST by creating an <input type="hidden"> tag within the form
A slash (/) is a reserved character. Encode it with %2F.
http://blooberry.com/indexdot/html/topics/urlencoding.htm#whatwhy
The solution was to do this:
<?php echo $this->Form->create('User',
array('id' => 'loginform', 'type' => 'post',
'url' => array('admin'=>false,'controller'=>'users','action'=>'login','url'=>$this->params['url']['continue']))); ?>
as I have a route already setup to handle the additional URL parameter:
Router::connect('/auth/login', array('controller'=>'users','action'=>'login'));
Router::connect('/auth/login?continue=:url',
array('controller'=>'users','action'=>'login'),
array(
'url' => '[A-Za-z0-9/\._-]+',
'pass' => array('url')
));
If anyone sees any issues with the way I do this though, please feel free to comment.

CakePHP Unfilled radio button changed to an unwanted value on submit

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')

Categories