symfony setting value of specific checkbox widgets in form - symfony-1.4

I have a widget defined with a series of checkboxes that is essentially used to build up a bit flag. So I have a DB column 'access_bits', and I have several checkboxes generated on in the form class, in the format of 'access_bits[]', with the appropriate values (i.e. 1,2,16,1024 etc)
following the solution on this post (Symfony: How to change a form field attribute in an action?) - which is simple and sensible - I am able to magically set the attribute for all the checkboxes. But how can I target specific ones (preferably by value)?
TO CLARIFY:
HTML:
<input name="user[access_bit][]" value="1" /> Level 1
<input name="user[access_bit][]" value="2" /> Level 2
<input name="user[access_bit][]" value="4" /> Level 3
<input name="user[access_bit][]" value="8" /> Level 4
In the DB I have a column that has a bitwise integer. So for example, to have Level 1 and Level 2 checked, the value in the column would be 3. To have them all checked, the value would be 15.
"What I Want" PHP in action.class.php
$exampleValue = 4;
foreach ($form->getWidget('access_bit') as $thisWidget)
{
if ($thisWidget->getValue() == $exampleValue)
{
$thisWidget->setAttribute('checked','checked');
}
}
... which would cunningly set the checkbox next to Level 3 as ticked.
I do not want to use jQuery to do this.

you can try this....on your form save you can use this
$samplevar = $this->your_form->save();
$samplevar->setYOURFORMFIELDNAME(array of values(1,2,3));
$this->sample = YOURFORM($samplevar);
or,
on showing the form in first you can also pass the value in form while setting
$this->samplevariable = YOURFORM($this->getYOURMODEL->setYOURFORMFIELDNAME(array of values(1,2,3) which u get form db getYOURFORMFIELDNAME);
if you have values in comma seperated you cane use explode directly
$samplevar = $this->YOURFORMNAME->save();
$samplevar->setYOURFORMFIELDNAME(explode(',', $samplevar ->getYOURFORMFIELDNAME()));
$this->YOURFORMNAME = new YOURFORMForm($samplevar);

Try using the setDefault method :
$thisWidget->setDefault(array($examplevalue));

Related

HtmlInputText Name property is not working and replace by ID

I am creating a series of input text controls from asp.net codebehind. I am using the below code, but this code doesn't set the name attribute in input control instead ID is set to the name attribute of input control. How to make name attribute different from ID.
HtmlInputText sno = new HtmlInputText();
sno.ID = "txtSno" + j;
sno.Name = "txtSno-name";
sno.Value = snoList[i].ToString();
sno.Attributes.Add("class", "form-control");
cellsno.Controls.Add(sno);
This is the final html which is rendered
<input name="txtSno1" type="text" id="txtSno1" value="1" class="form-control">
Expected is
<input name="txtSno-name" type="text" id="txtSno1" value="1" class="form-control">
You can't change the name property of the input using the HtmlInputText object's Name property.As mentioned in Microsoft docs here
Use the Name property to determine the unique identifier name for an
HtmlInputControl. In this implementation, the get accessor returns the
value of the Control.UniqueID property. However, the set accessor does
not assign a value to this property.

GWT - Get the value of a checkbox from a servlet [duplicate]

I have an html form and i would like ALWAYS to have checkboxes to submit a value. How can i do that? I have one idea but i havent tried it and i am unsure if its the best way to do it (jquery to check if the box is checked or not, then set the value to 0/1 and check it off so it will submit)
Thanks to #Lazarus' idea, also mentioned by #BalusC, you can add an additional control to the form:
<input type="hidden" name="checkbox1" value="off">
<input type="checkbox" name="checkbox1" value="on"> My checkbox
Checkbox and the hidden fields must have the same name. The hidden input is always submitted as a default value. If the checkbox is checked then also it's submitted. So you have a list of 2 values for parameter "checkbox1", that you have to treat at server side.
...maybe a <select> tag would be more handy.
There is a legitimate reason for asking for something like this, although the behaviour envisioned here is not the right way to go about it. There is a problem with the checkbox when used correctly when editing existing data and that's that there is no way to determine whether no value was submitted because the field was not present on the form or because the user cleared all of the values. You can run into this sort of problem any time you include fields conditionally.
One could go to the trouble of maintaining a "view state", of course, but it's much easier to include a hidden "companion field" whenever a checkbox or select with the multiple option (which is also excluded when all selections are cleared) is displayed. The field should have a related but different name (a name from which the actual field name can be extracted). The Lotus Domino server has used fields named %%Surrogate_FieldNameHere for this purpose since (I believe) version 7 for exactly the reason I described here.
To tell you the truth, this feels like a big no-no.
Anyway here goes:
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function () {
$(this).attr('value', $(this).is(':checked') ? '1' : '0');
$(this).attr('checked', true);
});
});
});
</script>
HTML doesn't work that way. HTML checkboxes are specified as follows: if checked, then its name=value will be sent as request parameter. If unchecked, then its name=value will not be sent as request parameter. Note that when the value is unspecified, then most browsers default to "on". It's easier if you give all checkboxes the same name but a different and fixed value. This way you can obtain the checked ones as an array/collection.
If all checkboxes are already known beforehand in server side, you can just apply basic math to obtain the unchecked checkboxes:
uncheckedCheckboxes = allCheckboxes - checkedCheckboxes
If those checkboxes are created dynamically at the client side and therefore unknown beforehand in server side, then add for each checkbox a <input type="hidden"> field containing information about the dynamically created checkbox, so that the server side knows which checkboxes are all present as the moment of submission.
Although this goes against the HTML spec, if you know what you are doing, using this you no longer have to cater checkboxes which are handled completely differently when submitted - and for example naming fields with_brackets[] can actually be useable.
Complete solution
$(document).on('submit', 'form', function() {
$(this).find('input[type=checkbox]').each(function() {
var checkbox = $(this);
// add a hidden field with the same name before the checkbox with value = 0
if ( !checkbox.prop('checked') ) {
checkbox.clone()
.prop('type', 'hidden')
.val(0)
.insertBefore(checkbox);
}
});
});
Take note: the non-checked checkboxes now submit a value of "0"
Additionally, if you want to change the behaviour of a single form only, just alter the first line in the above snippet:
$(document).on('submit', 'form.your-class-name', function() {
// ...
});
if you have many checkbox, you can try this code:
<input type="checkbox" onclick="$(this).next().val(this.checked?1:0)"/> <input type="hidden" name="checkbox1[]"/>
If you have the following HTML:
<form id="myform" method="post" action="my/url">
<input type="checkbox" id="checkbox1" name="checkbox1"/>
<input type="checkbox" id="checkbox2" name="checkbox2"/>
<input type="checkbox" id="checkbox3" name="checkbox3"/>
</form>
Normal form submit:
On form submit, before submitting, change all values of checkboxes to 0 and 1 based on if checkbox is unchecked or checked. Like so:
$('#myform').submit(function() {
var $checkboxes = $('#myform').find('input[type="checkbox"]');// Select all checkboxes
$checkboxes.filter(':checked').val(1);// Set value to 1 for checked checkboxes
$checkboxes.not(':checked').val(0);// Set value to 0 for unchecked checkboxes
$checkboxes.prop('checked', true);// Change all checkboxes to "checked" so all of them are submitted to server
});
Note: Ugly thing about this code, while form is submitting, all checkboxes will appear as "checked" for a moment. But if you apply same concept for ajax form submit, it would be better.
AJAX form submit:
$.post('my/url', {
'checkbox1': $('#checkbox1').is(':checked') ? 1 : 0,
'checkbox2': $('#checkbox2').is(':checked') ? 1 : 0,
'checkbox3': $('#checkbox3').is(':checked') ? 1 : 0
}, function(response) {
// Server JSON response..
}, 'json');

RadioButtonList and their 'Value' property

I was wondering about the 'Value' property of an item in a RadioButtonList.
If I want to get the value of the selected Radio Button that is in the list, these must be unique or it will auto-select the first item it finds with the value I'm looking for. So no duplicate values.
Why is this? I've looked around the net, used them, and such so I know HOW it is working, but I would like to know WHY it works this way.
If I select an item in the list, it knows which item I selected. The button fills in, you can get the index of the item that is selected...so why doesn't it go: "Okay, you selected the item at index X. You also want the value? Okay, let me access the list, go to item X and get its value."
I can only think that when you want the value of an item, it is looking by value rather than by index then by value?
UPDATE 1:
In my particular case I was doing this:
I have 1 RadioButtonList that has 3 items(RadioButtons) in it. The following Select...Case occurs inside of a button click.
Select Case RadioButtonList1.SelectedItem.Text
Case "TextA"
Case "TextB"
//This RadioButton has a value of 200
Case "TextC"
//This RadioButton has a value of 200
End Select
This works for the first Case and only ONE other. As I debugged, the first and second cases went through fine. When I selected the third RadioButton, then execute the event, it will automatically select the second RadioButton because it has the same value as the third, but comes first in the list.
Changing one of the identical values fixes this.
Not sure I completely understand, Do you have your HTML, script to share? You might have a problem if you're using duplicate IDs to group the radio button set; you should just use same name attribute. In that case, if you try to get the value using selectElementById it will just grab the first one.
Since you "want to get the value of the selected Radio Button that is in the list", you can get that array of same-named inputs (getElementsByName) and loop through and look for the 'CHECKED' condition:
<input type="radio" name="cars" value="beamer" checked="checked">BMW<br><br>
<input type="radio" name="cars" value="prius">Prius<br><br>
<input type="radio" name="cars" value="volvo">Volvo<br><br>
<input type="radio" name="cars" value="beamer">BMW<br><br>
<input type="radio" name="cars" value="prius">Prius<br><br>
<input type="radio" name="cars" value="volvo">Volvo<br><br>
<p>Selected Car Value and Index:</p>
<div id="selectedCar"></div><br><br>
<button onclick="getVal()">Get Value and Index</button>
<script>
var getVal = function(){
var cars = document.getElementsByName('cars');
var result = document.getElementById("selectedCar");
for (var i = 0, length = cars.length; i < length; i++) {
if (cars[i].checked) {
result.innerHTML = "value: " + cars[i].value + " and index: " + i;
break;
}
}
}
</script>

Search wordpress using three different drop down menus

I have three drop down menus that are chained together. Year, Make Model. I need wordpress search results to show their matching results. If I give them all the name="s" then it only searches the final s= in the url.
I basically need to know how to make
mysite.com/?s=2001&s=Chevrolet&s=Express&Search=Search
turn into:
mysite.com/?s=2001+Chevrolet+Express&Search=Search
or whatever gets the job done.
Any suggestions?
I would not name the selects. Instead, give them ids and make a hidden form field, then use javascript to update the hidden field.
function updateHiddenField(){
var year = document.getElementById("YearDD").value; //this is conceptual
var make = document.getElementById("MakeDD").value; //this is conceptual
var model = document.getElementById("ModelDD").value; //this is conceptual
document.getElementById("s").value = year+"+"+make+"+"+model; //this is conceptual
}
Then later...
<input type="hidden" name="s" id="s" value="">
<select id="YearDD" onChange="updateHiddenField();">
...
Otherwise you could overwrite the "Submit" Button, generate your own query string/url and redirect the page.
Or, in a real dirty way, you could just search the string and convert "&s=" with "+".

MVC2 Checkbox problem

When I used the html Helper Checkbox, it produces 2 form elements. I understand why this is, and I have no problem with it except:
The un-checking of the checkbox does not seem to be in sync with the 'hidden' value.
What I mean is that when I have a bunch of checkboxes being generated in a loop:
<%=Html.CheckBox("model.MarketCategories[" & i & "].Value", category.Value)%>
and the user deselects and checkbox and the category.Value is FALSE, the code being generated is:
<input checked="checked" id="model_MarketCategories_0__Value" name="model.MarketCategories[0].Value" type="checkbox" value="true" />
<input name="model.MarketCategories[0].Value" type="hidden" value="false" />
This is wrong since the Value is False the checkbox should NOT be checked.
Any ideas why this is happening?
What's worse, is when it's submitted, it shows up as "true,false". Very frustrating.
When you check the box programmatically, it doesn't set the associated hidden field. You can easily work around this by writing the markup for the checkbox directly instead of using the MVC control.
I've had to do this myself just recently. It's a pet peeve of mine.
See this link for more information on this.
This won't work for me because I am using Strongly Typed views/controllers.
I don't use:
public ActionResult ThisLooksWeird(FormCollection result)
{
var winnars = from x in result.AllKeys
where result[x] != "false"
select x;
// yadda
}
I use:
public ActionResult ThisLooksWeird(MyCustomModelObject result)
{
foreach (KeyValuePair<MarketCategory, Boolean> o in result.Categories) {
If (o.Value == True) {
// yadda
}
}
}
Now when I adapt my code to work as suggested in your posting, the Mapping between the two controls (checkbox/hidden) is still incorrect. It takes the value of the hidden component (which is always the value which was there when the page was loaded) instead of the checkbox which is what the value should be now.
Okay, looks like David was right. It was my misunderstanding of exactly how the two fields work together that cause his solution not to work for me.
In case this helps anyone else here is my solution and how it works:
First I had to hand craft the two fields as David had described...
<input <%
If category.Value = True Then
%> checked <%
End If
%> class="filterCheckbox" id="model_MarketCategories_<%=i%>__Value" name="model.MarketCategories[<%=i %>].Value" type="checkbox" value="true" />
<input name="model.MarketCategories[<%=i%>].Value" type="hidden" value="False" />
Now a quick recap of why there are 2 fields:
// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.
Now the reason both of the elements have the same name is this: If the browser will ignore all other input values with the same name once it has found one with a valid value. So if your browser always returns the value of the checkbox (regardless of whether it is checked or not) then the hidden element is ignored. If on the other hand your browser does not send the checkbox value if the checkbox is not checked, then the element immediately following the checkbox will set the value of the form property to false and return THAT.
My misunderstanding was that I thought the checkbox should always store the value of actual property, so something like:
<input <%
If category.Value = True Then
%> checked <%
End If
%> class="filterCheckbox" id="model_MarketCategories_<%=i%>__Value" name="model.MarketCategories[<%=i %>].Value" type="checkbox" value="<%=category.Value %>" />
This is what was causing issues... the checkbox 'value' should always be true. The hidden 'value' should always be false. And it is the state of the checkbox (checked or not) that will determine which gets returned to your controller.
Thanks David... sometimes the answer can be right in front of you but if your brain is not ready to receive, there's nothing a fellow programmer can do ;-)

Resources