How to add custom menu opton in Tinymce in Rails - ruby-on-rails

I am using tinymce-rails gem for Tinymce and I want to add custom menu option. Right now I am doing what is suggested in the readme of gem like:
<%= f.input :content , :label => false , :placeholder => 'Content', input_html: {class: "tinymce"} %>
<%= tinymce %>
I am using simple-form.
I want to add a drop-down in the editor with a bunch of options (I have an array of names) and when user clicks on an option then the selected name should be inserted in the view of editor. And those names will be dynamic.
I tried to pass many options to the initialiser tinymce but unable to get the result.

Rather than using the default initiator from the gem you could initiate tinymce manually and create the menu item at the same time:
http://www.tinymce.com/tryit/menuitem.php
Something like this:
<script type="text/javascript">
tinymce.init({
selector: '.my-class textarea',
toolbar: "styleselect | bold italic | mybutton",
setup: function(editor) {
<% #my_items.each_with_index do |name, index| %>
editor.addMenuItem('<%= name %>', {
text: '<%= name %>',
context: 'tools',
onclick: function() {
editor.insertContent('<%= name %>');
}
<%= index == (#my_items.count - 1) ? '});' : '}),' %>
< % end %>
});
</script>
We use a ternary operator to choose the correct closing tag based on the index of the names.
Theoretically you can also do this in the config/tinymce.yml file, but due to the dynamic nature it's not really plausible.
Something else you may want to look into is passing the menu to the activeEditor like:
tinyMCE.activeEditor.controlManager.get('my_menu')

Related

Why drop down list appears behind the box ? Using Simple Form + Select2

I am trying to implement a dropdown list in a simple_form but the collection of emails appears behind the main box. See image below:
I have already tried to play with z-index but failed. I have also tried to add some javascript code according to select2 documentation regarding common problems (https://select2.org/troubleshooting/common-problems ) and also failed.
Ruby slim code is:
.reveal id="doubt-material-#{material.id}" data-reveal=true
= simple_form_for [:student, trail, component, material, material_student, doubt], html: { id: "doubt" }, remote: true do |f|
= f.input :recipient, :collection => %w[contato#witseed.com suporte#witseed.com], label: "#{t 'students.materials.index.questions.form_send_email'}", include_blank: "#{t 'students.materials.index.questions.form_blank_line'}"
javascript:
$('#select2-doubt_recipient-container').select2({
dropdownParent: $('#doubt-material-#{material.id}')
});
Html is:
Does anyone have any idea of whats is going on ?
Thx.

Adding a tag if it doesn't exist in rails chosen rails

I have implemented the functionality of adding tags to a post in Rails using chosen-rails and acts-as-taggable gems. I want to further enhance the functionality by making user to create new tag if it doesn't exist.
form.html.slim
.form-group.text-center
= f.label :tag_ids, "Tags"
= f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true}
I need to add a new tag if it doesn't exist.
Ok with Selectize.js, Acts_as_Taggable, & SimpleForm:
Firstly, change your input from collection_select to a normal string input. Selectize.js will separate all of the values into tags anywhere there is a comma. This happens behind the scenes so as people add tags, it's actually inserting a long string into your database with whatever delimiter you supply. Then you need to add an id to that field so you can initialize selectize such as:
<%= f.input :nationalities, as: :string, placeholder: "Nationalities", input_html: { id: 'nationality-input'} %>
Then initialize selectize.js:
#The following line gets all tags ever posted for a user with the context 'nationalities' which we will use as options.
<%=nations = ActsAsTaggleOn::Tagging.includes(:tag).where(context: 'nationalities').uniq.pluck(:id, :name)
$(document).ready(function() {
$('#nationality-input).selectize({
delimiter: ',',
persist: true,
allowEmptyOption: false,
options: [
<% nations.each do |nat| %>
{text: '<%=nat[1] %>', value: '<%=nat[1]%>' },
<% end %>
searchField: 'text',
create: function(input) {
return {
value: input,
text: input
}
}
});
});
Make sure you have acts_as_taggable setup properly and that the corresponding model includes it. Then in your controller just save the whole string with commas and all and allow selectize to reformat it on views automagically.

Ruby on Rails and how to render partial using json and jquery

Ruby on Rails newbie whose confused and frustrated :) I've spent over a day on this and think I've probably just confused myself.
Basically, I'm trying to render a partial in a view. Here's what I have specifically:
A form with 2 basic fields: Category and SubCategory. SubCategory changes depending on what the user selected in Category. I'm using "JQuery" with the assets pipeline enabled. This part works:
contact_infos.js.coffee
jQuery(document).ready(->
$("select#contact_info_category_id").change(->
id_value_string = $(#).val()
if id_value_string == ""
# if the id is empty remove all the sub_selection options from being selectable and do not do any ajax
$("select#contact_info_subcategory_id option").remove()
row = "" + "" + ""
$(row).appendTo("select#contact_info_subcategory_id")
else
# Send the request and update sub category dropdown
tmp = '/subcategories/for_categoryid/' + id_value_string + '.json'
$.ajax(
type: 'GET',
dataType: 'json',
url: tmp,
timeout: 2000,
error: (XMLHttpRequest, errorTextStatus, error) -> alert "Failed to submit : " + errorTextStatus + " ;" + error,
success: (data) ->
# Clear all options from sub category select
$("select#contact_info_subcategory_id option").remove()
# put in a empty default line
row = "" + "" + ""
$(row).appendTo("select#contact_info_subcategory_id")
# Fill sub category select
$.each(data, (i, j) ->
row = "" + j.name + ""
$(row).appendTo("select#contact_info_subcategory_id")
)
)
)
)
It generates a json response correctly.
When the form loads, in addition to Category and SubCategory, I also have 2 text fields - previous_value and current_value; however, if
SubCategory == "Full"
then I hide previous_value and current_value and need to insert a partial with new fields.
I'm having no problem hiding previous_value and current_value fields with JQuery works and looks like this (this is inserted into the code above):
$("select#contact_info_subcategory_id").change(->
id_text_string = $("#contact_info_subcategory_id option:selected").text()
if id_text_string == "Full"
$('#contact_info_previous_value_id').hide()
$('#contact_info_current_value_id').hide()
else
$('#contact_info_previous_value_id').show()
$('#contact_info_current_value_id').show()
)
I created a div called "test" in my form where I want to insert the new fields if SubCategory is "Full" and of course, inserting this line into the contact_infos.js.coffee doesn't work:
$('#test').html('<%= escape_javascript render("contact_infos/_full_name_info") %>')
as all I get on the page is the string "<%= escape_javascript render("contact_infos/_full_name_info") %>"
I've tried the following but can't get any to work:
1. creating a new.json.erb file with the following code:
<% self.formats = ["html"] %>
test = {
"html":"<%= raw escape_javascript(render :partial => 'contact_infos/full_name_info',
:content_type => 'text/html')}
%>"
}
This json file never triggered. My controller has this line:
format.json { render json: #contact_info }
Is this the best way to do this? If yes, what can I try next?
2. I saw a posting yesterday (I can't find it now - was on another computer) about creating a javascript variable (I called it fullnamefield) in the application.html.erb layout file as well as adding the js variable to the new.html.erb view, which I did. I also added this line to the contacts_infos.js.coffee:
('#test').html(fullnamefield)
and it worked!! EXCEPT that then when I went to any other area of the site, I got an error.
3. As a workaround, I thought about trying to change the json that my jquery produces to a js and then trying to trigger the new.js.erb. I ran into trouble trying to convert the ajax call. I could create "json" and also "text" dataTypes but not script (not sure why).
So... any ideas/help? I've really been searching and I'm frustrated enough that I'm considering just creating all the fields and hidings/showing them as needed from JQuery, which would be so simple to implement but is just wrong.
UPDATE: Attempt 4 (or is it 40?):
What you wrote got me thinking... I think I'm close but not there yet.
In my _form.html.erb, I added to the Subcategory field data-remote, data-url and data-type:
<div class="field">
<%= f.label :category_id %>
<br/>
<%= collection_select(:contact_info, :category_id, Category.all, :id, :name, options ={:prompt => "--Select a Category--"}) %>
</div>
<div class="field">
<%= f.label :subcategory_id %>
<br/>
<%= collection_select(:contact_info, :subcategory_id, Subcategory.find_all_by_category_id(#contact_info.category_id), :id, :name, options ={:prompt => "--Select a SubCategory"}, "data-remote" => true, "data-url" => "/contact_infos/get_full_fields", "data-type" => :json ) %>
</div>
Then in the contact_infos_controller.rb I added:
def get_full_fields
#full_name = FullName.new
respond_to do |format|
format.js
end
end
In my routes.rb I modified contact_infos by adding collection do...
resources :contact_infos do
collection do
get 'get_full_fields'
end
end
I created contact_infos\get_full_fields.js.erb:
var full_fields_form = $('<%= j(render(:partial => "contact_infos/full_name_info"))%>');
$('#test').html(full_fields_form);
Now when I test this in the browser with debugger and change SubCategory to "Full" I can see that it runs correctly (I think) in that I'm getting this back:
Request URL:http://localhost:3000/contact_infos/get_full_fields?contact_info%5Bsubcategory_id%5D=3
Request Method:GET
Status Code:200 OK
The "Type" is showing up as "text/javascript." The Response tab is just showing the javascript code but nothing is happening/triggering. Even when I place just a
alert('hello');
in the js file nothing happens.
Any ideas why?
Why not do it the same way you get subcategory data? Create a view containing the partial (and corresponding controller action) and call it via ajax when you want to display that content.

rails selectbox_tag onchange()

Say we have a select box:
/app/views/tape/_form.html.erb
<%= f.select :tape, Tape::LIST_TAPES %>
and a .js.coffee file that i would like to trigger when some value is selected in selectbox:
/app/assets/javascripts/tapes.js.coffee
function selectBoxValue(value){
# value -- selected in selectbox;
console.log("box_value = ", value);
}
How can it be done in RoR 3.2?
Here's what i mean within html+js.
P.S.
I'm new to Rails. Sorry for my English and thank you.
Something like that:
<%= f.select :tape, Tape::LIST_TAPES, :id => 'some_id' %>
js file:
$(function(){
$('#some_id').change(function(){
selectBoxValue(this.value);
});
});
Pay attention that your select tag already has id so you can use it and remove :id => 'some_id'

Open Pop-Up window in Rails on clicking link

I want to open a pop-up window on click of 'link', then show some data there and close it.
I am using 'link_to' to create 'link'.
The part of code looks as:
<%= link_to 'Display Links', :controller=>'aaa', :action=> 'xyz_links', ....... %>
Previously, in rails2.3.x you could just do:
link_to "foo", foo_path(foo), :popup => true
But now in Rails3, this option has been deprecated
Another option is to use the Rails 3 unobtrusive way of event
delegating those links:
First add an attribute "data-popup" to your link_to if you want it to open
in a new window
Then if you are using the jquery adapter, add to application.js inside the document
ready handler:
$('a[data-popup]').live('click', function(e) {
window.open($(this).attr('href'));
e.preventDefault();
});
Or with the prototype adapter, use this code inside the document ready
handler:
document.on("click", "a[data-popup]", function(event, element) {
if (event.stopped) return;
window.open($(element).href);
event.stop();
});
You can find the same discussion here:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/e1f02d9e0977071b/814d69e4d56cea65?show_docid=814d69e4d56cea65&utm_medium=twitter&pli=1
I haven't tried this but have this in ruby docs:
<%= link_to name, url, :popup => ['dialog name','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes'] %>
pls check at
http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to#29-Window-open-a-dialog-of-no-menu-no-status-have-scroll

Resources