How to generate an excel file using js - javascript

I have a UI that shows a CRUD(create, read, update and delete) account of an employee. Now, I want to add a generate button that when its click, a window will pop-up that will show and ask if the following data in the grid lines under the UI are to be open or saved using the excel report.Also, I have already EXcelPhp library.
Here's my code for my 'actions.class.php':
public function executeLoadEmployeeList(sfWebRequest $request)
{
// $start = $request->getParameter('start') ? $request->getParameter('start'): 2;
// $limit = $request->getParameter('limit') ? $request->getParameter('limit'): 2;
$query = pg_escape_string($request->getParameter('query'));
$start = $request->getParameter('start');
$limit = $request->getParameter('limit');
if(isset($limit))
{
$page = $start / $limit;
$page ++;
}
else
$page = 1;
$criteria = Doctrine_Query::create();//what is the query?? is it select,inset,update,delete?
$criteria->select("(fname || ' ' || lname) AS fullname, department");
$criteria->from('Employees'); // Select * from profile
$criteria->orderBy('id'); // order by id
//print $criteria->getSqlQuery();
//die();
if($query!=null)
{
$criteria->where("(fname ilike '%$query%' or lname ilike '%$query%' or department ilike '%$query%')"); //where (uname ilike '%$query%' or status ilike '%$query%')
}
$allData = $criteria->fetchArray();
// print "<pre>";
// print_r($allData);
// die();
$this->pager = new sfDoctrinePager('Employees', 20); //what is sfdoctrine about? dont mind this.. this is a symphony built in class for pager
$this->pager->setQuery($criteria);
$this->pager->setPage($page);
$this->pager->init();//What is the purpose of this line? //initialize sfDoctrinePager
$result['data'] = $this->pager->getResults();
$result['totalCount'] = count($allData);
$result['limit'] = $limit;
$result['page'] = $page;
$result['query'] = $query;
die(json_encode($result));
}
public function executeAddEmployee(sfWebRequest $request)
{
try{
$fname = $request->getParameter('fname');
$lname = $request->getParameter('lname');
$department = $request->getParameter('department');
$Employee = new Employees();
$Employee->fname = $fname;
$Employee->lname = $lname;
$Employee->department = $department;
//save the data to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Added.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeDeleteEmployee(sfWebRequest $request)
{
try{
//what is Doctrine::getTable's purpose // to get the table profile
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', $request->getParameter('id')));
$Employee->delete();
$data = array("success"=> true, "data"=>"Employee record is Deleted.");
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeEditEmployee(sfWebRequest $request)
{
try{
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', array($request->getParameter('id'))));
$criteria = Doctrine_Query::create();
$criteria->select('fname,lname,department');
$criteria->from('Employees');
$criteria->where('id = ?', $request->getParameter('id'));//('id = ?', $request->getParameter('id') means... id = $request->getParameter('id')
$result = $criteria->fetchArray();
$record['fname'] = $Employee['fname'];
$record['lname'] = $Employee['lname'];
$record['department'] = $Employee['department'];
$data = array("success"=> true, "data"=>$record);
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeUpdateEmployee(sfWebRequest $request)
{
try{
$Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id')));
$Employee->fname = $request->getParameter('fname');
$Employee->lname = $request->getParameter('lname');
$Employee->department = $request->getParameter('department');
//save the update to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Successfully Updated.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeGenerateEmployee(sfWebRequest $request)
{
// ...
}**
What I've tried so far is setting only the generate button and there's no action yet. This is under my try.js:
var generateItem = new Ext.Action ({
text: 'Generate Excel Report',
width: 60,
enabled: true,
});
Could someone help me regarding this issue?

You can not generate an excel file without using a server side language / script. You can just prepare how it Will look and add some functions to make it functional like write, delete etc.

You can generate an Excel spreadsheet without any server side processing however you'll have a hellish time with browser support.
In theory you could generate an excel formatted file in js then simply do a window.open with the data URI.
for example here's a javascript generated image:
window.open('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC');
however.. it'll probably not be supported in most of the browsers for Excel data URIs:
here's another similar question:
Data URI used to export to CSV/Excel (no server-side request) : browser support/limitations?

Related

Integrate 2 functions for 1 button and keep input fields disabled after reload

A) I would like to have 2 different functions for 1 button.
For first click function 1 should start, for second click function 2, for third click function 1, fourth click function 2 ...
For now I need 2 buttons, one disables and the other one enables the possibility to input data in a form field. The best would be to have both functions for 1 button (as explained above).
Does anyone has an idea how to do that?
B) All data get saved and can be reopened in the datamanagementsystem. I would like that disabled fields stay disabled (after reopening the form again) for input. Is there a possibility to do so?
<script>
var nav = false;
function disable18() {
document.getElementById("field1").style.color = "red";
document.getElementById("field1").value = "X";;
document.getElementById("field1").disabled = true;
nav = true;
}
function enable18() {
document.getElementById("field1").disabled = false;
document.getElementById("field1").value = "";
document.getElementById("field1").style.color = "black";
nav = false;
}
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
</script>
How I get the data from database:
<?php
session_start();
require_once 'sc/functions.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
// php search data in mysql database using PDO
// set data in input text
$user = "xxx";
$pass = "xxxx";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO('mysql:host=localhost;dbname=xxx;charset=utf8', $user, $pass); //mysql:host=localhost;dbname=test_db","root","")
$pdoConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$ID = $_POST['ID'];
// mysql search query
$pdoQuery = "SELECT * FROM dabase WHERE ID = :ID";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your ID to the query ID
$pdoExec = $pdoResult->execute(array(":ID"=>$ID));
if($pdoExec)
{
// if ID exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$ID = $row['ID'];
$field1 = $row['field1'];
}
}
// if the id not exist
// show a message and clear inputs
else{
header( "Location: nodatasearch.php" ); die;
}
}else{
echo 'ERROR Data Not Inserted';
}
} ?>
Submitting/Saving data:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require("php/tc.php");
$ID = $_POST['ID'];
$field1 = $_POST['field1'];
$sql = "UPDATE pdbase SET
field1 = :field1
WHERE ID = :ID";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ID', $ID);
$stmt->bindValue(':field1', $field1);
$stmt->execute();
// var_dump($_POST['user']);
?>
My asnwer will solve problem A however problem B is a little more complicated. You will need a flag for this, for example this is your html
<input type="text" id="field1">
<button id="toggler" class="btn btn-success" onclick="toggleNav()">Toggler</button>
in your js start off with creating your flag, let's set it to false
var nav = false;
When your 1st function is called change your flag to true
function disable18() {
document.getElementById("field1").disabled = true;
nav = true;
}
Now for the second function we will set it back to false
function enable18() {
document.getElementById("field1").disabled = false;
nav = false;
}
Now we create the function that toogles between the 2 of them
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
After that, all that's left is make sure your toggleNav() function is in the onclick() in your button. Now for problem B I have more questions than answers. Need more details about how do you want to do achieve that

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

Using AJAX for query to MySQL database

I'm using the JavaScript function setInterval every 30 seconds to check the MySQL table with AJAX. Using AJAX it updates the page with new results without reloading the page.
I would like to use the effect highlight to colour certain records, in the example below this highlights ID 1 and 10:
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
I would like to highlight all new records that have been added since the last load.
index.php
// Run polling function every 60 seconds
var myVar = setInterval(myfunction, 30000);
// Load data from check_status page
function myfunction() {
$.ajax({
url: "check_status.php", success: function(result2) {
$("#div2").html(result2);
$("#title").html("Food Items AUTO Poll");
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
}
});
}
check_status.php
// Include and create instance of db class
require_once 'DB.class.php';
$db = new DB();
<?php
// Fetch all items from database
$data = $db->getRows();
if (!empty($data)) {
foreach ($data as $row) {
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<a href="javascript:void(0);" style="float:none;" class="image_link">
<?php echo $row['name']; ?>
</a>
</li>
<?php
}
}
?>
DB.class.php
<?php
class DB {
// Database configuration
private $dbHost = "###";
private $dbUsername = "###";
private $dbPassword = "###";
private $dbName = "###";
private $itemTbl = "###";
function __construct() {
if (!isset($this->db)) {
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if ($conn->connect_error) {
die("Failed to connect with MySQL: " . $conn->connect_error);
} else {
$this->db = $conn;
}
}
}
// Get rows from data table
function getRows() {
$query = $this->db->query("SELECT * FROM ".$this->itemTbl." ORDER BY img_order ASC");
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
$result[] = $row;
}
} else {
$result = FALSE;
}
return $result;
}
send ajax request to server each some second
respond json-formatted data, not html from your server controller
if this is first request, save it into "current" and "previous" variables
if this is not first request, save it into "current" variable
Display your data in your html page. During this operation compare "current" and "previous" variables, if something new in "current" highlight it
before next request to server, make assignment: previous = current
profit
Try to search and read something like "create REST service php". You should get main idea of such approach. Generally, your code should look like this:
php.php
<?php
$yourDatabaseClass = new YourDatabaseClass("localhost", "username", "password", "database");
$data = $yourDatabaseClass->getTable("select * from table");
echo json_encode($data);
Your js:
var oldData = [];
var currentData = [];
var yourElement = document.getElementById('application');
client.doRequest("php.php").then(function(response){
currentData = response;
renderData();
})
function renderData() {
yourElement.innerHTML = '';
currentData.forEach(function(item){
if(isNew(item)) {
yourElement.apendChild(createHighlightedData(item));
} else {
yourElement.apendChild(createOrdinarData(item));
}
})
}
function createHighlightedData(item) {
return ...
}
function createOrdinarData(item) {
return ...
}

Database won't connect, no results returned

So I've got three PHP files, and I'm trying to connect my database through these files. It won't seem to connect, I'm trying to connect it so then my ajax in my javascript file will hopefully work.
BaseClass.php:
<?php
require("Conn.php");
require("MySQLDao.php");
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
if (empty($raw_post_data))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($raw_post_data, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
When I run this in chrome all it shows is:
{"status":false,"title":"Error","message":"No Data Recieved"}
MySQLDao.php:
<?php
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
Nothing shows when I run this in chrome. Even when I put echo statements in some of the functions.
Conn.php:
<?php
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "";
}
?>
part of my test.html:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "MySQLDao.php",
data: { action : 'getResults()' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
}
//error, function(err){console.log(err)}
});
}
I basically just want to be able to write query methods and transport the results from these querys to my js, this is because I have a few graphs in my javascript and I want to get data from the database. All this code doesn't produce any errors I believe but it's just not returning anything back.
All help appreciated! Thanks!

Search from different table in yii

I am new to Yii. I have basically two tables for computation. TABLE:Mst_customers=> model name = masterCustomers ,TABLE:mst_nimsoft_host=> model name = NimsoftHost. I have a drop-down in my view, where it asks for Search by customer name or by host name. I have default search by customer name. Below that I have a text field with AJAX validation. the operation is that when I enter three letters, it must suggest customers name similar to that. and if I select search by host name in drop down and if I enter three letters/numbers it must check for similar host name in mst_nimsoft_host table, I have given my code here
My controller:
<?php
class NimsoftController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/ticket_console';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','nimsoftCustomers','Search','Details','UploadCustomers','StaticCi','city2','Customers','CiLink','LoadCustType'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate($id)
{
$model=new NimsoftHost;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$cust_id=$id;
$criteria = new CDbCriteria;
$cust_name = MasterCustomers::model()->findByPk($cust_id);
if(isset($_POST['NimsoftHost']))
{
$model->attributes=$_POST['NimsoftHost'];
$model->host_customer_id=$id;
if($model->save())
{
$this->redirect(array('view','id'=>$model->host_id));
}
}
$this->render('create',array(
'model'=>$model,'cust_id'=>$cust_id,'cust_name'=>$cust_name->cust_name
));
}
public function actionLoadCustType(){
$customer_id = $_POST['NimsoftHost']['host_customer_id'];
//$customer_id = 3;
// customer type
$custDetails = masterCustomers::model()->findByPk($customer_id);
$customer_type = $custDetails->cust_type;
// get customer service details
$criteria = new CDbCriteria;
$serviceDetails = masterCustomerServices::model()->findAllByAttributes(array('cust_id'=>$customer_id,'i_type'=>'im'));
//$serviceArr = array(array('label'=>'Please Service','value'=>''));
//$slaArr = array(array('label'=>'Please Select SLA','value'=>''));
//$blankServices = array();
//$srtypeArr = array(array('label'=>'Select SR Type','value'=>''));
foreach($serviceDetails as $val){
// get sla name
$criteria = new CDbCriteria;
$sla = masterSla::model()->findByPk($val->sla_id);
$slaArr[] = array(
'label' => $sla->sla_name,
'value' => $val->sla_id,
);
/*// get service type
$criteria = new CDbCriteria;
$services = masterServiceType::model()->findByPk($val->service_type_id);
$blankServices[] = $services->service_type_id;
$serviceArr[] = array(
'label' => $services->service_type_name,
'value' => $services->service_type_id,
);*/
//$serviceArr[$val->service_type_id] = $services->service_type_name;
}
// customer type
$custTypeDetails = MasterCustomerType::model()->findByPk($customer_type);
/* // get sr types
$criteria = new CDbCriteria;
$criteria->addCondition("i_type = 'im'", 'AND');
$criteria->addInCondition('sr_service_type_id',$blankServices);
$srArr = masterSrTypes::model()->findAll($criteria);
foreach($srArr as $sr){
$srtypeArr[] = array(
'label' => $sr->sr_type_name,
'value' => $sr->sr_type_id,
);
}*/
echo json_encode(array('cust_type'=>$custTypeDetails->cust_type_name,
'customerid'=>md5($customer_id),
//'services'=>$serviceArr,
//'srtypes'=>$srtypeArr,
'slas'=>$slaArr,
'sfdc'=>$custDetails->cust_sfdc_id,
'accountid'=>$custDetails->cust_account_id));
}
public function actionDetails($id)
{
$this->layout = 'iframe';
$custid=$id;
if(isset($custid) && $custid != ''){
$criteria = new CDbCriteria;
$criteria->condition = "md5(cust_id) = '$custid'";
$details = masterCustomers::model()->findAll($criteria);
// get service & sla Details
$criteria = new CDbCriteria;
$criteria->condition = "md5(cust_id) = '$custid'";
$sdetails = masterCustomerServices::model()->findAll($criteria);
//get host details
$criteria = new CDbCriteria;
$criteria->condition = "md5(host_customer_id) = '$custid'";
$hostdetails = NimsoftHost::model()->findAll($criteria);
// get contact details
$criteria = new CDbCriteria;
$criteria->condition = "md5(cust_id) = '$custid'";
$criteria->with = array('contactCategory');
$contactDetails = masterCustomersContacts::model()->findAll($criteria);
$this->render('details',array('customer'=>$details,'service'=>$sdetails,'contact'=>$contactDetails,'host'=>$hostdetails));
}
}
public function actionCiLink($action=''){
$this->layout = 'iframe';
if(isset($action) && isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$cis = Yii::app()->user->getState("ci_relations");
$temp = array();
if(!empty($cis)){
foreach($cis as $val){
if($id != $val){
$temp[] = $val;
}
}
Yii::app()->user->setState("ci_relations",$temp);
}
echo $this->renderPartial('_static_ci_display',array('citems'=>Yii::app()->user->getState("ci_relations")));
exit;
}
if(isset($_REQUEST['checkCI'])){
$ci = $_REQUEST['checkCI'];
if(Yii::app()->user->hasState("ci_relations")){
$existing = Yii::app()->user->getState("ci_relations");
foreach($ci as $new){
$existing[] = $new;
}
Yii::app()->user->setState("ci_relations", array_unique($existing));
}else{
Yii::app()->user->setState("ci_relations",$ci);
}
echo '
<div style="font-size:12px;font-family:Arial;color:#CCC;">CI Relation added successfully.</div>
<script>
var jQuery = parent.jQuery;
setTimeout(function () {
try {
jQuery("#ci_items", window.parent.document).empty().html("please wait loading...");
jQuery("#ci_items", window.parent.document).empty().load("'.$this->createUrl('itsmIncidents/staticCi').'");
parent.window.hs.getExpander().close();
} catch (e) {}
}, 500);
</script>
';
exit;
}
$model = new CmdbMaster('customsearch');
$model->unsetAttributes(); // clear any default values
if(Yii::app()->request->isAjaxRequest){
$inc = $_REQUEST['itsmIncidents']['inc_number'];
if (isset($_GET['CmdbMaster'])) {
$model->attributes = $_GET['CmdbMaster'];
}
$this->renderPartial('_ci_form_grid_json', array(
'model' => $model,
'inc'=> $inc,
'pages' => 10
));
exit;
}
$this->render('_static_ci_form');
}
public function actionStaticCi(){
echo $this->renderPartial('_static_ci_display',array('citems'=>Yii::app()->user->getState("ci_relations")));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['NimsoftHost']))
{
$model->attributes=$_POST['NimsoftHost'];
if($model->save())
$this->redirect(array('view','id'=>$model->host_id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$user = Yii::app()->db->createCommand()
->select('cust_name')
->from('mst_customers')
->queryAll();
$dataProvider=new CActiveDataProvider('NimsoftHost');
$model = new NimsoftHost();
$this->render('sample',array(
'dataProvider'=>$dataProvider,
'user' => $user,
'model'=>$model,
));
}
public function actionCustomers(){
//header('content-type: application/json; charset=utf-8');
$select= $_GET['select'];
$str = $_GET['q'];
if($select=='Customer_name')
{
$criteria = new CDbCriteria();
$criteria->condition = "( cust_name like '%$str%')";
$models = masterCustomers::model()->findall($criteria);
}
else
{
$criteria = new CDbCriteria();
$criteria->condition = "( host_name like '%$str%')";
$models = NimsoftHost::model()->findall($criteria);
}
$result = array();
foreach ($models AS $groups)
{
if($groups->cust_account_id != ''){
$acc = ' ( '.$groups->cust_account_id.' ) ';
}
$result['details'][] = array(
'id' => $groups->cust_id,
'name' => $groups->cust_name.$acc,
);
}
echo $_GET['callback'] . "(";
echo CJSON::encode($result);
echo ")";
}
public function actionUploadCustomers()
{
$this->layout = 'iframe';
$model = new NimsoftHost;
if(isset($_POST['NimsoftHost'])){
$sfile = CUploadedFile::getInstance($model,'upload_file');
$path = $sfile->tempName;
$handle = fopen($path,"r");
if ($handle) {
$flag = true;
while(($line = fgetcsv($handle, 1000, ",")) != FALSE) {
if($flag) { $flag = false; continue; } // ignore first line
$model = new NimsoftHost;
$model->host_name = $hostname = trim($line[0]);
$model->host_serviceid = $host_serviceid = $line[1];
$model->host_customer_id= $host_customer_id = $line[2];
$user = Yii::app()->db->createCommand()
->select('cust_id')
->from('mst_customers')
->where('cust_name=:cust_name', array(':cust_name'=>$model->host_customer_id))
->queryRow();
$model->host_customer_id=$user['cust_id'];
if($model->validate() && $model->host_name != ''){
$model->save();
echo "Uploaded successfully";
}
else {
echo "ALREADY PRESENT";
}
}
}
fclose($handle);
exit;
}
$this->render('_upload_file',array('model'=>$model));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new NimsoftHost('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['NimsoftHost']))
$model->attributes=$_GET['NimsoftHost'];
$this->render('admin',array(
'model'=>$model,
));
}
public function actionSearch($id){
echo $cust_id=$id;
die();
$criteria = new CDbCriteria();
$criteria->condition = "md5(host_customer_id) = '$cust_id'";
$details = NimsoftHost::model()->find($criteria);
/*if($details)
{
$criteria = new CDbCriteria();
$criteria->condition = "md5(cust_id) = '$id'";
$details = MasterCustomers::model()->find($criteria);
$details=$details->cust_id;
}*/
$dataProvider=new CActiveDataProvider('NimsoftHost',array(
'criteria' => $criteria,));
$model = new NimsoftHost();
$this->render('index',array(
'dataProvider'=>$dataProvider,'details'=>$details));
/*$this->layout = 'ticket_console';
$model = new itsmIncidents('search');
$model->unsetAttributes();
// Groups details
$criteria = new CDbCriteria;
$arrGrp = masterGroups::model()->findall($criteria);
$arr = array();
foreach($arrGrp as $e)
{
$arr[$e->group_id]=$e->group_name;
}
$arrGrp=$arr;
// severity types details
$criteria = new CDbCriteria;
$arrSvr = masterSeverityType::model()->findall($criteria);
$arr = array();
$arr['']='Select Severity';
foreach($arrSvr as $e)
{
$arr[$e->severity_type_id]=$e->severity_type_name;
}
$arrSvr=$arr;
if(isset($_GET['itsmIncidents']))
$model->attributes=$_GET['itsmIncidents'];
if(Yii::app()->request->isAjaxRequest){
$this->renderPartial('_my_ticket_grid_json',array('dataProvider'=>$model->search()));
}else{
$this->render('_mysearch',array(
'model'=>$model,
'assgroup'=>$arrGrp,
'sevArr'=>$arrSvr,
));
}*/
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return NimsoftHost the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=NimsoftHost::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param NimsoftHost $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='nimsoft-host-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
My view:
<div id="content">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'nimsoft-host-form',
//'enableAjaxValidation'=>true,
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => true, // allow client validation for every field
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<div style="float:left;padding-left:20px;">
<select name="search_by" size="1" onchange="javascript:onchange_action()" >
<option value="Customer_name" selected>Customer Name</option>
<option value="Host_name" >Host Name</option>
</select>
<?php echo $form->labelEx($model,'host_customer_id'); ?>
<?php
$variable=$_POST['search_by'];
echo $form->textField($model,'host_customer_id',array('style'=>'width:420px;'));
$this->widget('ext.select2.ESelect2', array(
'selector' => '#NimsoftHost_host_customer_id',
'options' => array(
'allowClear'=>false,
'placeholder' => 'Search Customers',
'minimumInputLength' => 3,
'quietMillis'=>100,
'ajax' => array(
'url' => Yii::app()->createUrl('Nimsoft/customers/'),
'dataType' => 'jsonp',
'data' => 'js: function('.$variable.',term,page) {
return {
select:'.$variable.'
q: term,
//ctype: $("#itsmIncidents_cloudcustomer input:radio:checked").val(),
page_limit: 10,
};
}',
'results' => 'js: function(data,page){
return {results: data.details};
}',
),
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
),
));
?>
<div style="float:right">
<?php
echo CHtml::link('Manage Hosts', array('/Nimsoft/Search'), array(
//'onclick'=>'return hs.htmlExpand(this, { objectType: "iframe", wrapperClassName: "full-size",height:500, align: "center" } )',
'class'=>'btn btn-block btn-success',
'style'=>'width:150px;display:none;',
'id'=>'search_details_pop',
));
?>
</div>
</div>
</div>
<script>
function onchange_action()
{
var e=document.getElementsByName("search_by")[0];
alert("the value of the option here is "+e.value);
}
$("#NimsoftHost_host_customer_id").on("change", function(e) {
<?php echo CHtml::ajax(array(
'url'=>array('Nimsoft/loadCustType'),
'data'=> "js:{'NimsoftHost[host_customer_id]':e.val}",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
// search customer host details
$('#search_details_pop').css('display','block');
$('#search_details_pop').attr('href', 'Nimsoft/search/id/'+data.customerid);
} ",
))?>;
})
</script>
<?php $this->endWidget();?>
I am not able to perform the above requirement. please help me on this. Thanks in advance.
Here is a link for your question's answer.
I think that you can use autocomplete.
In the link, the answer will show the way to you. There is a actionAutoComplete function. edit it like,
// if $term first 3 character is numeric
$query = NimsoftHost::model()->findallbyattributes( array('somecolumn'=>$term));
// else
$query = masterCustomers::model()->findallbyattributes( array('somecolumn'=>$term));
$list = array();
foreach($query as $q){
$data['value']= $q['id'];
$data['label']= $q['name'];
$list[]= $data;
unset($data);
}
echo json_encode($list);

Categories