How to update by passing array values from HTML to Rails controller - html

I am trying to update a record from an html.haml form.
HTML.HAML:
%input{:name => "post[my_card_ids][]", :type => "hidden",value: "#{post["my_card_ids"]}",id: "my_card_ids"}
When I inspect the HTML page, the values are exactly like they should be.
HTML inspection:
<input id="my_card_ids" name="post[my_card_ids][]" type="hidden" value="[5d1b83a6616b6523a9020000, 5d1b9893616b653abd0b0000]">
But when I receive the same params in the controller, they become like this:
Rails Console:
<ActionController::Parameters {"my_card_ids"=>["[\"5d1b83a6616b6523a9020000\", \"5d1b9893616b653abd0b0000\"]"]
The record is being saved with all the extra paranthesis and quotation marks, because it is being passed as a string I'm guessing.
How do I pass the array cleanly, as shown in the HTML inspection and update the record?

In order to create an array in the parameters you want to create a hidden input for each value in the array:
- post["my_card_ids"].each do |card_id|
%input{ name: "post[my_card_ids][]", type: "hidden", value: card_id, id: "my_card_ids_#{card_id}" }
This works since Rack merges parameters with names ending with [] into an array. Its also how the built in FormOptionsHelper works.

You put array as string to hidden field.
Try:
%input{:name => "post[my_card_ids]", :type => "hidden",value: "#{post["my_card_ids"].join(','}",id: "my_card_ids"}
And in the controller
params[:my_card_ids].split(',')

Related

How to add the variables of array to database table

I have a form. Posting array variables from this form in the same name. (Sorry for my bad English.)
Here is the example:
<input type="text" name="name[]" class="form-control">
It is coming like ["a", "b", "c"]
I need save this variables to mysql from array. Not with array. Just one by one.
Create from my post controller
array_length = params[:type].size
for i in 0..array_lenth
type = params[:type][i]
name = params[:name][i]
title = params[:title][i]
value = params[:value][i]
#And save code.
end
I know i can save with some normal sql query but i dont know should i use or how i can use params require permit . something like
def form_params
params.require(:form).permit(:id, :type, :name, :value, :title, :post_id)
end
If i use this, how can i determine the necessary variables. Please help me and sorry for my English :)
Note: I have new post form and i have to add some variables to another table in post form (it is those arrays)
You have to specify that the param is an actual array, something like:
def form_params
params.require(:form).permit(:id, :type, :value, :title, :post_id, name: [:name_of_attribute, :another_name_for_attribute])
end
And then for your form:
<div class="field">
<%= form.text_field "name[name_for_attribute]" %>
</div>
Where the name_for_attribute is the name of the attribute you want it to be, so on the controller you will read the params like:
"form" => {"name"=>{"name_for_attribute"=>"The entered value"}
You can change the name_for_attribute for whatever you want and if for some reason someone tries to add another weird thing into the array by inspecting the HTML, you will filter all the attributes you want anyway.
Hope this helps! Let me know how it goes

Symfony 2 / Doctrine Not Saving Any Zeros in varchar field

UPDATE
As asked for,
$NewUser = new Users();
$Form = $this->createForm(new UserType(), $NewUser, [])
->add('save', 'submit', ['label' => 'Save',
'attr' => ['class' => 'SaveButton ftLeft'],
]);
$Form->handleRequest($request);
if ($Form->isValid()) {
/*
Sometimes add more data to the entity.....
*/
$em = $this->getDoctrine()->getManager();
$em->persist( $NewUser );
$em->flush();
}
$FormRender = $Form->createView();
return $this->render('xxxxBundle:Users/add.html.twig',
['AddUser' => $FormRender]);
Sometimes I will add extra to the entity, on fields being set within the php code, e.g. account sign up date, but in most cases just save the entity with the form data.
Very simple issue, I have a new (ish) system and have notice that when trying to save zeros, for anything, phone number inputs, it does not save any zeros?
I am using YMAL files to control my doctrine ORM, here is how I have set it up within my User table,
mobileNumber:
type: string
nullable: false
length: 50
options:
fixed: false
column: mobile_number
This does save/make the field has a varchar, and thought nothing about it until I did a random test and saw it was not saving any leading zeros?
I know you can not save leading zeros in a int field type, but this is a varchar. Also when I go into the database, and manually add a zero to that input, its fine, so I take its not the database. Something to do with how I get doctrine to save the data?
If so how do I change that? I have just been saving the data with a standard persist() and flush() commands? Not sure why it would not save the zeros? I was thinking that I had to change the YMAL type to something like phone? I have been over the docs, can not see it.
All help most welcome..
Thanks.
The reason is in your comment:
User form type has the mobile number set to 'number' input.
This value is being casted to int by the Form component. Change the field type to regular string.
If you want to validate value to be only digits, use Validation component

page element definition for cloned rows

I am using the page-object-gem and trying find the best way to define my page elements when a set of text_field have an infinite number of occurrences.
The HTML on page load is similar to the following:
<div><input id="dx_1_code" value=""/> <input id="dx_1_dos" onblur="clone($(this),false)" value=""/></div>
If the user tabs out of the last input then a new row is cloned with id values that increment with HTML like follows:
<div><input id="dx_2_code" value=""/> <input id="dx_2_dos" onblur="clone($(this),false)" value=""/></div>
<div><input id="dx_3_code" value=""/> <input id="dx_3_dos" onblur="clone($(this),false)" value=""/></div>
My first try was to define my class as follows:
class SamplePage
include PageObject
include DataMagic
text_field(:dx_1, :id => "dx_1_code")
text_field(:dx_2, :id => "dx_2_code")
text_field(:dos_1, :id => "dx_1_dos")
text_field(:dos_2, :id => "dx_2_dos")
end
However I quickly ended up with a lot of redundant entries.
Is there a better way to handle an unknown number or entries like this in terms of element setups and use of the populate_page_with method?
The elements are indexed, which makes them a good candidate for the indexed properties feature. The indexed_property lets you define locators where a number is substituted in when accessing the element. The page object would look like:
class MyPage
include PageObject
indexed_property(:dx, [
[:text_field, :code, {id: 'dx_%s_code'}],
[:text_field, :dos, {id: 'dx_%s_dos'}],
])
end
The first two rows would then be inputted using:
page = MyPage.new(browser)
page.dx[1].code = 'a'
page.dx[1].dos = 'b'
page.dx[2].code = 'c'
page.dx[2].dos = 'd'
Unfortunately there is no built-in way for the populate_page_with method to work with indexed properties. As with anything, you could hack in something. The populate_page_with method looks for an "element" method as well as a setter method. By adding your own to the page object, the method could be used.
class MyPage
include PageObject
indexed_property(:dx, [
[:text_field, :code, {id: 'dx_%s_code'}],
[:text_field, :dos, {id: 'dx_%s_dos'}],
])
# Method for inputting the various dx code/dos values based on a Hash
def dx=(values)
values.each_pair do |index, fields|
fields.each_pair do |field, value|
dx[index].send("#{field}=", value)
end
end
end
# This is so that populate_page_with can check that the element is enabled/visible
def dx_element
dx[1].code_element
end
end
This would give you the ability to use populate_page_with by sending a Hash where the keys are the index and the values are the fields/values for that index. The same inputting of the page that we did before can now be written as:
page = MyPage.new(browser)
page.populate_page_with(dx: {
1 => {code: 'a', dos: 'b'},
2 => {code: 'c', dos: 'd'}
})

How to remove decimal values display from form field that is automatically coming from backend

In my form field i want to enter only integer values. i am using ruby moneyrails gem. my field name in db is amount_paisas. so when it is displayng in form it shows 0.00 . i need only 0 to dispaly there. how to avoid decimal values . i tried to give placeholder but no changes.
This is what iam getting in form display.here i need to avoid values after point
This value is automatically coming from backend. how to remove this?
my input field
= f.input :amount, label: 'Amount'+'('+#cart.currency+')', :input_html=>{:'data-validation' => 'required', :'data-validation-error-msg' => 'Please Select Amount'}
here iam not giving any value. but it is automatically getting 0.00 as its placeholder value from backend. this i need to avoid.
when i inspectin this form field i am getting like this
<input data-validation="required" data-validation-error-msg="Please Select Amount" class="string optional form-control valid" type="text" value="0.00" name="e_gift_card[amount]" id="e_gift_card_amount">
Any help is appreciatable ..
You have 2 options here:
Configure default formatting
Create config/initializers/money.rb file with the following content:
MoneyRails.configure do |config|
config.default_format = {
:no_cents_if_whole => true,
# :symbol => nil,
# :sign_before_symbol => nil
}
end
This configuration won't output cents if you have whole amount, i.e. $5 instead of $5.00.
Use custom helpers
If you don't want your cents at all, just use custom helpers:
money_without_cents(#money_object) # => 6
money_without_cents_and_with_symbol(#money_object) # => $6
To use it in your ruby code:
= f.input :amount, label: 'Amount'+'('+#cart.currency+')', :input_html=>{ :value => money_without_cents(#cart.amount), :'data-validation' => 'required', :'data-validation-error-msg' => 'Please Select Amount'}

Cakephp 3.0 I would like to include a Year input field with a drop down, but it is inputing as an array

I have a Year field in a form and I am using FormHelper.
echo $this->Form->input('year', [
'type' => 'year',
'minYear' => date('Y')-10,
'maxYear' => date('Y')
]);
The table file validator looks like:
->add('year', 'valid', ['rule' => 'numeric'])
->allowEmpty('year')
I have a very similar input in another app that seems to work fine. I set the MySql column to int(5) to match what I had working elsewhere.
Checking debugkit it shows the "year" input as an array while the other inputs are strings. If I remove the validation rule it throws an illegal array to string conversion, so I assume this is where the error is.
Any help is greatly appreciated.
I have just tested with your above code and it is working fine for me. Try to delete the cache and check it once more.
Creates a select element populated with the years from minYear to maxYear. Additionally, HTML attributes may be supplied in $options. If $options['empty'] is false, the select will not include an empty option:
empty - If true, the empty select option is shown. If a string, that
string is displayed as the empty element.
orderYear - Ordering of
year values in select options. Possible values ‘asc’, ‘desc’. Default
‘desc’ value The selected value of the input.
maxYear The max year to
appear in the select element.
minYear The min year to appear in the
select element.
Try this one:
<?php
echo $this->Form->year('exp_date', [
'minYear' => date('Y')-10,
'maxYear' => date('Y'),
'id' => 'cc-year',
'class' => 'form-control',
'empty' => false,
'orderYear' => 'asc'
]);
?>
Official Documentation: CookBook - Creating Year Inputs