Select2 optgroup format using PHP - javascript

I've got an ajax call that get dynamic data and places them in select2 as follow :
$.ajax({
type: 'get',
url: '/api/?stuff='+c,
dataType: "json",
success: function (response) {
// If select2 is already defined, we destroy it and rebuild it with the new data
if(typeof $(".select2edit").data('select2') !== 'undefined') {
$(".select2edit").select2('destroy').select2({ data: response, width: '100%', closeOnSelect: false });
} else {
$(".select2edit").select2({ data: response, width: '100%', closeOnSelect: false });
}
}
});
I create the response using PHP and then transform it to JSON before sending it :
$old_emplacement = '';
$results = array();
$i = -1;
while($array_campaign = tep_db_fetch_array($campaign)){
if ($array_campaign['name'] != $old_emplacement) {
$i++;
$results['results'][$i]['text'] = $array_campaign['name'];
$old_emplacement = $array_campaign['name'];
$c = 0;
}
$results['results'][$i]['children'][$c]['id'] = $array_campaign['id'];
$results['results'][$i]['children'][$c]['text'] = $array_campaign['c_name'];
$c++;
}
$results['pagination']["more"] = true;
Thus resulting in the following JSON format :
{
"results": [
{
"text": "Name 1",
"children" : [
{
"id": 1,
"text": "Text 1.1"
},
{
"id": 2,
"text": "Text 1.2"
}
]
},
{
"text": "Name 2",
"children" : [
{
"id": 1,
"text": "Text 2.1"
},
{
"id": 2,
"text": "Text 2.2"
}
]
}
],
"paginate": {
"more": true
}
}
I get a No results found. when select2 initializes and loads. And I have no idea why. It's the correct format as far as the documentation is saying and other questions seem to confirm. Any ideas where could the problem be coming from?
It's also good to note that my select2 is inside a form which is inside a modal, and this is it's html :
<select name="xx[]" id="edit-xx" name='xx' class="form-control select2edit" multiple>
</select>

The problem was with the format generated by my PHP code. I'm posting the result here for anyone trying to generate a select2 optgroup format using PHP and for my own reference :
$old_emplacement = '';
$results = array();
$i = -1;
while($array_campaign = tep_db_fetch_array($campaign)){
if ($array_campaign['name'] != $old_emplacement) {
$i++;
$results[$i]['text'] = $array_campaign['name'];
$old_emplacement = $array_campaign['name'];
$c = 0;
}
$results[$i]['children'][$c]['id'] = $array_campaign['id'];
$results[$i]['children'][$c]['text'] = $array_campaign['c_name'];
if(in_array($array_campaign['id'], $campaigns_array)) {
$results[$i]['children'][$c]['selected'] = true;
}
$c++;
}

Related

What is the best way to extract all rows from Datatables under a criteria in Javascript

I'm currently working on a condominum program. The goal of this issue is when one Apartment row is clicked on the Parent table all the months - related to that apartment - must be displayed on the Child table.
The click/select/deselect is working fine but I can not obtain all the twelfth months.
This is my actual tables layout (example 1):
And this is my actual tables layout (example 2):
My code to childTable is:
var childTable = $('#child').DataTable( {
"pageLength": 12,
ajax: {
url: "ajax/query_pagquotas.php", // This is the URL to the server script for the child data
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var rows = data.data[i];
if (rows.ID === ID) {
return [rows];
}
}
} else {
return [];
}
}
},
columns: [
{ "data": "ID" },
{ "data": "DATA" },
{ "data": "MES" },
{ "data": "VALOR" },
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
Thanks for your help Masters
[edited]
Ups! If condition at the end does not make the 'deselect' work...
This is my full code at the moment:
$(document).ready(function() {
var parentTable = $('#parent').DataTable( {
ajax: "ajax/dbfraccoes.php",
"language": {
"sSearchPlaceholder": "Apto ou Proprietário...",
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Portuguese.json",
},
"processing": true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
pageLength: 5,
select: {
style: 'single'
},
columns: [
{ "data": "ID","searchable": false },
{ "data": "APTO" },
{ "data": "FRACCAO"},
{ "data": "PROPRIETARIO" },
{ "data": "VALOR_QUOTA","searchable": false, className: "cssValores"},
{ "data": "OBS" }
]
} );
// tabela Child ------------------------------------------
var childTable = $('#child').DataTable( {
columnDefs: [{
targets: 6,
render: function(data, type, row, meta){
if(type === 'display' && data === 'EMITIDO'){
data = '<td style="text-align:center"><button type="button" class="btn btn-info btn-sm cssButton center" title="Emitido Aviso de Recibo a pagamento">EMITIDO</button></td>'+
'<div class="links">' +
'Editar ' +
'</div>';
}else if (type === 'display' && data === 'AGUARDA'){
data = '<td style="text-align:center"><button type="button" class="btn btn-warning btn-sm cssButton center" title="Limite de pagamento ultrapassado. Em período de tolerância.">AGUARDA</button></td>'+
'<div class="links">' +
'<a href="<?php echo WEB_URL;?>credit_debit/gest_quotas.php?spid='+
row['pqid']+'#insert">Editar</a> ' +
'</div>';
}
return data;
}
}],
"paging": false,
"searching": false,
"language": {
"zeroRecords": "<center>Clique na tabela acima, na linha do apartamento que pretende. <br/>Os dados da fracção/apartamento selecionado acima serão reflectidos nesta tabela</center>",
},
ajax: {
url: "ajax/query_pagquotas.php",
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var rows = []; // create an empty array
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i];
if (row.ID === ID) {
rows.push(row);
}
}
}
return rows;
},
},
columns: [
{ "data": "pqid" },
{ "data": "ID"},
{ "data": "DATA" },
{ "data": "MES"},
{ "data": "VALOR", className: "cssValores"},
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
// This will load the child table with the corresponding data
parentTable.on( 'select', function () {
childTable.ajax.reload();
} );
//clear the child table
parentTable.on( 'deselect', function () {
childTable.ajax.reload();
} );
} );
The simplest way to adjust your existing code, is to change the logic in your dataSrc: function (data) {...}.
At the moment, you are only creating an array of one item.
So, instead you can do this:
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
var rows = []; // create an empty array
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i]; // change the variable name to "row"
if (row.ID === ID) {
rows.push(row); // add the new row to your array of rows
}
}
}
return rows; // return your array of rows
}
The most important line here is: rows.push(row); which is how JavaScript adds a new item to the end of an array.
So, now at the end of your dataSrc function you will either have an empty array [] if no rows were selected, or you will have an array of rows which match your ID.
That should solve your current problem.
The above approach should work - but it involves fetching every child row, every time - and then filtering out the ones you do not want to show.
You can probably improve on this by submitting the ID of the selected row as part of the child table's ajax URL. You can move the relevant code from its current location into your parentTable's on(select) function:
var selectedID = -1
parentTable.on( 'select', function () {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
selectedID = selected.data().ID;
}
childTable.ajax.reload();
} );
I do not know how you have implemented your ajax/query_pagquotas.php, so I am not sure of the best way to pass the selectedID parameter to it.
Normally I would append it as a query parameter in your ajax parameters:
data: 'id=' + selectedID
You may already know how to do this yourself.
Once you have passed the selectedID to your PHP, then you can use it to return only the records you want to display - and you can remove all of the existing dataSrc: function (data) {...} logic from your child table definition.

jQuery Datatables populate search data

On document.ready, my Datatable loads accordingly.
What I need to do is build a feature that reloads the Datatable if the user conducts a search.
So the Datatable loads like this:
$(document).ready(function()
{
$('#searchSubmit').on('click', function() // used for searching
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
var searchtli = $('#searchtli').val();
if(searchbooking == "" && searchquote == "" && searchtli == "")
{
$('.message').text('You did not enter any search criteria.');
return false; // making sure they enter something
}
else
{
$.post('api/searchAll.php', {searchbooking:searchbooking, searchquote:searchquote, searchtli:searchtli}, function(data)
{
// what do i do here???
// how do I get the return results to load
});
}
});
// if the user does not enter any search parameters, load everything
$('#example1').DataTable({
"ajax": {
"url": "api/displayQnams.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
// and so on
});
});
As you will see in the above code, when the document is ready, if the user does not conduct a search, I load all of the data from the process called 'displayQnams.php'.
But if the user conducts a search, the parameters are sent to another process called 'qnamsSearch.php'.
How do I reload the datatable with the search results from 'qnamsSearch.php'?
I tried to create a variable from inside the post:
var dataUrl = data;
And I tried to call that variable in the ajax call:
"ajax": {
"url": dataUrl,
"type": "POST",
"dataSrc": ''
}
But the Datatable will not display anything and there are no console errors.
How can I make this work?
You can try using this.
After user click search button, below is the flow:
Clear datatables - datatables clear()
Add new data to the table - datatables rows.add()
Adjust column size (optional) - datatables adjust.columns()
Redraw back datatable with new data - datatables draw()
$(document).ready(function(){
var datatable = $('#example1').DataTable({
"ajax": {
"url": "api/displayQnams.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]]
});
$('#searchSubmit').on('click', function(){
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
var searchtli = $('#searchtli').val();
if(searchbooking == "" && searchquote == "" && searchtli == ""){
$('.message').text('You did not enter any search criteria.');
return false; // making sure they enter something
} else {
$.post(
'api/searchAll.php',
{ searchbooking:searchbooking, searchquote:searchquote, searchtli:searchtli },
function(data) {
var newData = data;
datatable.clear().draw();
datatable.rows.add(newData); // Add new data
datatable.columns.adjust().draw(); // Redraw the DataTable
});
}
});
});

How to get TItles of multiple People Or Group column's in list using REST API

I am new in sharepoint. I am using Sharepoint 2013.
I want to retrieve name and email id in People Or Group column using REST API.
My list contains two such columns. Please help me to retrieve title and email ids of both the columns
How to retrieve user field value using SharePoint REST
Using $expand OData operator you can specify that the request returns projected fields from User Information List list for user field.
ListItem resource endpoint: https://[site]/_api/web/lists/getbytitle('<list title>')/items(<item id>)?$select=<user field name>/Name,<user field name>/EMail&$expand=<user field name>
Examples
Assume a Tasks List that contains AssignedTo (multi-valued) and Author (single-valued) user fields.
The first example demonstrates how to retrieve AssignedTo column user details:
/_api/web/lists/getbytitle('Tasks')/items(1)?$select=AssignedTo/Name,AssignedTo/EMail&$expand=AssignedTo
returns Name and Title for AssigntedTo column:
{
"d": {
"__metadata": {
"id": "764f494a-7186-4b83-9db0-2bcf1a0930a5",
"uri": "https://contoso.sharepoint.com/_api/Web/Lists(guid'71284427-d86e-424f-ae07-2e0c53b9ac4a')/Items(1)",
"etag": "\"3\"",
"type": "SP.Data.TasksListItem"
},
"AssignedTo": {
"results": [
{
"__metadata": {
"id": "a06b28ff-9356-4aa9-8f38-f75107058fd2",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
}
]
}
}
}
The following example demonstrates how to retrieve Author and AssignedTo user field user values:
Endpoint Url: /_api/web/lists/getbytitle('Tasks')/items(1)?$select=Author/Name,Author/EMail,AssignedTo/Name,AssignedTo/EMail&$expand=AssignedTo,Author
Result:
{
"d": {
"__metadata": {
"id": "e29690e4-3813-44ce-a828-160ad072666d",
"uri": "https://contoso.sharepoint.com/_api/Web/Lists(guid'71284427-d86e-424f-ae07-2e0c53b9ac4a')/Items(1)",
"etag": "\"3\"",
"type": "SP.Data.TasksListItem"
},
"Author": {
"__metadata": {
"id": "6dc8fe57-1865-464f-aaa3-f7b8bb555f20",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
},
"AssignedTo": {
"results": [
{
"__metadata": {
"id": "b9a1d6f8-4bec-4ec8-b940-fdaeac2eff37",
"type": "SP.Data.UserInfoItem"
},
"Name": "i:0#.f|membership|username#contoso.onmicrosoft.com",
"EMail": "username#contoso.onmicrosoft.com"
}
]
}
}
}
JavaScript example
function getItemDetails(webUrl,listTitle,itemId,selectFields, expandFields){
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")";
endpointUrl+= '?$select=' + selectFields.join(",");
endpointUrl+= '&$expand=' + expandFields.join(",");
return executeRequest(endpointUrl,'GET');
}
function executeRequest(url,method,headers,payload)
{
if (typeof headers == 'undefined'){
headers = {};
}
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var selectFields = ['Author/Name','Author/EMail','AssignedTo/Name','AssignedTo/EMail'];
var expandFields = ['Author','AssignedTo'];
getItemDetails(webUrl,'Tasks',2,selectFields,expandFields)
.done(function(data){
//print MULTI-valued user field: AssignedTo
console.log('AssignedTo user field value:')
for(var i = 0; i< data.d.AssignedTo.results.length;i++) {
console.log(data.d.AssignedTo.results[i].EMail);
console.log(data.d.AssignedTo.results[i].Name);
}
//print SINGLE-valued user field: Author
console.log('Author user field value:')
console.log(data.d.Author.EMail);
console.log(data.d.Author.Name);
});

Post row datas from DataTable to an Ajax Form

I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)

Save created row in datatable editor via php

I using datatable editor to display rows
This is the code i'm using
var editor;
$(document).ready( function () {
editor = new $.fn.dataTable.Editor( {
"ajaxUrl": {
"create": "admin/save",
},
"domTable": "#example",
"fields": [ {
"label": "username:",
"name": "username"
}, {
"label": "password:",
"name": "password",
"type":"password"
}, {
"label": "fname:",
"name": "fname"
}, {
"label": "lname:",
"name": "lname"
}, {
"label": "email:",
"name": "email"
},{
"label": "address:",
"name": "address"
}
]
} );
$('#example').dataTable( {
"sDom": "Tfrtip",
"aoColumns": [
{ "mData": "username"},
{ "mData": "password" },
{ "mData": "fname" },
{ "mData": "lname" },
{ "mData": "email" },
{ "mData": "address" }
],
"oTableTools": {
"sRowSelect": "single",
"aButtons": [
{ "sExtends": "editor_create", "editor": editor },
{ "sExtends": "editor_edit", "editor": editor },
{ "sExtends": "editor_remove", "editor": editor }
]
}
} );
} );
How can I pass the form data to controller page.I also given name field but it is not added to element.
create : admin/save
Here admin is the controller name and save is the action name.
Please help me.
Using Datatables with the Editor extension, it sends data to the server to be processed. The client sends three fields: action, id and data. The action can be create, edit or delete. The id is only filled in for edit.
So in short, you can use this controller:
<?php
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
class DatatablesController extends AbstractActionController
{
public function saveAction()
{
if (!$this->getRequest()->isPost()) {
$response = $this->getResponse();
$response->setStatusCode(405); // Method not allowed
return $response;
}
$action = $this->params()->fromPost('action', null);
$data = array();
switch ($action) {
case 'create':
$data = $this->createRow();
break;
case 'edit':
$data = $this->editRow();
break;
case 'delete':
$data = $this->deleteRow();
break;
default:
$response = $this->getResponse();
$response->setStatusCode(422); // Unprocessable entity
return $response;
}
$model = new JsonModel($data);
return $model;
}
protected function createRow()
{
$data = $this->params()->fromPost('data', array());
// Create a new entity with $data
// Return the properties from the new entity
return array();
}
protected function editRow()
{
$id = $this->params()->fromPost('id');
$data = $this->params()->fromPost('data', array());
// Fetch the entity with id $id
// Update the entity with $data
// Return the properties from the entity
return array();
}
protected function deleteRow()
{
$ids = $this->params()->fromPost('data', array());
// Remove all entities with an id in the array $ids
}
}

Categories