Rails help to preview text area - javascript

I am trying to create a preview for my text area:
I have tried this:
My controller:
def preview
post = Post.new(params[:post])
render :text => post.body_html
end
def new
#post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #post }
end
end
And my form:
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :titel %><br />
<%= f.text_field :titel %>
</div>
<div class="field">
<%= f.label :body_html %><br />
<%= f.text_area :body_html %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
How should I make a preview in my form of the body_html text area?
I want to have a preview when a type something in the body_html text_area it gets previewed instant.

Is the user entering HTML that you want rendered in the preview? Or just the text as is?
I guess either way, add a div for the preview:
<div id='preview'></div>
and then using jQuery:
var $html = $('#body_html');
$html.bind('change keyup',function(){
$('#preview').html($html.val());
});

Related

Implementing AJAX Creation, Missing Template (Create) Error

I am trying to implement AJAX in my to do type app, but am getting a missing template error (Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}.) on my create action. There shouldn't be a create.html.erb page because the creation of items happens on a lists#show page:
<div class='new-item'>
<%= render 'items/form' %>
</div>
<div class="js-items">
<% #items.each do |item| %>
<%= div_for(item) do %>
<p><%= link_to "", list_item_path(#list, item), method: :delete, remote: true, class: 'glyphicon glyphicon-ok', style: "margin-right: 10px" %>
<%= item.name %>
<% if item.delegated_to != "" && item.user_id == current_user.id %>
<small>(Delegated to <%= item.delegated_to %>)</small>
<% elsif item.delegated_to != "" && item.user_id != current_user.id %>
<small>(Delegated by <%= item.user_id %>)</small>
<% end %></p>
<% end %>
<% end %>
</div>
And the _form.html.erb partial to which it links:
<div class="row">
<div class="col-xs-12">
<%= form_for [#list, #item], remote: true do |f| %>
<div class="form-group col-sm-6">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter Item Name" %>
</div>
<div class="form-group col-sm-6">
<%= f.label 'Delegate To (Not Required)' %>
<%= f.text_field :delegated_to, class: 'form-control', placeholder: "Enter an Email Address" %>
</div>
<div class="text-center"><%= f.submit "Add Item to List", class: 'btn btn-primary' %></div>
<% end %>
</div>
</div>
Here's the create method in the items_controller:
def create
#list = List.friendly.find(params[:list_id])
#item = #list.items.new(item_params)
#item.user = current_user
#new_item = Item.new
if #item.save
flash[:notice] = "Item saved successfully."
else
flash[:alert] = "Item failed to save."
end
respond_to do |format| <<<<ERROR CALLED ON THIS LINE
format.html
format.js
end
end
And here's my create.js.erb file:
<% if #item.valid? %>
$('.js-items').prepend("<%= escape_javascript(render(#item)) %>");
$('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: { list: #list, item: #new_item }) %>");
<% else %>
$('.flash').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>×</button><%= flash.now[:alert] %></div>");
$('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: { list: #list, item: #item }) %>");
<% end %>
Anyone have any ideas why I am getting this? I tried removing the format.html line from the items_controller but I got an unrecognizable format error.
You can force the form submission to use a JS format, instead of the default HTML format, so that your respond_to block will render the create.js.erb view instead of the create.html.erb view.
<%= form_for([#list, #item], format: :js, remote: true) do |f| %>
Typically, Rails will detect your remote: true option via "unobtrusive JavaScript (ujs)", which will effectively handle the format: :js option for you. There is something unique in your setup that we have not identified, which is requiring you to enforce the format option.
To see that your create.js.erb is working, you can change the line that renders your item partial:
$('.js-items').prepend("<%= escape_javascript(render(#item)) %>");
To render a the item's name, wrapped in a <p> tag:
$('.js-items').prepend("<p>" + <%= #item.name %> + "</p>");
You can customize that line to generate the html that you want to appear for your new list item. Based on your code above, this looks like it will work out for you.
As you finish your to-do app, you can create a partial for your item, and then change that line again so that your partial will be appended to your list of items.

Rails 4 render js: redirecting to another page and displaying raw js

In my TestimoniesController I have written a render js: line in the event that #testimony.save is not successful.
if #testimony.save
redirect_to #testimony
else
render js: "alert('Please make sure you feel out every field of the Testimonial!');"
end
Instead of rendering the alert that I write, it redirects me to the /testimonies route and just displays the string that was supposed to be rendered as javascript and nothing else. Is my JS disabled somehow?
Here is my new.html.erb file:
<h1> New Testimonial</h1>
<%= form_for :testimony, url:testimonies_path do |f| %>
<p>
<%= f.label :first_name %><br>
<%= f.text_field :first_name %>
</p>
<p>
<%= f.label :last_name %><br>
<%= f.text_field :last_name %>
</p>
<p>
<%= f.label :email %><br>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :contact_number %><br>
<%= f.text_field :contact_number %>
</p>
<p>
<%= f.label :country %><br>
<%= f.text_field :country %>
</p>
<p>
<!--bunch of the same stuff -->
<p>
<%= f.submit %>
</p>
<% end %>
In order tor respond with js, you have to add remote: :true in your form_for, and submit your request as ajax
<%= form_for :testimony, url:testimonies_path, remote: :true do |f| %>
but then your
redirect_to #testimony
will not work as it only works on html format, so in that scenario replace this line with
render js "location.href = '#{testimony_path}'";

Rails:In-place editing in edit form with submit button

I want to create my edit form such that it will display the current user information simply as text not in text filed and when user click on the text it will turn into text field and user can edit his information . Changes will be reflect in data base only when user click on submit button.
Simply it is not completely in place editing and not completely like default edit form it is mixture of the behaviour of both the features.
My form looks like following .it is not complete form these are some of the fields of form.
<%= form_for #contact, :html => { :multipart => true, :class => "contact_form"} do |f| %>
<% if #contact.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#contact.errors.count, "error") %> prohibited this contact from being saved:</h2>
<ul>
<% #contact.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :f_name, "First Name" %><br/>
<%= f.text_field :f_name %>
</div>
<div class ="field">
<%= f.label :experience, "Total years of experience "%><br/>
<%= f.select :experience, (0...30),{},{:class => 'select'} %>
</div>
<div class="field">
<%= f.label :l_name, "Last Name" %><br/>
<%= f.text_field :l_name %>
</div>
<div class = "field">
<%= f.label :primary_practice_area, "Primary practice area" %><br/>
<%= f.select :primary_practice_area , MetaPracticeArea.all.collect {|p| [ p.practice_area, p.id ] } %>
</div>
<div class = "field">
<%= f.label :phone, "Phone" %><br/>
<%= f.text_field :phone %>
</div>
<div class="actions">
<%= f.submit :class => "submit_btn" %>
</div>
<% end %>
and controller and model is default.
You can try the REST_in_place gem: https://github.com/janv/rest_in_place
Check below link for in_place_editing :
http://railscasts.com/episodes/302-in-place-editing?view=asciicast

In my comment app when i refresh the page comments disappears

My comment app works ,but the only problem is whenever i refresh the page the comments disappear.In the log it shows the body is inserted in the comments table(it is saved).What am i doing wrong here?Any help will be appreciated.Thank you in advance.
View#show
<div id="comments"></div>
<%= form_for :comment,:remote => true,:url=> {:controller=>"comments",:action=>"create"},:html => { :id => 'new-comment'} do |f| %>
<%= f.text_area(:body) %>
<div class="errors"></div>
<%= f.submit "post" %>
<% end %>
Comment controller
class CommentsController < ApplicationController
respond_to :js
def create
#deal=Deal.find(1)
#comment =#deal.comments.build(params[:comment])
#comment.save
respond_with( #comment, :layout => !request.xhr? )
end
def show
#comment=Comment.all
#deal=Deal.find(1)
#comment=#deal.comments
end
end
create.js.erb
$('#comments').append("escape_javascript(#comment.body)");
I don't see where your comments are being display in your show template.
How about something like this?
<div id="comments">
<% #comments do |comment| %>
<%= comment.body %>
<% end %>
</div>
<%= form_for :comment,:remote => true,:url=> {:controller=>"comments",:action=>"create"},:html => { :id => 'new-comment'} do |f| %>
<%= f.text_area(:body) %>
<div class="errors"></div>
<%= f.submit "post" %>
<% end %>
Note, you need to set #comments in the controller or use another method of getting comments, e.g. #view = View.find(params[:id]) and <%= #view.comments.each do |comment| %>...
I guess the comment has a belongs_to relationship with the post that is not assigned.
In your form you should add
<%= f.hidden_field :post_id, #post.id %>
If you want to play by the book, post_id should be attr_protected and instead assign it manually in the comments controller
#comment = Comment.new(params[:comment])
#comment.post_id = params[:comment][:post_id]
#comment.save

Dynamically add & remove new but the same fields of a form any amount times

I have a form that has no nested models.
class UserProductsController
def new
#user_product = current_user.user_products.build
end
end
With jquery/javascript i want to add and remove new #user_product fields on the same form. This how it would look normally:
<%= form_for(#user_product) do |f| %>
<%= f.error_messages %>
<%= f.text_field :product %>
<%= f.text_field :address %>
<%= f.text_field :price %>
<%= f.submit %>
<% end %>
And I'm trying to achieve:
<%= form_for(#user_product) do |f| %>
<%= f.error_messages %>
<%= f.text_field :product_name %>
<%= f.text_field :address %>
<%= f.text_field :price %>
---New ID(New generated ID, could be any new number in the database)
<%= f.text_field :product_name %>
<%= f.text_field :address %>
<%= f.text_field :price %>
<%= Remove this Product %> # ajax style, this link removes this product entirely
----ID 3----
<%= f.text_field :product_name %>
<%= f.text_field :address %>
<%= f.text_field :price %>
<%= Remove this Product %>
-----Add link------
<%= Add Another Field %> # ajax style adding
<%= f.submit %>
<% end %>
Notice the new IDs that aren't preset and the one submit button so this way more then one Product can be created at a time by a User. How do i achieve the above?
Thank you.
Answer:
Using the User.rb model you can do what James said. Here is my form that works.
<%= form_for(current_user, :url => user_products_path) do |f| %>
<%= f.error_messages %>
<%= f.fields_for :user_products do |builder| %>
<%= render "user_product_fields", :f => builder %>
<% end %>
<%= link_to_add_fields "Add a UserProduct", f, :user_products %>
<%= f.submit "Create" %>
<% end %>
_user_product_fields.html.erb
<div class="fields">
<%= f.label :product, "Product" %>
<%= f.text_field :product %>
<%= f.label :address, "Address" %>
<%= f.text_field :address %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= link_to_remove_fields "remove", f %>
</div>
As others have suggested (somewhat unhelpfully), use nested forms.
You need the form to be based on the current_user object with fields_for declaration for :user_products. You will need to set the url for the form to post back to the user_product controller not the user controller using url_for and you will need to adjust the user_product controllers update and create actions to make use of params[:user] instead of params[:user_product]
If you have your accepts_nested_attributes configured properly all should be good.
BTW if you follow those railscasts you will find that the javascript to add new will not work for Rails 3.x
You should use something like this for your view helpers
module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')")
end
end
and something like this for your javascript in your application.js file
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).up().insert({
after: content.replace(regexp, new_id)
});
}
and obviously your form_for need to be refactored to something like this
<%= form_for(current_user, :url => user_product_path) do |f| %>
<!-- add your f.fields_for :user_products here, probably in a rendered partial -->
<%end%>
That should be enough with the rails casts to get you going
Checkout this:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
You can use cocoon for this.

Categories

Resources