How to load selectize.js email contacts options dynamically - javascript

I'm using selectize.js like email contacts. But when I get mail list from database selectize shows undefined. When I type return value manuelly everything is fine. How can I populate it? Here is my code samples.
Return Value:
"[{"name":"Test User 1","id":"1"},{"name":"Test User 2","id":"2"}]"
C#
public JsonResult GetMails(){
var list = db.Members
.Where(x => x.IsActive == Status.Active)
.OrderBy(x => x.FullName)
.Select(c => new
{
name = c.FullName,
id = c.Id.ToString()
});
return Json(list, JsonRequestBehavior.AllowGet);
}
Javascript
<script type="text/javascript">
$(function () {
$.get("/mail/getmails", function (data) {
$("#MailReceivers").selectize({
persist: false,
plugins: ['remove_button'],
maxItems: null,
valueField: 'id',
labelField: 'name',
searchField: ['name', 'id'],
options: JSON.stringify(data),
create: function (input) {
return {name: input};
}
});
});
});
</script>

The answer is first parse json and than stringfy.
options: JSON.parse(JSON.stringify(data))

Related

how to solve Trying to get property 'bids' of non-object error

I want to display data from bid table in a form of datatable. But I get this error
"Trying to get property 'bids' of non-object" if it doesn't have bids.The bids model is connected to auction model and the auction model is connected to media site model. How to make it display blank record if it doesn't have data.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Auction;
use App\Bid;
use App\User;
use App\Media;
use App\MediaSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MediaSiteController extends Controller
{
public function show(MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
$bids = $auction->bids;
return view('admin.media-site.show', ['mediaSite' => $mediaSite,'auction' => $auction], compact('auction'));
}
My view:
<body>
<div id="datatable-bid"></div>
</body>
<script>
$(document).ready(function () {
var datatableBid = $('#datatable-bid').mDatatable({
// datasource definition
data: {
type: 'local',
source: {!! json_encode($auction->bids) !!},
pageSize: 10
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false,
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
search: {
input: $('#panel-search')
},
// columns definition
columns: [
{
field: "price",
title: "Price",
}, {
field: "month",
title: "Month",
},{
field: "user_id",
title: "User Id",
}
]
});
</script>
Here is my error:
Trying to get property 'bids' of non-object
place following after $auction = $mediaSite->auction;
if($auction){
$bids = $auction->bids;
}else{
//put following line or whatever you need to do if there is no data comes
$auction = [];
}
In the show() function make these changes
$auction = $mediaSite->auction;
if($auction) {
$bids = $auction->bids;
} else {
$bids = [];
}
// now send $bids to view along with $auction
// may be like this
// return view(..., compact($auction, $bids));
Then, in your view make this change
// datasource definition
data: {
type: 'local',
source: {!! json_encode($bids) !!},
pageSize: 10
},
See if this helps.

Parsing initial values to an ExtraSignUp Fields Meteor

I am trying to add a hidden field for the user registration. The problem is not with the field itself but with its value. I want to parse it a default value. This is my code:
Accounts.ui.config({
requestPermissions: {},
extraSignupFields: [{
fieldName: 'name',
fieldLabel: 'Name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
},{
fieldName: 'status',
fieldLabel: 'Status',
inputType: 'text',
value: 'somevalue',
visible: false,
}]
});
I want to add the value to the field 'status'.
Actually, I found the answer. The option is the following code in the
server folder:
Accounts.onCreateUser(function(options, user) {
if (options.profile) {
user.profile = options.profile;
}
user.profile.status = "sth";
return user;
});
Looking at the implementation of signup in that package, there is no way to set a default value. The code just creates an object in signup() and grabs whatever existing values from the form that it can.

Select2 inserts an empty text option in the dynamic list

I am using Select2 with Jquery-editable and encountering an abnormal behavior of Select2, what I am doing is displaying editable table of information using ejs template, and as user clicks on CBA opens up a select2 box which have the originally selected result, and then user can add or delete options in it, options comes from Database source, and when user selects an options it adds an empty option in database with the selected option , the array looks like this
[ "ABCD", "ONAB", "" , "BCNU" ]
I read somewhere about allowClear: true and add a placeHolder but It doesn't helped me at all. As everything is done dynamically I can't find where that empty option is added.
Code is below:
Ejs/HTML code for Select 2
<tr>
<td width="40%">Select CBA(s)</td>
<td>
<a class="cbaSelectUnit" data-emptytext="Select CBA(s)" data-original-title="Select CBA(s)" data-type="select2"></a>
</td>
Javascript for Select 2
$("a[data-name='Cba']").editable({
showbuttons: 'false',
emptytext: 'None',
display: function(values) {
var html = [];
html.push(values);
$(this).html(html);
},
select2: {
multiple: true,
allowClear: true,
placeholder: "Select CBA(s)",
ajax: {
// url is copied from data-source via x-editable option-passing mechanism
dataType: 'json',
// pass the '?format=select2' parameter to API call for the select2-specific format
data: function(term, page) {
return {
deptId: departmentId,
format: 'select2'
};
},
// transform returned results into the format used by select2
results: function(data, page) {
return {
results: data
};
}
},
// what is shown in the list
formatResult: function(cba) {
return cba.text;
},
// what will appear in the selected tag box
formatSelection: function(cba) {
return cba.text;
},
// rendering id of the values to data.value requirement for Select 2
id: function(cba) {
return cba.value;
},
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
id: v,
text: v
};
});
callback(result);
}
}
});
Format in which Code is returned from the database:-
Facility.findOne({ _id: department.Facility }, function(err, facility) {
if (err) {
res.send(500, err);
} else if (!facility) {
res.send(404, 'Facility not found');
} else if (req.query.format && req.query.format === 'select2') {
var result = facility.Cba.map(function(c) {
return { value: c, text: c };
});
res.json(result);
}
});
Image showing an empty box added by itself
How Array looks after I edit
So it was just a simple syntax error, I was doing found out by myself,
I was returning cba.value as id, but the initSelection was returning
{id: v, text: v}
it should be value & text instead of id & text.
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
value: v,
text: v
};
});
callback(result);
}

Set value in Backbone.Form after fetch from the server

Hi I am newbie in Backbone and JS.
I need to fetch data from the server and put this value as the default to planProviderMode choice radio button. So i fetch the data in defaultMode variable. But the call is a asynchronous and I receive a value after the planProviderMode: defaultMode.value code has been executed.
var PlanProviderMode = Backbone.Model.extend({
url: '/rest/enrollment/step/plan-provider-mode'
});
var defaultMode = new PlanProviderMode;
defaultMode.fetch({
success: function() {
// recieve correct data
}
});
var formItems = new Backbone.Form({
template: tpl,
className: 'wizard-content',
schema: {
planProviderMode: {
template: formTpl,
type: 'Radio',
options: [
{
label: 'By Plan',
val: 'BY_PLAN',
custom: {
img: '../resources/img/by-plan.jpg'
}
},
{
label: 'By Provider',
val: 'BY_PROVIDER',
custom: {
img: '../resources/img/by-provider.jpg'
}
}
]
}
},
//here i put the default value
data: {
planProviderMode: defaultMode.value
}
});
How could I set the fetched value to the form.
Please let me know if the question is not described well. Thanks.
you should write such code in success callback function which is executed only after the fetch request is completed succesfully.
var PlanProviderMode = Backbone.Model.extend({
url: '/rest/enrollment/step/plan-provider-mode'
});
var defaultMode = new PlanProviderMode;
defaultMode.fetch({
success: function() {
// recieve correct data
//here you put the default value
data: {
planProviderMode: defaultMode.value
}
}
});
var formItems = new Backbone.Form({
template: tpl,
className: 'wizard-content',
schema: {
planProviderMode: {
template: formTpl,
type: 'Radio',
options: [
{
label: 'By Plan',
val: 'BY_PLAN',
custom: {
img: '../resources/img/by-plan.jpg'
}
},
{
label: 'By Provider',
val: 'BY_PROVIDER',
custom: {
img: '../resources/img/by-provider.jpg'
}
}
]
}
}
});
Backnone has a function called "parse" that helps you in this cases.
This function will always be called from backbone before the data from server populate the model.
Take a read in parse method.
There's a answer here.
how to override Backbone's parse function?
Hope it helps

selectize js use array as source

Hi I am getting back a JSON encoded array ("html") from my Ajax call that I would like to add in the selectize as both value and text (I am using a tag) .
How can I do that ?
HTML
<input type="text" value="test" class="demo-default selectized" id="input-tags" tabindex="-1" style="display: block;">
JQUERY
try {
data = $.parseJSON(html);
var obj = jQuery.parseJSON(html);
outcome = (obj.outcome);
$('#input-tags').selectize({
delimiter: ',',
persist: false,
maxItems: 1,
create: function (input) {
return {
value: input,
text: input
}
}
});
}
You could map the array onto an array of objects, like this:
data = $.parseJSON(html);
var items = data.map(function(x) { return { item: x }; });
Then use "labelField" and "valueField" to specify the text/value:
$('#input-tags').selectize({
delimiter: ',',
persist: false,
options: items,
labelField: "item",
valueField: "item"
});
Fiddle Demo.
With ES6 you can reduce your oneliner a bit
const items = data.map(item => ({item}));

Categories

Resources