Get both name and value from option using Perl CGI param - html

In my HTML code I have
<option name="PRODUCTS" value="3">Products</option>
I need get both the name and value values in my server side Perl function through my Perl CGI param.
I can only get the value, is there a way to get the name also?

<option name="PRODUCTS" value="3">Products</option>
An <option> element does not have a name attribute, so this is invalid HTML and the browser will ignore it (except that it might make it available to JavaScript).
When the form is submitted, the browser will send to the server the name of the select coupled with the value of the selected option. This is the only information that the server will receive.
If you want to get 'PRODUCTS' then you will need to either:
Include it in the value: value="3-PRODUCTS" and then my ($number, $word) = split '-', $value
Look up the word that 3 is related to on the server (e.g. in a hash embedded in the script, or with a database query).

CGI::param() with no parameters returns all the names. Then CGI::param($name) will return all the values for a given name.
for my $name (CGI::param()) {
for my $val (CGI::param($name)) {
print "name: $name, value: $val\n";
}
}
Update: sorry, misread "option" as "input". option's name attribute isn't sent to the server at all, so there's no way to tell what it was without also having the html itself. You could add javascript to set a hidden input field to the option's name when it's chosen, though. What does populateCatArray do?

I would use the Vars method if there is some doubts on what is getting passed, especially if you have thee same 'name' used multiple times or a js its producing elements that don't exist on the page normally.
use CGI;
use Data::Dumper
my $q = new CGI;
print
$q->header({ type=>'text/plain' }),
Dumper($q->Vars);

Related

HTML url passing multiple parameters

I'm trying to pass multiple parameters with an url. I have checked out almost every topic about it, but can't seem to find an answer. I have tried different ways, but it still doesn't work.
It is only sending the first parameter.
If I start with post_id - I can't get comment_id
If I start with comment_id - I can' get post_id
My idea of url:
http://localhost/index.php?post_id=3&comment_id=6
OR
http://localhost/index.php?post_id=3&comment_id=6
I try to use it later like this:
else if(isset($_GET['post_id']) & isset($_GET['comment_id'])){
$post_id = $_GET['post_id'];
$comment_id = $_GET['comment_id'];
$user_id = $this->UserModel->getUser();
$BlogPost = $this->BlogModel->getBlogPost($post_id);
$BlogComments = $this->BlogModel->getBlogCommentList($post_id);
$BlogComments = $this->BlogModel->deleteBlogComment($comment_id,$user_id);
include 'views/ViewBlogPost.php';
}
Your below URL Structure is perfactly true
http://localhost/index.php?post_id=3&comment_id=6
Logic to Pass data Through URL in your script is called as QueryString Which you can build in below way
NAME=VALUE - this is called Name Value Pair , you can Pass Multiple Name Value pair by appending with '&' only
e.g.
http://localhost/index.php?name_1=value_1&name_2=value_2
on server side you will retrive them by using GLOBAL $_GET e.g print_r($_GET); to view all the passed data.
individually you can access them by using
echo $_GET['name_1']; echo $_GET['name_2'];
Also i suggest you to check your GPSC setting in your php.ini to define the priorities between your Super Globals.

In a PowerShell function, how can I make a parameter mandatory only if another optional parameter is absent?

I'm writing a PowerShell function and I need the first parameter to be optional, then the third parameter to be optional but only if the first parameter is present.
Here is the code as it is right now:
Param(
[Parameter(position=0)][array]$From,
[Parameter(position=1,Mandatory=$true)][string[]]$Names,
[Parameter(position=2)][string[]]$Values
)
Ideally I would do this:
[Parameter(position=2,Mandatory=(!$From))][string[]]$Values
But that is not allowed.
I've been getting the impression that using set names in some way is the way to go, but I'm not sure how I would go about it. The only thing I need to change is the Mandatory attribute value for $Values depending on the existence of $From.
What is the best way for me to do this?
I've looked over each of the following past questions pretty thoroughly and nothing I tried based on what I found in them would work.
Create a function with optional call variabls: Powershell
Requiring parameters in PowerShell when another parameter is present
PowerShell mandatory parameter depend on other parameter
Having a optional parameter that requires another paramter to be present
Multiple Mandatory Parameter Sets
Conditional powershell parameters
Try something like this:
[Parameter(position=0,ParameterSetName = "From")]
[array]$From,
[Parameter(position=1,Mandatory=$true,ParameterSetName = "Names")]
[string[]]$Names,
[Parameter(position=2,Mandatory=$true,ParameterSetName = "Names")]
[Parameter(position=2,Mandatory=$false,ParameterSetName = "From")]
[string]$Values
You define two sets, Names and From
Names has $Names and mandatory $Values
From has $From and optional $Values

ASP.NET : Add a number to local variable in view

I know the solution for this should be simple, but I can't figure it out.
When I add a number (for example 2) to page variable, it actually considers it as a string and shows: instead of 3 : 1+2
#{
var page= 1 ;
}
<li>#page+2</li>
Expression must be evaluated server side so it must be enclosed in parenthesis:
<li>#(page+2)</li>
If you don't then parser will evaluate server side only first token after #, page will be replaced with its value and you'll have <li>1+2</li> HTML text (where, of course, no more evaluation will be performed).

putting all checked items in checkboxes in an array

I need to take all the checked items in an html page and put them in an array to perform a certain action on it. I don't understand the fields of a checkbox(name, value,...). I am using html with ruby on rails!
If you need to do it on the client side using javascript you can use jQuery like this:
var arr = $('[type=checkbox]:checked');
If you need to do this on the server side in ruby on rails I cannot help you. However I do know that only checked checkboxes will get send back to the server on a GET or POST, so if you know what names these checkboxes you can get them from the request object and put them in a array. Non checked checkboxes will never get to the server, so you won't have to explicitly ignore them.
$_POST is already an array of everything within the form set. Use this to do your "certain action" on the checkboxes. If for whatever reason you need the information in a different variable, then just loop through the $_POST and put it into a different variable like so:
while ($row = $_POST) {
$new_var[] = $row[0];
}
That should work for you to put into a new/different array but frankly, I don't see the point of that since it's already an array.
As far as understanding the way the array of $_POST looks like, then var_dump() it and see. The name of the checkbox will be that in [] and the value will display after the =>. So if your input is named name=box1 and the value is value=1 then the array, from the $_POST standpoint, would look like [box1] => 1 so you can then use this section by calling it specifically like $foo = $_POST['box1'] and the value of $foo would be the value of box1 or you can do whatever else you want with that (rather than put into a new variable) by calling it.
If you do something like this:
<input type='checkbox' name='User[]' VALUE='someVal'>Visible Text</option>
Whatever checkbox is checked by the user then submitted will be in a POST array called User.
Adding the [ ] to the name creates an array when submitted.
Not sure hot to do this in ruby on rails but in php. When the form is submitted but the user an array is passed to the server. We names our checkboxes as User so our posted array is called User. In php i retrieve the posted array like this:
print_r($HTTP_POST_VARS["User"]);
then this outputs the array like so:
Array ( [0] => Me [1] => You [2] => SomeoneElse )
all of the data in the array were check checkboxes. the you can do a
foreach (​​​​​​​ $HTTP_POST_VARS["User"] as $key => $value) { $key is 0, $value is Me. and so on }
Hope this helps –

Why is the first element always blank in my Rails multi-select, using an embedded array?

I'm using Rails 3.2.0.rc2. I've got a Model, in which I have a static Array which I'm offering up through a form such that users may select a subset of Array and save their selection to the database, stored in a single column in Model. I've used serialize on the database column which stores the Array and Rails is correctly converting the users' selections into Yaml (and back to an array when reading that column). I'm using a multi-select form input to make selections.
My problem is that, the way I currently have it, everything works as I would expect except that the user's subset array always has a blank first element when it's sent to the server.
This isn't a big deal, and I could write code to cut that out after the fact, but I feel like I'm just making some kind of syntactical error as it doesn't seem to me that the default Rails behaviour would intentionally add this blank element without some reason. I must have missed something or forgot to disable some kind of setting. Please help me understand what I'm missing (or point me in to some good documentation that describes this with more depth than what I've been able to find on the intertubes).
MySQL Database Table 'models':
includes a column named subset_array which is a TEXT field
Class Model includes the following settings:
serialize :subset_array
ALL_POSSIBLE_VALUES = [value1, value2, value3, ...]
Form for editing Models includes the following input option:
f.select :subset_array, Model::ALL_POSSIBLE_VALUES, {}, :multiple => true, :selected => #model.subset_array
PUT to server from client looks something like this:
assuming only value1 and value3 are selected
"model" => { "subset_array" => ["", value1, value3] }
Database update looks like this:
UPDATE 'models' SET 'subset_array' = '--- \n- \"\"\n- value1\n- value3\n'
As you can see, there's this extra, blank, element in the array being sent and set in the database. How do I get rid of that? Is there a parameter I'm missing from my f.select call?
Much thanks appreciated :)
EDIT: This is the generated HTML code from the f.select statement. It looks as though there is a hidden input being generated which may be the cause of my issue? Why is that there?
<input name="model[subset_array][]" type="hidden" value>
<select id="model_subset_array" multiple="multiple" name="model[subset_array][]" selected="selected">
<option value="value1" selected="selected">Value1</option>
<option value="value2">Value2</option>
<option value="value3" selected="selected">Value3</option>
<option...>...</option>
</select>
In Rails 4:
You will be able to pass :include_hidden option. https://github.com/rails/rails/pull/5414/files
As a quick fix for now: you can use right now in your model:
before_validation do |model|
model.subset_array.reject!(&:blank?) if model.subset_array
end
This will just delete all blank values at model level.
The hidden field is what is causing the issue. But it is there for a good reason: when all values are deselected, you still receive a subset_array parameter. From the Rails docs (you may have to scroll to the right to see all of this):
# The HTML specification says when +multiple+ parameter passed to select and all options got deselected
# web browsers do not send any value to server. Unfortunately this introduces a gotcha:
# if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
# the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
# any mass-assignment idiom like
#
# #user.update_attributes(params[:user])
#
# wouldn't update roles.
#
# To prevent this the helper generates an auxiliary hidden field before
# every multiple select. The hidden field has the same name as multiple select and blank value.
#
# This way, the client either sends only the hidden field (representing
# the deselected multiple select box), or both fields. Since the HTML specification
# says key/value pairs have to be sent in the same order they appear in the
# form, and parameters extraction gets the last occurrence of any repeated
# key in the query string, that works for ordinary forms.
EDIT: The last paragraph suggests that you shouldn't be seeing the empty one in the case when something is selected, but I think it is wrong. The person who made this commit to Rails (see https://github.com/rails/rails/commit/faba406fa15251cdc9588364d23c687a14ed6885) is trying to do the same trick that Rails uses for checkboxes (as mentioned here: https://github.com/rails/rails/pull/1552), but I don't think it can work for a multiple select box because the parameters sent over form an array in this case and so no value is ignored.
So my feeling is that this is a bug.
In Rails 4+ set :include_hidden on select_tag to false
<%= form.grouped_collection_select :employee_id, Company.all, :employees, :name, :id, :name, { include_hidden: false }, { size: 6, multiple: true } %>
Another quick fix is to use this controller filter:
def clean_select_multiple_params hash = params
hash.each do |k, v|
case v
when Array then v.reject!(&:blank?)
when Hash then clean_select_multiple_params(v)
end
end
end
This way can be reused across controllers without touching the model layer.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
Gotcha
The HTML specification says unchecked check boxes or selects are not successful,
and thus web browsers do not send them. Unfortunately this introduces
a gotcha: if an Invoice model has a paid flag, and in the form that
edits a paid invoice the user unchecks its check box, no paid
parameter is sent. So, any mass-assignment idiom like
#invoice.update(params[:invoice]) wouldn't update the flag.
To prevent this the helper generates an auxiliary hidden field before
the very check box. The hidden field has the same name and its
attributes mimic an unchecked check box.
This way, the client either sends only the hidden field (representing
the check box is unchecked), or both fields. Since the HTML
specification says key/value pairs have to be sent in the same order
they appear in the form, and parameters extraction gets the last
occurrence of any repeated key in the query string, that works for
ordinary forms.
To remove blank values:
def myfield=(value)
value.reject!(&:blank?)
write_attribute(:myfield, value)
end
In the controller:
arr = arr.delete_if { |x| x.empty? }
I fixed it using the params[:review][:staff_ids].delete("") in the controller before the update.
In my view:
= form_for #review do |f|
= f.collection_select :staff_ids, #business.staff, :id, :full_name, {}, {multiple:true}
= f.submit 'Submit Review'
In my controller:
class ReviewsController < ApplicationController
def create
....
params[:review][:staff_ids].delete("")
#review.update_attribute(:staff_ids, params[:review][:staff_ids].join(","))
....
end
end
I make it work by writing this in the Javascript part of the page:
$("#model_subset_array").val( <%= #model.subset_array %> );
Mine looks more like following:
$("#modela_modelb_ids").val( <%= #modela.modelb_ids %> );
Not sure if this is going to get me headache in the future but now it works fine.
Use jQuery:
$('select option:empty').remove();
Option to remove blank options from drop down.