Rails: How to add custom data-attributes in collection_select - html

I am working on a solution to add custom data-attributes to option-tags with the collection_select form helper in Rails.
I studied some posts at stackoverflow and did a lot of trial and error after consulting some API documentation. I am nearly there but sadly my solution only adds attributes to the select-tag not to the option-tags.
This way I am populating the html-options-hash (6th position):
<%= f.collection_select(:parallax_id, #parallax.all, :id, :title, {}, { :"data-icon" => #parallax.map{ |p| "#{p.image}"}} ) %>
This results in a select tag like:
<select data-icon="/uploads/image/image/4/169_strecken-ausgang.jpg" name="game[parallax_id]" id="game_parallax_id">...</select>
But I want the option to get the data-icon attribute. When I switch positions and add my data-icon to the options-hash (5th position) nothing is output.

Is this what you want?
= f.select :parallax_id, options_for_select(#parallax.map {|p| [p.title, p.id, {'data-icon' => p.image }]})

Just FYI I was looking at this matter, found the more fitting solution here: How do I set the HTML options for collection_select in Rails?.

Related

How to set a color for an option in a rails select form helper?

I search on the web, and it seems we can do it by apply a style: "background-color:colorName;" on the desired option.
But after many researches and tries, I cannot find how to do this with the rails form helpers.
This is what I have now :
<% users_array = ["Choose your player"] %>
<% users_array += User.all.map { |user| [user.name, user.id ]} %>
<%= select("player-#{user.id}-#{category[0]}", nil, options_for_select(users_array, user.name.to_s ), { }, { class: "selectstyle col-md-2" }) %>
I display all my model content with a default selected option specified in the options_for_select, but I want to add a different color to each users of my model displayed in this select.
The only example I found on the web are for a select without model displaying, and all my tries failed. How can I do ?
Check here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select
You can optionally provide HTML attributes as the last element of the array.
You can do something like:
users_array += User.all.map do |user|
html_attributes = {}
html_attributes['style'] = '...' if <some_condition>
[user.name, user.id, html_attributes]
end

Rails 4: Change 'name' attribute of Simple Form input

I am using Simple Form in a Rails 4 app for a #user object and have the line...
= f.input :entity_name
This generates the HTML name='user[entity_name]' inside the input tag. I would like to change it because of some custom processing I am doing in the controller but haven't found a way to do so.
I've tried changing the line to...
= f.input :entity_name, name: 'entity[name]'
...but this doesn't seem to affect the generated HTML at all. So far I haven't found anyone else with this question on Google/Stack Overflow.
Does anyone know if/how it's possible to change the name attribute through the Simple Form helper?
Thanks in advance!
The trick is using the input_html option.
= f.input :entity_name, input_html: { name: 'entity[name]' }
If you're looking to just change the shown label of the field:
= f.input :entity_name, label: 'new_input_field_name'

how to populate csv into textarea value

I'd like to populate the value of a textarea input with a csv string. Here's my csv string (it's in a rails view at this variable #item[:template]):
x,y,series,size
2,-0.083014839,Group 0,0.883928284
-9,0.355697349,Group 0,0.149154477
5,-0.256459661,Group 0,0.066308001
3,-0.243723214,Group 0,0.388138931
7,-0.663022927,Group 0,0.09761712
0,-0.587616252,Group 0,0.246573359
Here's my textarea tag in rails:
<%= text_area_tag 'template', nil, class: 'form-control temp-grab',
value: #item[:template] %>
The textarea isn't actually populating though. I don't know if it's because it's a multiline string or because the characters aren't escaped. I've tried simple_format(#item[:template]) but it isn't working. Any ideas?
Per the documentation, any parameter other than size, rows, cols, disabled, and escape becomes HTML attributes. HTML textareas do not have a value attribute. You instead want to do this:
<%= text_area_tag 'template', #item[:template], class: 'form-control temp-grab' %>

HAML : Img tag inside anchor tag

Here is guy that made a lot of effort:
.picture{:"ng-repeat" => "picture in pictures"}
%h2 {{picture.title}}
%a{ :ng-href => "pictures/{{$index}}"}
%img{:src => "{{picture.url}}"
tried to
%a{ :ng-href => "pictures/{{$index}}"}
%img{:src => "{{picture.url}}"
and %a{ :ng-href => "pictures/{{$index}}"}<
%img{:src => "{{picture.url}}">
but nothing works. can't find in haml documentation (these are so bad docs....) answer for my question. Does anyone know how to put inside in haml?
I had the same trouble properly placing my image inside the anchor, and got the following solution for rails:
Inside your view.html.haml, with embedded rails helpers:
= link_to image_tag('name_of_the_asset', alt: 'title'), root_path
(root_path is using the url_for helper but chan be changed for "https://www.someexample.com")

Radio Button generates duplicate HTML id-s

It seems that the default ASP.NET MVC2 Html helper generates duplicate HTML IDs when using code like this (EditorTemplates/UserType.ascx):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UserType>" %>
<%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary) %>
<%: Html.RadioButton("", UserType.Standard, Model == UserType.Standard) %>
<%: Html.RadioButton("", UserType.ReadOnly, Model == UserType.ReadOnly) %>
The HTML it produces is:
<input checked="checked" id="UserType" name="UserType" type="radio" value="Primary" />
<input id="UserType" name="UserType" type="radio" value="Standard" />
<input id="UserType" name="UserType" type="radio" value="ReadOnly" />
That clearly shows a problem. So I must be misusing the Helper or something.
I can manually specify the id as html attribute but then I cannot guarantee it will be unique.
So the question is how to make sure that the IDs generated by RadioButton helper are unique for each value and still preserve the conventions for generating those IDs (so nested models are respected? (Preferably not generating IDs manually.)
In addition to PanJanek's answer:
If you don't really need the elements to have an id, you can also specify id="" in the htmlAttributes (i.e. new { id="" }) parameter of helpers. This will result in the id attribute being left out completely in the generated html.
source: https://stackoverflow.com/a/2398670/210336
I faced the same problem. Specyfying IDs manually seems to be the only solution. If you don't need the ids for anything (like javascript), but want it only to be unique you could generate Guids for them:
<%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary, new { id="radio" + Guid.NewGuid().ToString()}) %>
A more elegant solution would be to create your own extension method on HtmlHelper to separate ID creation logic from the view. Something like:
public static class HtmlHelperExtensions
{
public static MvcHtmlString MyRadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool value)
{
string myId = // generate id...
return htmlHelper.RadioButtonFor(expression, value, new {id=myId});
}
}
The helper method could use ViewContext and Model data to create more meaningfull IDs.
UPDATE:
If you use EditorTemplates to render the control like this
<%= Html.EditorFor(m=>m.User, "MyUserControl") %>
Then inside the MyUserControl.ascx (placed in ~/Views/Shared/EditorTemplates) you can use ViewData.TemplateInfo.HtmlFieldPrefix property to access the parent control ID or Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("MyPostfixPart") to generate prefixed id. Theese methods could be used in the helper extension above.
The same works with controls rendered with Html.Editor(...) and Html.EditorForModel(...). In the Html.Editor helper you can also specify htmlFiledName manually if you want.
When you embed the control with
<%= Html.Partial("UserControl", Model.User) %>
generation of meaningfull IDs is harder because the Html.Partial will not provide information about the prefix - the ViewData.TemplateInfo.HtmlFieldPrefix will be always empty. Then, the only solution would be to pass the prefix manually to the ascx control in as ViewData key of as a model field which is not as elegant a solution as the previous one.
If you do need to access the radio buttons via jQuery, I find that often the better place to set the id's will be on the page, close to their intended usage. This is how I did the same:
#Html.Label(Resource.Question)
#Html.RadioButtonFor(m => m.Question, true, new {id = "QuestionYes"}) Yes
#Html.RadioButtonFor(m => m.Question, false, new {id = "QuestionNo"}) No
Then my jQuery:
if ($("input[id='QuestionNo']").is(":checked")) {
$('#YesOptionalBlock').removeClass('showDiv');
$('#YesOptionalBlock').addClass('hideDiv');
}