Meteorjs use input select multiple and push to collections - javascript

Hi everybody this is my first project in meteor js.
I'm using Meteor 1.4.1.1 with this package:
aldeed:collection2 2.10.0
I have this field in my collection
Clienti.ClienteSchema = new SimpleSchema({
cantieri: {
type: [Clienti.Cantieri],
optional: true,
autoform: {
type: "hidden"
}
}
});
Clienti.Cantieri = new SimpleSchema({
giorni: {
type: [Clienti.Giorni],
optional: true,
autoform: {
type: "hidden"
}
}
});
Clienti.Giorni = new SimpleSchema({
giorno: {
type: Date,
label: "giorno del lavoro"
},
oraPartenza: {
type: Date,
label: 'Giorno e ora partenza',
},
oraInizio: {
type: Date,
label: 'Giorno e ora inizio',
optional: true
},
oraFine: {
type: Date,
label: 'Giorno e ora fine',
optional: true
},
dipendenti: {
type: [Dipendenti]
}
});
This is the input's select
<div class="col-xs-12">
<div class="form-group">
<label class="checkbox" for=dipendenti>dipendenti</label>
<select multiple name="dipendenti">
{{#each Dipendenti}}
<option value="{{_id}}">{{nome}} {{cognome}}</option>
{{/each}}
</select>
</div>
</div>
with this form I'd like to submit the last field Giorni in a existing Cliente.cantiere.
I tried:
Template.nuovoGiorno.events({
'submit #Giorno'(event) {
event.preventDefault();
const id = FlowRouter.getParam('id');
const target = event.target;
const giorno = target.giorno.value;
const oraPartenza = target.oraPartenza.value;
let select = target.dipendenti.options;
let selezionati=[];
for (var i = 0; i < select.length; i++) {
var option = select[i];
if (option.selected){
console.log(id);
console.log('opzione ' + option.value);
Clienti.update({_id:id}, {$set:{
'cantieri.giorni.giorno': giorno,
'cantieri.giorni.oraPartenza': oraPartenza,
'cantieri.giorni.dipendenti._id': option.value
}});
}
}
}
});
but doesn't work. How can I fix it?

It looks like your cantieri key is an array of objects which are themselves arrays of objects. Is this really what you want?
I would try:
Clienti.update({ _id: id }, { $set: {
cantieri: [{
giorni: [{
giorno: giorno,
oraPartenza: oraPartenza,
dipendenti._id: option.value
}]
}]
}});
If you want to push a giorni into a specific cantieri (as per your comment) then select the cantieri you want in the query and then push a new giorni into it:
Clienti.update({ _id: id, cantieri: myCantieri }, { $push: { 'cantieri.giorni': newGiorni }});

Related

disallow blank/empty cells in kendo grid

How could I disallow a cell in my kendo grid to be 'blank' or 'empty' rather... How could I replace all blank or empties with a 0..
I have a save button grabbing the values from my kendo grid such as below: Everything works fine EXCEPT, it is completely omitting my empty cells.. I want to keep them, just have a 0 value on them...
Save button: want to keep the empties with simply a 0 or N/A..
$('.' + chs).on('click', '#saveChanges', function(e) {
which = $(frm).attr("class");
let dataSource = $("#grid").data("kendoGrid").dataSource,
data = dataSource.data(),
changedModels = [];
if(dataSource.hasChanges) { // only saves cells/row that have been edited/changed, need to keep this
for(var i = 0; i < data.length; i++) {
if(data[i].dirty) { changedModels.push(data[i].toJSON()) }
}
}
let ds = JSON.stringify(changedModels);
$.ajax({
type: "POST",
url: "saveGrid",
dataType: "json",
data: {
id: which,
data: ds
},
success: function(result) {
console.log('yy');
},
error: function(result) {
console.log('nn');
}
});
});
This is my kendo grid initialized:
let dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/popGrid?id=" + which,
dataType: "json"
},
},
batch: true,
schema: {
data: "data",
model: {
id: id,
}
},
});
console.log(id);
$("#grid").kendoGrid({
dataSource: dataSource,
height: 600,
sortable: true,
autoBind: true,
nullable: true,
editable: {
createAt: "top"
},
change: function(e) {
let grid = $("#grid").data("kendoGrid");
let selectedItem = grid.dataItem(grid.select());
let val = selectedItem.id;
console.log(val);
},
selectable: "row",
toolbar: [
{ name: "create" },
{ name: "cancel" }
],
paging: false,
});
I can't understand if you want to POST empty fields as "0" or if you want to SHOW them in the grid as "0", when null or "empty".
But I guess you're talking about posting it as "0". In that case I think you have to do that before posting:
let fieldName = 'myCell';
if (data[i].dirty) {
if (!data[i].hasOwnProperty(fieldName) || // In case field is not present on data
!data[i][fieldName]) { // In case field value is null/undefined/0/false/empty string
data[i][fieldName] = 0;
}
changedModels.push(data[i].toJSON());
}
For multiple field check:
let fieldNames = ['fieldA', 'fieldB', ...],
checkFields = (item) => {
fieldNames.forEach(field => {
if (!item.hasOwnProperty(field) || // In case field is not present on data
!item[field]) { // In case field value is null/undefined/0/false/empty string
item[field] = 0;
}
});
};
Or you can do the same before data is bound to the grid with dataSource.schema.parse.

How to dinamically fill sap.m.Select with data?

I need to display some odata's data in a sap.m.Select but don't know why is not working, This is the code I have so far
var oModel = new sap.ui.model.json.JSONModel();
var data = [];
var sUrlCard = "odata's url";
var oDataModel = new sap.ui.model.odata.ODataModel(sUrlCard, true);
oDataModel.read("CardBrandCollectionSet", {
async: false,
success: function(oData, response) {
$.each(oData.results, function(i, val) {
data.push(val);
});
oModel.setData({
'card': data
});
sap.ui.getCore().setModel(oModel, "card");
},
error: function(oError) {
console.log(oError);
}
});
table where the select input is located
var oTable = new sap.m.Table({
mode: oMode,
columns: [
{
hAlign: 'Center',
header: new Text({
text: "Card"
})
}
]
});
Select input I need to fill with data
var oSelectMarca = new sap.m.Select({
items: {
path: "/card",
template: new sap.ui.core.ListItem({
key: '{Codcard}',
text: '{Descript}'
}),
templateShareable: true
},
selectedKey: '{Marca}'
});
The binding path of the select control is wrong:
sap.ui.getCore().setModel(oModel, "card"); // model is set at core with name as card
$.each(oData.results, function(i, val) {
data.push(val);
});
oModel.setData({
'card': data // setting data in an object with name as card
});
var oSelectMarca = new sap.m.Select({
items: {
path: "card>/card/", //Binding path model name along with array name
template: new sap.ui.core.ListItem({
key: '{card>Codcard}', // model name with property name
text: '{card>Descript}' // model name with property name
}),
templateShareable: true
},
selectedKey: '{card>Marca}' // model name with property name
});
fist of all you do not want to create your odata model like that, please specify it in your manifest:
in "sap.app" part:
"dataSources": {
"yourRemote": {
"uri": "YOUR_URI",
"type": "OData",
"settings": {
"odataVersion": "2.0"
}
}
}
in "sap.ui5" part:
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "YOUR_i18n"
}
},
"remoteModel": {
"dataSource": "yourRemote"
}
}
2nd you dont want to create controls in js, you do that in your xml files:
https://sapui5.hana.ondemand.com/#/topic/1409791afe4747319a3b23a1e2fc7064
https://blogs.sap.com/2018/05/01/why-do-we-use-xml-views-rather-js-views-in-sapui5/
in that your select needs to be bound like that:
<Select
id="anID"
valueState="{vsModel>/otherText}"
valueStateText="{i18n>someText}"
forceSelection="false"
items="{
path: 'remoteModel>/CardBrandCollectionSet',
sorter: {
path: 'Descript'
}
}">
<core:Item key="{remoteModel>Codcard}" text="{remoteModel>Descript}" />
</Select>

Pass data from a JavaScript array to an HTML form

I am trying to learn JavaScript and I came across a practice problem in a book I purchased that I cannot seem to crack. The task is to flesh out a javascript formBuilder function to generate HTML forms dynamically from a JavaScript array. I have copied the code from the book onto a CodePen page for visual and testing purposes.
CodePen: http://codepen.io/anon/pen/gpwZMX
HTML sample:
<div>
<button data-sample='1'>Run 1</button>
<button data-sample='2'>Run 2</button>
<button data-sample='3'>Run 3</button>
</div>
<hr>
<div id='spec'>
<i>This div will display the currently-processed spec</i>
</div>
<br>Output:
<div id='result'>
<i>I sure wish I had a cool html form in me...</i>
</div>
<!--here are some test cases in docblock form-->
<div class='testcase' id='1'>
/** Comment Form
* Make a comment on the blog post!
* #param string[100] title
* #param email email
* #param text body
* #param bool subscribe Email me when someone comments on my comment!
*/
</div>
JavaScript sample:
var samples = [
{
title:"Comment Form",
desc:"Make a comment on the blog post!",
params:[
{
type: 'text',
max_length: 100,
name: 'title'
},
{
type: 'email',
name: 'email'
},
{
type:'textarea',
name:'body'
},
{
type:'checkbox',
name:'subscribe',
label:'mail me when someone comments on my comment!'
}
]
}]
formBuilder sample:
//builds an HTML form using all information present in `spec` and places the resulting HTML in jquery element `$el`
function formBuilder(spec,$el){
$el.html("<i>I still wish I had a cool html form in me...</i>");
}
$("button").on("click",function($e){
var specIndex = $($e.target).data('sample');
var specData = samples[specIndex-1];
$("#spec").html("Sample spec "+(specIndex)+" looks like: <br>"+JSON.stringify(specData));
formBuilder(specData, $("#result"));
});
Errors in the codepen code exist, paste the code below into your project:
var samples = [
{
title:"Comment Form",
desc:"Make a comment on the blog post!",
params:[
{
type: 'text',
max_length: 100,
name: 'title'
},
{
type: 'email',
name: 'email'
},
{
type:'textarea',
name:'body'
},
{
type:'checkbox',
name:'subscribe',
label:'mail me when someone comments on my comment!'
}
]
},
{
title:"Car Order Form",
desc:"Choose your car!",
params:[
{
type:'select',
values:['red','blue','green','black','white','taupe'],
name: 'color'
},
{
type: 'checkbox',
values:['fog-lights','radio','a-c','wheels','headlights'],
name: 'options'
},
{
type:'string',
minLength:7,
maxLength:7,
name:'vanityPlate',
optional:true
},
{
type:'int',
name:'price',
}
]
},
{
title:"New User Creator",
desc:"Create a new user account",
params:[
{
type:'string',
maxLength:20,
name:'fname',
label:'First Name'
},
{
type:'string',
maxLength:20,
name:'lname',
label:'Last Name'
},
{
type:'date',
name:'dob',
label:'Date of Birth'
},
{
type:'email',
multiple:true,
maxCount:4,
name:'emails',
label:'Email Addresses'
},
{
type: 'string',
name: 'addr1',
label: 'Street Address'
},
{
type: 'string',
name: 'city'
},
{
type: 'state',
name: 'state',
},
{
type: 'int',
name: 'zipcode',
maxValue: 99999,
minValue: 0,
label: 'ZIP'
},
]
}
]
//builds an HTML form using all information present in `spec` and places the resulting HTML in jquery element `$el`
function formBuilder(spec,$el){
var inputs = getInputs(spec);
$el.html("<form title='"+spec.title+"'><fieldset><legend>"+spec.desc+"</legend>"+inputs+"</fieldset></form>");
}
function getInputs(spec) {
var inputs = "";
for(var i = 0; i < spec.params.length; i++) {
var input = "<input ";
var attributes = JSON.stringify(spec.params[i]).split(",");
console.log(attributes);
for(var j = 0; j < attributes.length; j++) {
$.each(spec.params[i], function(key, value) {
input += key + "='" + value + "' ";
});
}
inputs += input + "/><br/>";
}
return inputs;
}
$("button").on("click",function($e){
var specIndex = $($e.target).data('sample');
var specData = samples[specIndex-1];
$("#spec").html("Sample spec "+(specIndex)+" looks like: <br>"+JSON.stringify(specData));
formBuilder(specData, $("#result"));
});
The last item in an array does not get a comma appended to it. Always ensure to end a line of code with a semi-colon as well. Those are the changes I made to your code, now it runs, as I assume, correctly unless you have any other issues?

jquery select2 add text to source if not found in source

I want select2 to behave as sort of combobox.See attached image for ref.
So if user types in a string but it is not found in source array, then on enter or closing select2 it should add that new string to source. So say if there were 2 values before, after above there would be now 3.
select2 just like combobox in file open dialogs
I have created sample code, but cant make it to work.I am unable to update source.
JSFIDDLE:
HTML:
<div class="row">
<div class="col-md-2">
<input type="hidden" id="select2_sample3" class="form-control ">
</div>
</div>
JS:
$(function () {
var preload_data = {
results: [{
id: 'user0',
text: 'Disabled User',
}, {
id: 'user1',
text: 'Jane Doe'
}]
};
$("#select2_sample3").select2({
placeholder: "Select...",
allowClear: true,
minimumInputLength: 1,
data: preload_data,
query: function (query) {
var data = {
results: []
}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {
s = s + query.term;
}
data.results.push({
id: query.term + i,
text: s
});
}
query.callback(data);
}
}).on("select2-close", function () {
// add to
console.log("close");
});
});
I've recently had the same task. This is my solution:
<input type="hidden" name="trBrand" id="trBrand" class="form-control"></input>
and js code
$('#trBrand').select2({
placeholder: 'choose something',
allowClear: true,
id: function(object) {
return object.text;
},
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
data:preload_data
});

Select2: how to set data after init?

I need to set an array of data after initializing select2. So I want to make something like this:
var select = $('#select').select2({});
select.data([
{id: 1, text: 'value1'},
{id: 1, text: 'value1'}
]);
But I get the following error:
Option 'data' is not allowed for Select2 when attached to a element.;
My HTML:
<select id="select" class="chzn-select"></select>
What should I use instead of a select element?
I need to set the source of items for search
In onload:
$.each(data, function(index, value) {
$('#selectId').append(
'<option value="' + data[index].id + '">' + data[index].value1 + '</option>'
);
});
Make an <input type="hidden"> element and bind select2 to that. Using .select2 on a regular select box doesn't let you play with the data, it just mostly gives you the UI and post-selection methods.
Source:
Select2 Documentation
Source: https://select2.org/programmatic-control/add-select-clear-items
Add item:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
Clear items:
$('#mySelect2').val(null).trigger('change');
For v4 you'll have to destroy and reconstruct select2 with updated data. Check https://github.com/select2/select2/issues/2830
I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:
$("#group").on('change', function () {
var uri = "/Url/RetrieveNewResults";
$.ajax({
url: uri,
data: {
format: 'json',
Id: $("#group :selected").val()
},
type: "POST",
success: function (data) {
$("#groupchild").html('');
$("#groupchild").select2({
data: data,
theme: 'bootstrap',
placeholder: "Select a Type"
});
},
error: function () {
console.log("Error")
}
});
});
I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.
You can rerender and trigger the select2
render select2
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true
});
after need to change the data data
let dataChange = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
rerender the select2
$('.select2').select2('destroy');
$('.select2').empty();
$('.select2').select2({
placeholder: 'Slect value',
allowClear: true,
data: dataChange
});
trigger select2
$('.select2').trigger('change');
Hope this is the answer for you :3
Here's what I did.
1. Extend select2
Select2.prototype.setAjax = function (ajaxOptions)
{
// Set the new ajax properties
var oAjaxOpts = this.options.get('ajax');
if (oAjaxOpts != undefined && oAjaxOpts != null)
{
for (var sKey in ajaxOptions)
{
oAjaxOpts[sKey] = ajaxOptions[sKey];
}
}
var DataAdapter = this.options.get('dataAdapter');
this.dataAdapter = new DataAdapter(this.$element, this.options);
}
2. Initialize as usual (for example --- yours could be different)
jHtmlFrag.select2({
dropdownParent: $(oData.jDiv),
placeholder: "Select Option",
allowClear: true,
minimumInputLength: 2,
ajax: {
url: "",
method: "POST",
dataType: 'json',
delay: 250,
processResults: function (oResults, params)
{
let page = params.page || 1;
// console.log(oResults, (params.page * 10));
return {
results: oResults.data,
pagination: {
more: (page * 10) < oResults.recordsFiltered
}
};
}
}
}).val(null).trigger('change');
3. Set Ajax options dynamically when you feel like by calling the new extension func
jCombo.select2('setAjax', {
url: sUrl,
data: function (params)
{
let query = {
search: params.term,
type: params._type,
page: params.page || 1,
}
return query;
},
});

Categories

Resources