Coldfusion ignores posted html array fields - coldfusion

I am posting an html form which multiple input names look like that: left_impedance_TYMP[]
However when accessing them in coldfusion, it ignores empty fields.
FORM["left_impedance_TYMP[]"]
Inspecting POST request seems correct.
Is there a solution on this?

When you have multiple form fields of the same name, with or without brackets, both a GET and a POST ignore empty fields values.
Form:
<form action="brackets_process.cfm" method="GET">
<input type="text" name="foo" value="A"><br>
<input type="text" name="foo" value="B"><br>
<input type="text" name="foo" value="C"><br>
<input type="text" name="foo" value="D"><br>
<button>Submit</button>
</form>
Processing:
<cfdump var="#url#" label="URL">
<p></p>
<cfdump var="#form#" label="FORM">
A GET querystring brackets_process.cfm?foo=A&foo=B&foo=C&foo=D
A POST brackets_process.cfm
If you add brackets to foo[], the querystring is encoded and the struct key contains the brackets.
brackets_process.cfm?foo%5B%5D=A&foo%5B%5D=B&foo%5B%5D=C&foo%5B%5D=D
A POST is still a list of submitted values.
Converting POST data to an array.
PHP automatically converts field names that end with a bracket to an array. ColdFusion has an application.cfc setting this.sameformfieldsasarray=true; that #Alex linked. Problem is that its a global setting and could change a considerable amount of existing functionality.
With that setting on, a POST converts the values to an array.
A GET sticks to a list. So if you leave out a value (B), the value of url["foo[]'] is a list with 4 elements, where the 2nd element is empty.
Leaving a value (B) out of a POST, however, returns an array with 4 elements, where the 2nd value is empty.
So you need to determine if you want to make a global change that affects all current functionality or if you can add some conditional logic that checks the number of elements in a list vs. the expected number of fields.
I've written code in the past that named fields something like name="fieldName.#counterValue#", then parsed the field names to set positional values in a list or array to account for empty values.

Related

Multiple Regex Validation against a value

I want to validate a text box input with below requirement
Text must be integer
Value of text must be between a predefined Max Value and predefined Min Value
** I don't want to use RangeAttribute.I want to use regular expression which I want to store in database and will get applicable when View will get rendered.
How we can do this in c# using multiple regex?
IF you want to restrict it in HTML, so you are sure the value you will receive is already a number you can do it like this:
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
IF this is an MVC project, you should restrict this in your ViewModel by setting your property to be an Integer (int), use annotations to enforce things like
[Required]
or
[Range(10, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
Depending on what your project is built in (Webpages or MVC) this can be done differently.

Django - Better way to set checked checkboxes on a search form based on GET parameters

I've done a good bit of searching, but it doesn't seem like this particular brand of form creation is addressed anywhere.
I'm creating a search page that queries the database for the set of all elements which have attributes at or above a given threshold. Right now I have a simple form that has 5 attributes, which have 5 thresholds each, each with their own checkbox i.e.
attrib_1 X threshold 1 X threshold 2 X threshold 3 X threshold 4 X threshold 5
attrib_2 X threshold 1 X threshold 2 X threshold 3 X threshold 4 X threshold 5
... etc ...
The HTML looks something like this:
<div class= "form-inline">
<label>Attribute 1</label>
<label class="checkbox inline">
<input type="checkbox" name="attrib 1" value="1"> Very Negative
</label>
<label class="checkbox inline">
<input type="checkbox" name="attribt 1" value="2"> Negative
</label>
<label class="checkbox inline">
<input type="checkbox" name="attrib 1" value="3"> Nonfactor
</label>
<label class="checkbox inline">
<input type="checkbox" name="attrib 1" value="4"> Positive
</label>
<label class="checkbox inline">
<input type="checkbox" name="attrib 1" value="5"> Very Positive
</label>
</div>
I then search the database using the information in the GET parameters. When I display the search results, what's an elegant way to make sure the checkboxes reflect the search query? I expect that the user will check some boxes, look at the results, then check some more to refine the search and I don't want them to have to recheck all the boxes each time they submit a search.
I've considered a few way to do this. I could use if/else statements for each checkbox and fill in the checked attribute appropriately. This would work, but seems inelegant, not very DRY, and would result in a very complex template. Alternatively, in the view I could create a data structure (dict of lists or list of tuples, probably dict of lists), which would have either 'checked' or the empty string for each checkbox. This would result in a cleaner template, but I suspect there's a more properly Django/Pythonic way to do this. I also considered a custom form, but that seemed like trying to fit a square peg in a round hole.
So, what's an elegant way to make sure that check boxes on a search form are properly checked based on GET parameters?
I am assuming you are POSTing back to the page with a refresh, instead of AJAX. In which case...
I will assume (as per Django standards) that you've made all these checkboxes a part of a Django form. In that case, you can pass the forms a series of arguments (I would suggest a dictionary) that contains the initial value for all of your checkboxes.
class SearchQuery(forms.form)
#Adding an init will allow us to pass arguments to this form In
# This case, a single dictionary argument named 'context'
def __init__(self, *args, **kwargs)
checkbox_context = kwargs.pop('context')
super(SearchQuery,self).__init__(*args, **kwargs)
#Now, instead of doing a bunch of if statements, we can say that
# our dictionary passed a series of True and False keys that will
# tell us how our checkboxes should be, in their initial state
self.fields['checkbox_one'].initial = context['box1']
checkbox_one = forms.BooleanField()
So, let's say we passed context = {'box1':True} , then our checkbox would be rendered with an initial value of 'True' or 'Checked'

Django and radio buttons

I am implementing a quiz app and I am displaying the multiple choice answers using radio buttons.
I need to group the answers per question, so I have it like this
{% for answer in quiz.quizanswer_set.all %}
<p><input type="radio" name="score[{{quiz.id}}]" value="{{answer.score}}"/>{{answer.answer}}</p>
{% endfor %}
When I hit submit, I have the POST object like this
<QueryDict: {u'score[1]': [u'10'], u'score[3]': [u'10'], u'score[2]': [u'10'], u'Get Result': [u'Submit']}>
How do I loop through the scores in a canonical way?
I have tried request.POST.getlist('score') and it returns empty list
PS. the quiz.id may not in sequence, it's from the database row id.
My current work around is:
for quiz in Quiz.objects.all():
total_score += int(request.POST.get('score[{0}]'.format(quiz.id)))
Just filter the POST keys:
for score_key in filter(lambda key:key.startswith('score'), request.POST.keys()):
total_score += int(request.POST[score_key])
Update
Thinking about it, a list comprehension would be better than filter:
for score_key in [key for key in request.POST.keys() if key.startswith('score[')]:
total_score += int(request.POST[score_key])
Update 2
Another way that I have been looking into, is keeping the name for each radio button the same (e.g. score) and then merging the quiz id with the value:
<input type="radio" name="score" value="{{quiz.id}}-{{answer.score}} />
You could then easily get a list of all scores and split the values:
for value in request.POST['score']:
quiz_id, score = value.split('-')
You are using a PHP-ism by naming the inputs score[{{quiz.id}}]. Don't do that. Just call them all score, and your browser will do the right thing by putting them all in the same POST value which you can then get via request.POST.getlist('score').

Ordered list form value in Django form

Is there a way to submit an unbounded list of values as part of a form and retrieve it in Django as an ordered list? I saw this question: Django equivalent of PHP's form value array/associative array which makes sense, however since the values are submitted with the same name as separate POST values I assume they are unordered.
Ideally, I'd like this on the front end:
<input type="hidden" name="list[0]" value="blah">
<input type="hidden" name="list[1]" value="blah2">
<input type="hidden" name="list[2]" value="blah3">
and be able to see which list item occurred in which position when the form was submitted.
I want it sorted in an order determined in the front-end HTML, not sorted by value. I know about getlist(), but that doesn't preserve order.
As far as I'm aware, the square bracket notation is a convention of PHP rather than HTML per se.
There seems to be a Django workaround using dot notation to generate expanded dictionaries (http://stackoverflow.com/questions/2527476/phps-form-bracket-trick-is-to-djangos). I haven't tried it, but it seems it could work
The other solution is to parse the form names yourself, extracting the number from the square brackets and generating your own ordered list
(DISCLAIMER: I'm a mere casual programmer, and am more than willing to acknowledge that im wrong - but hopefully the SO moderation system will moderate any silly comments into oblivion)

Does default_if_none have any use in Django templates?

From the Django docs,
Generally, if a variable doesn't
exist, the template system inserts the
value of the
TEMPLATE_STRING_IF_INVALID setting,
which is set to '' (the empty string)
by default.
Filters that are applied to an invalid
variable will only be applied if
TEMPLATE_STRING_IF_INVALID is set to
'' (the empty string). If
TEMPLATE_STRING_IF_INVALID is set to
any other value, variable filters will
be ignored.
This behavior is slightly different
for the if, for and regroup template
tags. If an invalid variable is
provided to one of these template
tags, the variable will be interpreted
as None. Filters are always applied to
invalid variables within these
template tags.
If an invalid variable always gets translated to '', for template tags and filters other than if, for and regroup, then what good does the template filter default_if_none do? Obsolete?
There is a difference between an invalid variable and one that exists but has a value of None.
Consider the following context:
{'apple':'green','banana':None}`
In your template {{ apple }} resolves to green, while {{ banana }} resolves to None, and {{ orange }} resolves to TEMPLATE_STRING_IF_INVALID.
Now consider {{ banana|default_if_none:'yellow' }} and you should see the use of the default_if_none tag.
Here's a case where I have used default_if_none a few times. I'm querying a secondary database in which I have no control and I'm displaying the data in the template. Most of the times the data looks fine but sometimes, the data value will show None. In that case, I will use the filter as:
{{ data_value|default_if_none:"N/A" }}
The general public and users of site doesn't usually understand what the None value means, by replacing it with a more friendly word, the filter default_if_none comes in handy.
I have a Django model with a method returning the the number of days a trade has been open (an integer). For the first 24 hours it returns 0. However, once the trade is closed, it returns None.
In this situation, the distinction between default and default_if_none is important... I need to use default_if_none... otherwise, for the first 24 hours a trade is open, it looks as if they were already closed (because zero is falsy).