Data from a single column of a sql view not displayed - php

I have a SQL view in phpmyadmin which has a is used to populate data in a table created using jquery jtable. The issue is quite bizarre as only one column's data which is being pulled by the view isn't being displayed and all of the others are being displayed without an issue. There is also no issue when I edit the fields and I can see the changes I made in phpmyadmin. How do I get the Successful column to display ? All help is greatly appreciated.
Screenshot of the table
js which handles creation of the table
function getLessonsLearnedResponseChildTable(ContainerID) {
var table = {
title: '',
width: '5%',
sorting: false,
edit: false,
create: false,
display: function(data) {
//create an image to be used to open child table
var $img = $('<img src="' + config.base_url + 'assets/images/expand_row-small.png" title="View Responses" style="height:30px;width:30px;cursor:pointer;" height="30" width="30"/>');
$img.click(function() {
$('#' + ContainerID).jtable('openChildTable',
$img.closest('tr'),
{
title: data.record.event,// + ' - Response Plans'
actions: {
listAction: config.base_url + "data_fetch/responses/" + data.record.risk_id,
deleteAction: config.base_url + 'data_fetch/delete_response/',
updateAction: config.base_url + 'data_fetch/edit_response/'
},
messages: defaultResponseMessages,
fields: LessonsLearnedResponseFields
}, function(data) {//opened handler
data.childTable.jtable('load');
});
});
//return image to show on row
return $img;
}
};
return table;
}
Controller method for the listAction:
function responses($risk_id = null, $offset = 0, $limit = 100, $order_by = 'response_id', $direction = 'ASC') {
$confirm_member = $this->User_model->confirm_member(true, false);
if (!$confirm_member['success']) {
$this->print_jtable_error(self::ERROR_NOT_LOGGED_IN);
return;
}
$user_id = $_SESSION['user_id'];
$this->load->model('Response_model');
$responses = $this->Response_model->get_all($risk_id, $user_id, $limit, $offset, $order_by, $direction);
if ($responses == false) {
$this->print_jtable_error(self::ERROR_NO_ACCESS_PERMISSION);
return;
} else {
return $this->print_jtable_result($responses);
}
}
get_all method in Response Model
/*
* Retrieves all responses associated with the risk
*/
public function get_all($risk_id, $user_id, $limit = null, $offset = 0, $order_by = null, $direction = 'ASC') {
//load risk model to check if user can read from project
$this->load->model('Risk_model');
if ($this->Risk_model->initialize($risk_id, $user_id) == false) {
return false;
}
if ($limit !== null && $limit != 0) {
$this->db->limit($limit, $offset);
}
if ($order_by !== null) {
$this->db->order_by($order_by, $direction);
}
$query = $this->db->select('SQL_CALC_FOUND_ROWS *', false)->from('view_responses')->where('risk_id', $risk_id)->get();
$data = $query->result_array();
$this->load->model('Task_model');
foreach ($data as &$response)
$response['WBS'] = $this->Task_model->normalize_WBS($response['WBS']);
$data['num_rows'] = $this->db->
query('SELECT FOUND_ROWS()', false)->row(0)->{'FOUND_ROWS()'};
return $data;
}
Screenshot of the sql view
successful is received but not displayed
http://imgur.com/MqCVAGm

I've been able to solve the problem. It was an issue with spelling. I had a missing c in successful coming from the SQL view and now its working fine.

Related

how to show array of parent and child Data as row in datatables

i am working in codeigniter and i need to show a list of destinations as row in datatables, like UK as Parent and London as Child destination.
i need to show them in datatable, i have created array of both parent and child data, but i am not able to understand, how to show them in datatable properly as each child destination row below their parent row.
something like wordpress parent and child category.
here is what i did as of now.
here is my controller
public function fetch_destinations(){
// POST data
$postData = $this->input->post();
// Get data
$data = $this->tourismo->fetch_dest_nested($postData);
echo json_encode($data);
}
this is my model
function fetch_dest_nested($postData=null)
{
$response = array();
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$search_arr = array();
$searchQuery = "";
if($searchValue != ''){
$search_arr[] = " (name like '%".$searchValue."%' ) ";
}
if(count($search_arr) > 0){
$searchQuery = implode(" and ",$search_arr);
}
## Total number of records without filtering
$this->db->set_dbprefix('');
$this->db->select('count(*) as allcount');
$records = $this->db->get('destinations')->result();
$totalRecords = $records[0]->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchQuery != '')
$this->db->where($searchQuery);
$records = $this->db->get('destinations')->result();
$totalRecordwithFilter = $records[0]->allcount;
//fetch records
$this->db->select("*");
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->where('level', 1);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$this->db->from("destinations");
$q = $this->db->get();
$final = array();
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$this->db->select("*");
$this->db->from("destinations");
$this->db->where("parentid", $row->id);
$q = $this->db->get();
if ($q->num_rows() > 0) {
$row->children = $q->result();
}
array_push($final, $row);
}
}
$data = array();
foreach($final as $parentdest){
$data[] = array(
"id"=>$parentdest->id,
"name"=>$parentdest->name,
"slug"=>$parentdest->slug
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
return $response;
}
this is my view
<table class="apitable table dt-table" id="destlist_table">
<thead>
<th>
Destination Id</th>
<th>Destination Name</th>
<th>Destination Slug</th>
</thead>
</table>
here is my jquery code for ajax request
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<!-- Script -->
<script type="text/javascript">
$(document).ready(function(){
var destlistDataTable = $('#destlist_table').DataTable({
'bDestroy': true,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
"searching": true,
"pageLength": 10,
"order":[[0,'desc']],
'ajax': {
'url':'<?php echo admin_url('tourismo/tourismo/fetch_destinations'); ?>',
'data': function(data){
}
},
'columns': [
{ data: 'id' },
{ data: 'name' },
{ data: 'slug' },
]
});
});
what i want is every child destination row should be just below its Parent destination row, i am just not able to understand how to work with this loop here.
this is the reference for what i want

vTiger Custom Field Validation beforesave

I have created a custom module on vTiger 6.5.
I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.
Please see my code below. Thanks!
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {}
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave.final') {}
if($eventName == 'vtiger.entity.aftersave') {
}
}
}
}
?>
After doing some searching around and looking at other peoples event handlers I managed to solve this by changing:
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
to
if($eventName == 'vtiger.entity.beforesave') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
Now I want to see if I can display the message and then give a link to go back to the entity module with all the fields still full.
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database
Here is an example:
In your Edit.js:
donCache : {},
checkDon : function(details) {
// alert("checkOverlap");
var aDeferred = jQuery.Deferred();
var params = {
'module' : 'Affectations',
'action' : "checkAffectAmount",
'mode': 'CtrlAffectAmount',
'recordId' : details.don,
'montant' : details.montant
}
AppConnector.request(params).then(
function(data) {
if (data.success == true) {
// console.log(data.result);
var statut = data.result.statut;
var reste = data.result.reste;
if(statut == "error"){
aDeferred.reject(data);
}else {
aDeferred.resolve(data);
}
}
},
function(error,err){
aDeferred.reject();
}
);
return aDeferred.promise();
},
registerRecordPreSaveEvent : function(form) {
var thisInstance = this;
if (typeof form == 'undefined') {
form = this.getForm();
}
form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
var check = false;
var recordId = jQuery('input[name="record"]').val();
if (!recordId || recordId) {
var montant_affectation = jQuery("input[name='affectations_montant']").val();
var don_id = jQuery("input[name='affectations_potentialid']").val();
var params = {};
if (!(check in thisInstance.donCache)) {
thisInstance.checkDon({
'montant' : montant_affectation,
'don': don_id
}).then(
function(data){
thisInstance.donCache[check] = data['success'];
form.submit();
},
function(data, err){
thisInstance.donCache[check] = data['success'];
var reste = data.result.reste;
var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure de ")+ reste +app.vtranslate(" Euros au montant du don");
Vtiger_Helper_Js.showPnotify(msg);
delete thisInstance.donCache[check];
}
);
} else {
delete thisInstance.donCache[check];
return true;
}
e.preventDefault();
}
})
},
The PHP part in modules/isa/actions:
<?php
/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/
class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {
function __construct() {
$this->exposeMethod('CtrlAffectAmount');
}
public function checkPermission(Vtiger_Request $request) {
$moduleName = $request->getModule();
$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
$permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());
if(!$permission) {
throw new AppException('LBL_PERMISSION_DENIED');
}
}
public function process(Vtiger_Request $request) {
$mode = $request->getMode();
if(!empty($mode) && $this->isMethodExposed($mode)) {
$this->invokeExposedMethod($mode, $request);
return;
}
}
function CtrlAffectAmount(Vtiger_Request $request){
global $adb,$log;
$log->debug("ALTAIR CtrlAffectAmount OK");
$recordId = $request->get('recordId');
$montant = $request->get('montant');
// $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
$query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
$sommeAffectation = $adb->query_result($query,0,"sommeaffectation");
$query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
$montantDon = $adb->query_result($query,0,"amount");
if ( ($sommeAffectation + $montant) == $montantDon) {
$statut = "ok";
$reste = "";
} else if( ($sommeAffectation + $montant) > $montantDon) {
$statut = "error";
$reste = ($sommeAffectation + $montant) - $montantDon;
}
$value = array('statut'=>$statut, 'reste'=>$reste);
$response = new Vtiger_Response();
$response->setEmitType(Vtiger_Response::$EMIT_JSON);
$response->setResult($value);
$response->emit();
}
}
Oh. you have 1 invalid error here. please change:
if($eventName == 'vtiger.entity.beforesave') {
$currentAmount = $entityData->get('currentamount');
if($currentAmount > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}

I want to delete the selected record from database

I have two form views: form and controller.
Below are the codes which I want to delete the selected record from database using codeginiter.
Please check why code.controller form is not working.
view Form
function deleteCustEntry(id){
var answer = confirm("Are you sure you want to move in trash?")
if (answer){
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>manager/deletecust/',
data: { manager_id: id, status : 'trash'},
}
}
Controller form
public function deletecust() {
$manager_id = $this->input->post('manager_id');
$status = $this->input->post('status');
$result = 0;
if($status == 'trash') {
$data = array(
'isTrash' => 1
);
$this->db->where('id', $manager_id);
$this->db->update('manager', $data);
$result = 1;
} elseif ($status == 'delete'){
$this->db->delete('manager', array('id' => $manager_id));
if ($this->db->affected_rows() > 0) {
$result = 1;
}
}
echo $result;
flush();
}
do you want to delete the record from the table or change the status of the record. As status : 'trash' this will always change the status of isTrash. Provide more info.

Making simple allowed array in PHP? (CodeIgniter)

I have some simple function to collect allowed array, but something is not ok, can somebody help me? Here is my code
public function getAllbyLink($table, $what, $url)
{
$link=mysql_real_escape_string($url);
$query = $this->db->query("SELECT * FROM ".$table." WHERE ".$what." = '{$link}' LIMIT 0 , 1");
if ($query->num_rows() > 0)
{
return $query->result();
}
else redirect('');
}
Please read something about MVC pattern, question is clearly pointed on how to write a Model.
consider using this function
public function getTable($table, $where = array(), $select = '*', $order_by = '', $limit = '', $offset = '') {
if ($order_by !== '' && $order_by != 'RANDOM') $this->db->order_by($order_by);
if ($order_by == 'RANDOM') $this->db->order_by('id', 'RANDOM');
if ($limit !== '') $this->db->limit($limit, $offset);
$this->db->select($select);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
for your purpose call the function like this:
getTable($talbe, array('what' => $link));
//returns FALSE if no data are selected,
//or returns object with data,
if you wish return array instead replace $q->result() with $q->array_result()
Please note that active record auto escapes.
After comments:
comment-1, you can simplify that function easily just delete what you do not need, for example
public function getTable2($table, $where = array(), $limit = '', $offset = '') {
if ($limit !== '') $this->db->limit($limit, $offset);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
comment-2,when there is no data use this if-else statement
if (!$my_data = getTable2('table', array('where' => $link))) {
//there is some DATA to work with
echo "<pre>";
var_dump($my_data);
echo "</pre>";
} else {
//no DATA do redirect or tell user that there is no DATA
redirect(); //redirect to default_controller
}
comment-3, no comment;
comment-4, It also allows for safer queries, since the values are escaped automatically by the system. from this source. And another SO question about active record providing exact answer you are seeking.
My understanding of your code is:
Read all rows from table
Check if linkurl is in the list
If so, return a random row for that value
Else, redirect.
In this case, try this:
public function getAllbyLink($table,$url,$what)
{
$query = $this->db->query("
SELECT *
FROM `".$table."`
WHERE `".$what."` = '".mysql_real_escape_string($linkurl)."'
ORDER BY RAND()
LIMIT 1
");
if( !$query) return redirect('');
$result = $query->result();
if( !$result) return redirect('');
return $result;
}

jqgrid and server side pagination

I realize there are some related questions but I couldn't find what I was looking for. I used jqgrid many times in the past but forgot how to achieve server side pagination.
here is my javascript
$("#list").jqGrid({
url: "index.php?loadData=test",
datatype: "json",
mtype: "GET",
colNames: ["id", "eNodeB_unique", "enodeB_type", "radio_freq_mod", "macroEnbId_dec representation", "num_cells"],
colModel: [
{ name: "id", width: 55 },
{ name: "enodeB_unique", width: 90 },
{ name: "enodeB_type", width: 80, align: "right" },
{ name: "radio_freq_mod", width: 80, align: "right" },
{ name: "macroEnbId_dec_rep", width: 80, align: "right" },
{ name: "num_cells", width: 150, sortable: false }
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "id",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid",
loadonce:false
});
and my server side code
public function getData($page, $limit, $sidx, $sord){
$query_str = "SELECT COUNT(*) AS count FROM tbl";
$prepState = $this->DBi->prepare($query_str);
$result = $this->DBi->query($prepState);
$count = $result[0]['count'];
if( $count > 0 && $limit > 0) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){
$page = $total_pages;
}
$start = $limit * $page - $limit;
if($start < 0){
$start = 0;
}
$query_str = "SELECT * FROM tbl ORDER BY {$sidx} {$sord} LIMIT {$start}, {$limit}";
$prepState = $this->DBi->prepare($query_str);
$result = $this->DBi->query($prepState);
return $result;
}
if I keep $start and $limit in the query then i just get the inital ten results. If I take those out... then my grid shows all my results.. but there is only one page available. I have on option to click on the next page.
EDIT:
okay I realize now that I have to return this information.. I'm puzzled by the way I have to return the rows. Was JQgrid always this way?
$query_str = "SELECT * FROM enodeB ORDER BY {$sidx} {$sord} LIMIT {$start}, {$limit}";
$prepState = $this->DBi->prepare($query_str);
$result = $this->DBi->query($prepState);
$finalRows = array();
foreach($result as $row){
$finalRows[] = array('cell'=> $row);
}
return array('page' => $page, 'total' => $total_pages, 'records' => $count, 'rows' => $finalRows);
public static dynamic ToJson<T>(this IEnumerable<T> Collection, string sidx, string sord, string page, string rows, List<string> Columns)
{
return ToJson<T>(sidx, sord, page, rows, Collection, Columns);
}
private static dynamic ToJson<T>(string sidx, string sord, string page, string rows, IEnumerable<T> Collection, List<string> Columns)
{
page = page.NotNull("1"); rows = rows.NotNull("100"); sidx = sidx.NotNull("Id"); sord = sord.NotNull("asc");
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = Convert.ToInt32(rows);
int totalRecords = Collection.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
if (!Collection.IsNull())
{
Collection = Collection.ToList().OrderWith(x => x.GetPropertyValue(sidx), sord).Skip(pageSize * pageIndex).Take(pageSize);
return JsonData<T>(Collection, totalPages, page, totalRecords, Columns);
}
return BlankJson();
}
private static dynamic JsonData<T>(IEnumerable<T> collection, int totalPages, string page, int totalRecords, List<string> Columns)
{
var colsExpr = Columns.ConvertAll<PropertyInfo>(x => Extentions.GetProperty<T>(x));
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = collection.Select(row => new { id = row.GetPropertyValue("Id") ?? Guid.NewGuid(), cell = GetValues<T>(colsExpr, row) }),
};
return jsonData;
}
public static dynamic BlankJson()
{
return new
{
total = 0,
page = 0,
records = 0,
rows = "",
};
}
private static string[] GetValues<T>(List<PropertyInfo> columns, T obj)
{
var values = new List<string>();
try
{
foreach (var x in columns)
{
var temp = x.GetValue(obj, null);
values.Add(temp != null ? temp.ToString() : string.Empty);
}
return values.ToArray();
}
catch
{
return values.ToArray();
}
}

Categories