Is it possible to submit a hidden field and control its value with x-editable? - submit

inside the document of X-editable, we can create a new record, but how to edit an existing record, and post its name and email fields as well as its id =1(this id not changed) to the backend?
<table>
<thead><th>id</th><th>name</th><td>email</th></thead>
<tbody>
<tr><td><span>1</span></td><td><span class='myeditable'>name</span></td><td><span class='myeditable'>email#example.com</span></td></tr>
</tbody>
</table>
$('.myeditable').editable({
type: input,
url: '/edituser'
});
$('#save-btn').click(function() {
$('.myeditable').editable('submit', {
url: '/edituser',
ajaxOptions: {
dataType: 'json' //assuming json response
},
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
},
error: function(errors) {
}
});
});

I used Angular-xeditable to do this, but the idea is the same I think.
I added a hidden span to my table and gave it an e-name. ng-show sets display:none, which I think is just what you need to do as well.
<span
editable-text="journalEntry._id"
e-name="_id"
e-form="rowform"
ng-show="false">
</span>

I used Angular-xeditable also, but had to change Michael's code because the hidden field appeared (I wanted it to remain hidden) when I edited the row.
Therefore I had to insert
e-class="hidden"
So in the end I had:
<span
e-class="hidden"
editable-text="employee.key"
e-name="key"
e-form="rowform"
ng-show="false">
</span>

To post a hidden field, you could try to modify your
url: '/edituser'
to
url: '/edituser?hidden-name1=hidden-value1&hidden-name2=hidden-value2' and so on...

Related

How to use Ajax for nested form on active admin rails

Please help me out with this problem. I am new on rails
I am trying to use the ajax method to get values on the active admin nested form. But only the top of the form gets dynamic values. After changing values on the top one form on the nested form then ajax makes a request then it changes the values(i.e. update the form values).
But after adding a new buy line item then ajax makes a request but doesn't update the values on the form i.e.same values for every new buy line item.
my js code
app/assets/javascripts/buys.js
// for nested buyline items of buys resources
$('.lineItem').change(function () {
$.ajax({
url: '/admin/get_buys_buy_line_item',
type: 'GET',
dataType: "json",
data: {
product_id: $('.lineBuyProduct').val(),
buy_quantity: $(".lineBuyQuantity").val(),
buy_quantity_unit: $(".lineBuyUnit").val(),
buy_price: $(".lineBuyAmount").val(),
},
success: (data) => {
alert(data);
// if (data == null) {
// document.getElementById('lineQuantity').value = ' ';
// document.getElementById('lineAmount').value = ' ';
// }
// else {
// document.getElementsByClassName("linebuyQuantity").value = data['1'];
// document.getElementsByClassName('linebuyAmount').value = data[0];
// console.log("Dynamic select OK!")
// }
}
});
});
});
My active admin forms
f.inputs 'Line Items', class: "lineItem" do
table do
thead do
tr do
th 'S.N', class: 'form-table__col'
th 'Product', class: 'form-table__col'
th 'Quantity', class: 'form-table__col'
th 'Unit', class: 'form-table__col'
th 'Amount', class: 'form-table__col'
th 'Expiry Date', class: 'form-table__col'
th 'Destroy', class: 'form-table__col'
end
end
end
f.has_many :buy_line_items, new_record: 'Add Buy Line Item', heading: false, allow_destroy: true do |x|
x.input :sn, label: false
x.input :product, label: false, as: :select2, collection: Product.drop_down_options,
input_html: { required: true, class: 'lineBuyProduct' }
x.input :buy_quantity, label: false, input_html: { required: true, class: 'lineBuyQuantity' }
x.input :buy_quantity_unit, label: false, collection: Unit.all.pluck(:name),
input_html: { class: 'lineBuyUnit' }
x.input :buy_price, label: false,
input_html: { required: true, class: 'lineBuyAmount' }
x.input :expiry_date, as: :date_picker, input_html: { style: 'width:auto' }, label: false
end
end
Some of my screenshots of how my program behaves and what my expectations are
In this image my first selection of product on buy line iteme then on request we can see json are renderd
But in this image after selecting another product again same json data are rendered that means doesn't update with different respective product values
And there are also some problems on active admin blaze theme, after adding class on form then it changes to legend color and add item button colors to light brown
This picture is about after removing custom class name lineItem.But, after removing this class then ajax doesn't hit for that form
Might be i faced such problem due to nested form's class on active admin.While i used default class of those form from inspect then it even doesn't hit to that form for ajax request.
So, please expert team help me to slove this problem.
If you want to send the data to create a new entity(record), you need to use the http POST method: https://api.jquery.com/jquery.post/
The GET request it just retrieves an already existing entity. Probably that's why you can read some data after an ajax call, but it's not updated.
More about the differences between GET and POST methods:
When should I use GET or POST method? What's the difference between them?
If this fix doesn't work, check the rails logs.
I have never used anything related to Ruby, and I'm not completely sure if I understood your question. I'm assuming you have problems with the AJAX behavior for new items in the list. Considering that, I think your problem could be related to attaching the "change" event to the new items. I think there might be many different other ways to get the behavior you want, but I will just elaborate on your solution using JS.
From the activeAdmin's code you can see they trigger an event called "has_many_add:after" when a new item was successfully added to its parent. Considering that, I would try changing your Javascript code to:
// for nested buyline items of buys resources
$("#buy_line_items").on("has_many_add:after", function(event, fieldset, parent){
fieldset.change(function () {
$.ajax({
url: '/admin/get_buys_buy_line_item',
type: 'GET',
dataType: "json",
data: {
product_id: $(this).find('.lineBuyProduct').val(),
buy_quantity: $(this).find(".lineBuyQuantity").val(),
buy_quantity_unit: $(this).find(".lineBuyUnit").val(),
buy_price: $(this).find(".lineBuyAmount").val()
},
success: (data) => {
alert(data);
// if (data == null) {
// document.getElementById('lineQuantity').value = ' ';
// document.getElementById('lineAmount').value = ' ';
// }
// else {
// document.getElementsByClassName("linebuyQuantity").value = data['1'];
// document.getElementsByClassName('linebuyAmount').value = data[0];
// console.log("Dynamic select OK!")
// }
}
});
});
});
I'm very confident that this will work, mainly because I don't have how to try it (if you give me the generated HTML maybe it'd help me). You can try it and reach back to see if it worked or if any adjustment is required.
You might want to change your commented lines accordingly. Also about the identifier "#buy_line_items" I'm not sure if it exists in the rendered HTML so you might need to adjust that as well.

Using same form as local and remote both in rails for filtering purposes

Scenario:
I have a form that does some filtering. For the sake of simplicity, let's assume I have a form that has three input options:
<%= form_tag(some_path,method: :get) do %>
#..checkboxes for option 1
#..radiobuttons for option 2
#..checkboxes for option 3
<%= submit_tag "submit" %>
<% end %>
<p>You have a total of: COUNT results.</p>
Required Output:
What I want is the functionality when a user clicks on any checkbox or radio button, (essentially a change in any input field), by ajax request should be generated to a path that returns a COUNT of total results, and I will update the COUNT inside p tag with that returned count number.
And when the user clicks on submit button, the default GET request should be generated.
I added this script for ajax request, and it is working perfectly fine.
<script>
$(".option").change(function(){
var type = $("input[name='type[]']:checked").map(function () {
return this.value;
}).get();
$.ajax({
url: "/gre",
type: "put",
dataType: "json",
data: {custom: 'true',type: type},
success: function (response) {
var count = response["count"];
$('#count').html('Your session will have a total of '+ count + ' questions.');
}
});
});

View rails record details in bootstrap modal on row click

I have been stuck on this problem for quite some time now and looked through several posts as well, however I cannot achieve exactly what I want for my Rails application. Essentially, I want to be able to click on a table row on my page and have a modal pop up which displays all the information for that specific record. Here are the scenarios which I have thought of/attempted partially:
Set the data-link attribute in table row with some JS as follows
HTML:
<tr data-link="<%= kid_path %>">
...
</tr>
JS:
$("tr[data-link]").dblclick(function() {
window.location = $(this).data("link")
})
This worked fine to open the show path page generated by the scaffold, but I was not able to modify it to work with a modal and have the same data for the kid in the modal.
Use data-id and JavaScript to load onto the modal
HTML:
<tr data-id="<%= kid.id %>">
...
</tr>
JS:
$(function () {
$('#showModal').modal({
keyboard: true,
backdrop: "static",
show: false,
}).on('show', function () {
});
$(".table-striped").find('tr[data-id]').on('click', function () {
debugger;
$('#showDetails').html($('<p>' + 'Kid ID: ' + $(this).data('id') + '<%= Kid.find(30).first_name %>' + '</p>'));
$('#showModal').modal('show');
});
});
In this approach I am able to load the modal on row click and am able to access the Kid ID, however I cannot move further to access other attributes of the record. For example, I want to set #Kid = kid.find(id) using JS where id would be the extracted ID from the row. And then, I want to be able to write the generic modal template which displays other elements (ex. kid.first_name, kid.last_name, etc).
I am totally stuck and cannot find any approach that helps to accomplish my goal. Any help is appreciated, thank you.
You need to ajax call record attributes because the line Kid.find(30).first_name doesn't exist at the time page loaded.
Try this:
KidsController
def show
kid = Kid.find(params[:id])
respond_to do |format|
format.html { // Usually show.html.erb }
format.json do
# Return kid as json object
result = {
first_name: kid.first_name,
last_name: kid.last_name
}
# If you want to return the whole kid record attributes in json: result = kid.attributes.to_json
render json: result
end
end
end
Try /kid/[:id].json to verify that you are not getting UnknownFormat error.
JS
$(".table-striped").find('tr[data-id]').on('click', function () {
var kid_id = $(this).data('id');
$.getJSON("/kid/" + kid_id, function(data) {
// Render the modal body here
// first_name = data.first_name, last_name = data.last_name etc
$('#showDetails').html($('<p>'+ data.first_name + '</p>'));
$('#showModal').modal('show');
});
})
If you have setup correct route for Kid model then these are what you needed.
UPDATED: I made a typo in the result hash. FIXED

Ember direct URL or page refresh empty model

I have an index page with different courses. From that index page you can navigate to a specific course by a link-to. When I navigate to a course everything works fine but when I refresh the page or go to that URL directly the model is empty.
This is how my code looks like:
index.hbs ---------------------------------------
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<h1>Become a Tjuna Fish</h1>
<img src="http://placehold.it/500x300">
<p>Leer met de technieken werken die bij Tjuna worden gebruikt en ontwikkel jezelf tot een echte Tjuna Fish!</p>
</div>
</div>
<div class="row">
<h1 class="text-center">Cursussen</h1>
{{#each}}
<div class="col-md-4 text-center">
<div class="row">
<img {{bind-attr src="img"}}/>
</div>
<div class="row">
{{#link-to "course" this}}{{title}}{{/link-to}}
</div>
</div>
{{/each}}
</div>
scripts ---------------------------------------
BecomeTjunaFish.Router.map(function () {
// Add your routes here
this.resource('index', {path: '/'});
this.resource('course', { path: ':url'});
});
BecomeTjunaFish.IndexRoute = Ember.Route.extend({
// admittedly, this should be in IndexRoute and not in the
// top level ApplicationRoute; we're in transition... :-)
model: function () {
return this.store.find('course');
}
});
BecomeTjunaFish.CourseRoute = Ember.Route.extend({
// admittedly, this should be in IndexRoute and not in the
// top level ApplicationRoute; we're in transition... :-)
model: function (params) {
return this.store.find('course', params.id);
}
});
BecomeTjunaFish.Course = DS.Model.extend({
title: DS.attr('string'),
img: DS.attr('string'),
goal: DS.attr('string'),
targetGroup: DS.attr('string'),
prerequisites: DS.attr('string'),
url: DS.attr('string')
});
BecomeTjunaFish.Course.FIXTURES = [
{
id: 1,
title: 'Tjuna Basis',
img: 'http://placehold.it/200x200',
goal: 'kunnen werken met de basis tools en opmaaktalen die Tjuna gebruikt',
targetGroup: 'frontend developers in wording',
prerequisites: 'geen',
url: 'basis_cursus'
},
{
id: 2,
title: 'Tjuna Frontend',
img: 'http://placehold.it/200x200',
goal: '',
targetGroup: '',
prerequisites: '',
url: 'frontend_cursus'
},
{
id: 3,
title: 'Tjuna Backend',
img: 'http://placehold.it/200x200',
goal: '',
targetGroup: '',
prerequisites: '',
url: 'backend_cursus'
}
];
You need to specify the dynamic segment as :id in your router. What happens is,
When you transition via {{link-to}}, you pass the entire model object. Hence while retrieving the course model(this.store.find('course', params.id);) in route#model , you have the id with you and thereby fetching the model with no trouble.
When you hit back or refresh the course page, all you have is the course url in the address bar URL. This course url (note the entire course object) will be passed to the course route#model hook where you try to retrieve using the id. Hence it blows up
So make your dynamic segment as id in the router to make it work. You can also fetch the records with name.
Working Jsbin
As selvagsz explained, I had to change :url to :id in the router.
I also wanted to have nested URL's without nested templates. Something like this:
this.resource('index', {path: '/'});
this.resource('course', { path: ':course_id'}, function(){
this.resource('lesson', {path: ':lesson_id'}, function(){
this.resource('topic', {path: ':topic_id'});
});
});
Problem with this is, when I go to course/lesson url the lesson template will only render when I have an outlet in the course template. I want the course template to be replaced with the lesson template but keep the same nested url.
I fixed this by using the renderTemplate function of Ember like this:
BecomeTjunaFish.LessonRoute = Ember.Route.extend({
model: function (params) {
return this.store.find('lesson', params.lesson_id);
},
renderTemplate: function() {
this.render('lesson', { into: 'application'})
}
});
This works great but when I navigate back, for example to course, it is not working anymore. Instead of only have a courseRoute I also needed a courseIndexRoute which uses the same model as courseRoute and place the renderTemplate in the CourseIndexRoute (same for LessonIndexRoute). Example:
BecomeTjunaFish.CourseRoute = Ember.Route.extend({
model: function (params) {
return this.store.find('course', params.course_id);
}
});
BecomeTjunaFish.CourseIndexRoute = Ember.Route.extend({
model: function () {
return this.modelFor('course');
},
renderTemplate: function() {
this.render('course', { into: 'application'})
}
});
To me it seems to be a lot of code and I don't know if this is the right way to do this. At the moment this is good enough for me, it's working :) But I would appreciate it to have feedback on it and would like to know if there are other / better ways to fix this.
*I used this question as inspiration: Redirecting from edit to parent resource doesn't (re)render template

Auto refresh <div> without reload entire page

I'm trying to update the content of "mydiv" without refreshing the entire index page.
#mydata is given by mycontroller. I need to recalculate it every n seconds and pass it to "mydiv"
With "link_to" it works!
index.html.erb
<%=
link_to('refresh', '/mycontroller/index', :remote => true)
%>
<div id="mydiv">
<%=
#mydata
%>
</div>
index.js.erb
$('#mydiv').html('<%= escape_javascript(#mydata) %>')
Now I need to refresh the content of "mydiv" automatically every n seconds (so without click on the link). I have tried solutions from:
First Link
Second Link
but no luck.
In my application.js I have writed this:
function executeQuery() {
$.ajax({
//url: '/index',
success: function(data) {
$('#mydiv').html(data)
}
});
setTimeout(executeQuery, 500);
}
$(document).ready(function() {
setTimeout(executeQuery, 500);
});
For who is facing my same problem, I solved it by replacing
$('#mydiv').html(data)
with
$('#mydiv').load('/mycontroller/index #mydiv')
Use setInterval() instead of using setTimeout().
Ref: https://www.w3schools.com/jsref/met_win_setinterval.asp
function executeQuery() {
$.ajax({
type: 'GET',
url: 'example.com/url/', // Provide your response URL here.
success: function(data) {
$('#mydiv').html(data);
}
});
}
setInterval(executeQuery(), (n * 1000)); // Replace 'n' with how many seconds you want.
This code will run the executeQuery() method in every 'n' seconds interval. So that your requirement is accomplished.
Set layout to false in the action and just pass on the relevent content, not the entire page
def action1
<your code here>
end
def action2
<your code here>
render :layout => false
end
Your view for action2 should have content pertaining only to #mydiv.
A better solution would be to use a single action and change render options based on type of request. (Ajax or non ajax)

Resources