Meteor, Session values and reactivity - session

I recall reading somewhere that one of the nice things about Session variables in Meteor was that when you changed a Session variable, anywhere that you used Session.get for that variable would react to the new value. I have a form where if the user cancels out of adding a new record I set that Session variable back to the last document in the collection, #2 in my case, but the form stays on the never added new record #3.
Here is my basic form;
<template name="transactions">
<form id="trx_form">
{{#each currentVal}}
Trx No. <input type="text" value="{{trx_num}}" id="trx_num" readonly>
Amount: <input type="text" value="{{trx_amount}}" id="trx_amount">
<input type="submit" value="Save" id="save_trx">
<input type="button" value="Cancel" id="cancel_trx">
{{/each}}
</form>
</template>
The Session variable gets set to the last record in the collection in a seperate navigation form Session.set('trx_DB_currentID', trx_DB_currentID)
This is what gets the values of that document;
Template.transactions.currentVal = function() {
var currValues = {trx_num: '', trx_amount: '''};
var trxCursor = trx.find({"_id": Session.get('trx_DB_currentID')});
trxCursor.forEach( function(rec) {
currValues.trx_num = trx.find({"userID": Meteor.userId()}).count();
currValues.trx_amount = rec.trx_amount;
});
var array = [];
array[0] = currValues;
return array;
};
Everything up to this point works fine. Here is the event for clicking the cancel button;
'click #cancel_trx': function(theEvent, theTemplate) {
// Change trx_DB_currentID to last record
var trxCursor = trx.find({"userID": Meteor.userId(), 'trx_num': trx.find({"userID": Meteor.userId()}).count()});
trxCursor.forEach( function(rec) {
Session.set('trx_DB_currentID', rec._id);
});
}
I can see in the console that trx_DB_currentID is indeed set to the id for record #2 but the form still shows a blank record #3. If I click go back one record on my navigation form it brings up record #1. So why doesn't my form react to trx_DB_currentID being set to record #2?

Related

Laravel 5.1, update multiple values from checked checkbox

In Laravel 5.1, I need to update multiple values from checked checkbox.
I can edit some registries from a table by clicking the edit button for each registry, and that button send me to the edit view
(This is de edit view for a single registry)
With the url: http://myapp/someroute/2246/edit where 2246 is some id.
Inside that edit I can update 4 fields. One of those fields is called "my state" and can have the values 1, 2 or 3.
Now, I have to make a multi select edit feature, where I can check every row of the table that I need to update simultaneously (each have the name=someid) and then click some button called "Validate", and update for evey row only 1 field, the my state field, and the new value will be always 1 (in the picture the values are string but thats only for the view).
The question is: how can I call the method update for every id that I'm selecting in the view? every input checkbox has it's own name which is the id of the registry that I will update.
The update method just validate some values from the view and then call some myeditmethod, but in this case I will jump the update and go directly to myedit which is someting like:
public function myedit(Request $request, $id) {
$obj = Self::findOrFail($id);
$obj->fk_id_comuna = $req['fk_id_comuna'];
$obj->fk_id_user = $usuario_id;
$obj->date = \Carbon\Carbon::now();
$obj->fk_id_my_state = $estado; //THIS IS THE ONLY FIELD THAT I WILL EDIT, ALWAYS WITH THE SAME VALUE `1`
$obj->save();
I was trying the make a form for that Validate button but I don't know how to handle multiple id in one call on the edit method.
<form action="{!! route('myroute.update', ['id' => [HERE, HOW CAN I PASS MULTIPLE ID FROM THE CHECKED CHECKBOX] ]) !!}" method="POST">
<input type="submit" class="btn btn-primary pull-right" value="Validar" />
</form>
I was thinking on a javascript function which collect in a array every checked checkbox name and call the myedit method directly, without the formof the view, could be?
About passing multiple values as one Request value.
Assume you have form like this:
<form method="post">
<input type="checkbox" name="options[]" value="foo"/>foo<br/>
<input type="checkbox" name="options[]" value="bar"/>bar<br/>
<input type="checkbox" name="options[]" value="buz"/>buz<br/>
<input type="submit" value="Submit" />
</form>
Your request('options') would be an array: ["foo", "bar", "buz"].
Than you can iterate over options using foreach.
Inside your update method you can go with:
foreach ($option as request('options')) {
//put your previous code here, so it'd be applied for every option
}
In JS I did this:
var optionsChecked = [];
$('.options:checkbox:checked').each( function(){
optionsChecked .push($(this).val());
});
Then in ajax:
$.ajax({
type: 'POST',
data: {'id': optionsChecked },
etc
Then in PHP:
$all = $request->input('id');
foreach ($all as $id){
//whole obj->* = *;
$obj->save();
}

Get the ID from a button which has a dynamic ID

I can not grasp my mind around this.
I am making a ajax call into a servlet. The problem is, on the page that is displayed, i could have 1-20 different buttons that needs to recall the same servlet. So I have the following form...
<form id="ajax-contact">
<input type="text" value="${item.transactionId}" id="transactionId" name="transactionId"/><br>
<input type="text" value="deliveryReceipt" id="action" name="action"/><br>
<input type="text" value="${item.id}" id="id" name="id"/><br>
<button type="submit" id="${item.id}" class="btn btn-primary" data-toggle="modal" data-target=".${item.id}">view delivery receipt</button>
</form>
In my ajax, I have this...
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
//var formData = $(form).serialize();
var id = $("#id").val();
var tranid = $("#transactionId").val();
var action = $("#action").val();
var dataFromForm = "trannsactionId="+tranid+"&action="+action+"&id="+id;
alert(dataFromForm);
alert(formData);
// Submit the form using AJAX.
$.ajax({
url : "Controller",
type: "GET",
data : dataFromForm,
dataType: "json",
})
.success(function(response) {
...
I am trying to make it so the ajax call uses the params for the specific set of information within the form. How can I do this?
Thanks!
More detail:
Once this page shows, if I have 10 sections on there with a button. When I click on the first view delivery receipt button, it works fine.
If I go down my list and click on t he 8th view delivery receipt, itll make an ajax call for the first form.

Get next and previous records in laravel

how to get next and previous records using buttons instead of href,
for example
<form method="post" action="/">
//Question and options will come here,
//when click on next button next question should appear and
// if I click on prev button it should goto prev question
<button type ="submit">Next Question
<button type ="submit">Previous Question
</form>
my Controller
$questions = Question::find($qId);
$options = Question::find($qId)->options;
$previous = Question::where('id', '<', $questions->id)->max('id');
$next = Question::where('id', '>', $questions->id)->min('id');
return view('Pages/User/Questions/Question2')
->with('options',$options)
->with('questions',$questions)
->with('previous',Question::find($previous))
->with('next',Question::find($next));
Now How to send next and prev id on the button submit.
You can do it like this:
You need to add value to button and on submit value will be submitted as well. So, You can get desired record.
<form method="post" action="/">
// your question content
<input name="qId" value="{{$question_id}}" hidden>
<button type ="submit" name="option" value="0">Previous </button>
<button type ="submit" name="option" value="1">Next </button>
</form>
Now, You have to check which button is clicked by using option value,
public function getQuestion(Request $request){
if($request->option==0){
// Get previous record using $request->qId
}else{
// Get Next record using $request->qId
}
// Write code here to return data
}
Hope you understand,

After button disabled its value did not posted to controller

I have an controller which has check like that
if (form["submit"].ToString() == "Continue")
{
}
and i have button which is doing submit
<button name="submit" value="Continue">Continue</button>
It was all working well until i decided to disable Continue button on submit to prevent double click using this function:
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});
So now i don't get value form["submit"] posted on controller.
Any thoughts how may i fix that?
I want still prevent second click but be able to get form["submit"] value posted on controller.
Can you control the submit value in a hidden field in the form? I can't tell what other logic you might need, but when the form renders, you could set the hidden field's value to the submit button's value and change it when necessary using the first script below. As long as it has a name attribute and is enabled (which you'd rarely disable a hidden field) then it will post when the form is submitted.
$(function() {
// this assumes your button has id="myButton" attribute
$(':hidden[name="submit"]').val($('#myButton').val());
});
And of course in your form, you would need a hidden field with name="submit"
<input type="hidden" name="submit" value="Continue" />
Then, whenever the state of your form changes, modify the disabled state of the button and the value of the hidden field to reflect the value (if it changed at all).
There are also frameworks you may find useful for UI features like this. KnockoutJS comes to mind. It can be used to "value" bind input elements. It's probably overkill for this small example, but it could be useful if your UI expands. I've added markup, script and comments below if you're interested.
$(function () {
var viewModel = {
submitValue: ko.observable("Continue")
};
ko.applyBindings(viewModel);
$('form').submit(function() {
if($(this).valid()) {
// the following line will change the both the hidden field's value
// as well as the button's value attribute
viewModel.submitValue("some other value");
// I couldn't follow your selector here, but please note I changed
// the name of the submit button in the markup below.
$(':submit, this).attr('disabled', 'disabled');
}
});
});
KnockoutJS requires you use the data-bind attribute to setup your elements. In your case, you'd bind one property to multiple elements like this:
<button name="submitButton" data-bind="value: submitValue"/>Continue</button>
<!-- and bind the same value similarly in the hidden field-->
<input type="hidden" name="submit" data-bind="value: submitValue"/>

MVC 3: Why is jquery form.serialize not picking up all the controls in my form?

I am trying to create a situation where if a user clicks on an "edit" button in a list of text items, she can edit that item. I am trying to make the "edit" button post back using ajax.
Here's my ajax code:
$(function () {
// post back edit request
$('input[name^="editItem"]').live("click", (function () {
var id = $(this).attr('id');
var sections = id.split('_');
if (sections.length == 2) {
var itemID = sections[1];
var divID = "message_" + itemID;
var form = $("#newsForm");
$.post(
form.attr("action"),
form.serialize(),
function (data) {
$("#" + divID).html(data);
}
);
}
return false;
}));
});
But the form.serialize() command is not picking up all the form controls in the form. It's ONLY picking up a hidden form field that appears for each item in the list.
Here's the code in the view, inside a loop that displays all the items:
**** this is the only control being picked up: ******
#Html.Hidden(indexItemID, j.ToString())
****
<div class="datetext" style="float: right; margin-bottom: 5px;">
#Model.newsItems[j].datePosted.Value.ToLongDateString()
</div>
#if (Model.newsItems[j].showEdit)
{
// *********** show the editor ************
<div id="#divID">
#Html.EditorFor(model => model.newsItems[j])
</div>
}
else
{
// *********** show the normal display, plus the following edit/delete buttons ***********
if (Model.newsItems[j].canEdit)
{
string editID = "editItem_" + Model.newsItems[j].itemID.ToString();
string deleteID = "deleteItem_" + Model.newsItems[j].itemID.ToString();
<div class="buttonblock">
<div style="float: right">
<input id="#editID" name="#editID" type="submit" class="smallsubmittext cancel" title="edit this item" value="Edit" />
</div>
<div style="float: right">
<input id="#deleteID" name="#deleteID" type="submit" class="smallsubmittext cancel" title="delete this item" value="Delete" />
</div>
</div>
<div class="clear"></div>
}
It's not picking up anything but the series of hidden form fields (indexItemID). Why would it not be picking up the button controls?
(The ID's of the edit button controls, by the way, are in the form "editItem_x" where x is the ID of the item. Thus the button controls are central to the whole process -- that's how I figure out which item the user wants to edit.)
UPDATE
The answer seems to be in the jquery API itself, http://api.jquery.com/serialize/:
"No submit button value is serialized since the form was not submitted using a button."
I don't know how my action is supposed to know which button was clicked, so I am manually adding the button to the serialized string, and it does seem to work, as inelegant as it seems.
UPDATE 2
I spoke too soon -- the ajax is not working to update my partial view. It's giving me an exception because one of the sections in my layout page is undefined. I give up -- I can't waste any more time on this. No Ajax for this project.
You could try:
var form = $('#newsForm *'); // note the '*'
Update
Did you change the argument to $.post() as well? I think I may have been a little too simple in my answer. Just change the second argument within $.post() while continuing to use form.attr('action')
New post should look like this:
$.post(
form.attr("action"),
$('#newsForm *').serialize(), // this line changed
function (data) {
$("#" + divID).html(data);
}
);

Resources