MY CODE


so this is my AuthController.php :

<?php
namespace PhalconRest\Controllers;
use \PhalconRest\Exceptions\HTTPException;
use PhalconRest\Models\VlApps;

class AuthController extends RESTController{

/**
* Sets which fields may be searched against, and which fields are allowed to be returned in
* partial responses.
* @var array
*/
protected $allowedFields = array(
'search' => array('APIID', 'SECRETKEY')
);
public function get(){
return $this->respond(array('apiId'=>$this->session->get('apiId')));
}

public function auth(){
foreach ($this->searchFields as $field => $value) {
if($field == 'APIID'){
$APPID = $value;
}else if($field == 'SECRETKEY'){
$SECRETKEY = $value;
}
}

try {
$cache = $this->modelsCache;
$data = array();
$cacheKey = 'apiauth.cache';
$data = $cache->get($cacheKey);
if ($data === null) {

$data = VlApps::query()
->where("apps_APP_ID =?1")
->andWhere("apps_SECRETKEY =?2")
->bind(array(1=>$APPID,2=>sha1('V@lu3lin3-'.$SECRETKEY.'-SOLDEV')))
->execute();
$cache->save($cacheKey,$data);
}

foreach($data as $app){
$this->session->set('apiId',$app->apps_APP_ID);
$this->session->set('apiKey',$app->apps_Key);
$this->session->set('appId',$app->autokey);
return $this->respond(array('apiId'=>$this->session->get('apiId')));
}
} catch (Exception $e) {
$this->logger->log('/auth - '.$e->getMessage(),\Phalcon\Logger::ERROR);
$this->logger->close();
return $this->respond();
}


}


public function respond($results){
return $results;
}

private function array_remove_keys($array, $keys = array()) {

// If array is empty or not an array at all, don't bother
// doing anything else.
if(empty($array) || (! is_array($array))) {
return $array;
}

// At this point if $keys is not an array, we can't do anything with it.
if(! is_array($keys)) {
return $array;
}

// array_diff_key() expected an associative array.
$assocKeys = array();
foreach($keys as $key) {
$assocKeys[$key] = true;
}

return array_diff_key($array, $assocKeys);
}

}


this is my VlApps.php :

<?php
namespace PhalconRest\Models;
use \PhalconRest\Exceptions\HTTPException,
Phalcon\Mvc\Model\Resultset;


class VlApps extends \Phalcon\Mvc\Model
{

/**
*
* @var integer
*/
public $autokey;

/**
*
* @var string
*/
public $apps_APP_ID;

/**
*
* @var string
*/
public $apps_SECRETKEY;

/**
*
* @var integer
*/
public $apps_partner;

}

this is my DiscountController.php:

<?php
namespace PhalconRest\Controllers;
use \PhalconRest\Exceptions\HTTPException,
PhalconRest\Models\VlDiscount,
PhalconRest\Models\VlProduct;


class DiscountController extends RESTController{


protected $allowedFields = array(
'search' => array('KEY','NAME', 'CODE', 'DESC','keyList','page','rows')
);

//get category
public function getCategory(){

$page = 1;
$row = 10;
$productName = '';

foreach ($this->searchFields as $field => $value) {
if($field == 'page'){
$page = $value;
}else if($field == 'rows'){
$rows = $value;
}else if($field == 'NAME'){
$productName = $value;
}
}



$offset = ($page-1)*$rows;

if($productName != ""){

$total = VlDiscount::query()
->where("productName LIKE ?1 or productCode LIKE ?2")
->andWhere("app_id =?3")
->bind(array(1 => '%'.$productName.'%', 2 => '%'.$productName.'%', 3 =>$this->session->get('appId')))
->execute();

$query = VlCategory::query()
->where("productName LIKE ?1 or productCode LIKE ?2")
->andWhere("app_id =?3")
->limit($rows,$offset)
->bind(array(1 => '%'.$productName.'%', 2 => '%'.$productName.'%', 3 =>$this->session->get('appId')))
->execute();

} else {
$total = VlDiscount::query()
->where("app_id =?3")
->bind(array(3 =>$this->session->get('appId')))
->execute();

$query = VlDiscount::query()
->where("app_id =?3")
->limit($rows,$offset)
->bind(array(3 =>$this->session->get('appId')))
->execute();
}

$data = array();

foreach ($query as $key) :
$data[] = array(
'key' => $key->autokey,
'productName' => $key->productName,
'productCode' => $key->productCode,
'discountDesc' => $key->discountDesc
);
endforeach;

$paginate = $this->paginateDisplay($rows,$page,count($total));
return $this->respond(array(
'row' => $data,
'currentPage' => $paginate['currentPage'],
'prevousPage' => $paginate['prevPage'],
'nextPage' => $paginate['nextPage'],
'noOfPage' => $paginate['noOfPage'],
'range' => $paginate['range'],
'total' => count($total)));

}


public function searchProducts(){

foreach ($this->searchFields as $field => $value) {
if($field == 'NAME'){
$productName = $value;
}
}

$discount = VlDiscount::query()
->where("app_id =?1")
->andWhere("productName =?2")
->bind(array(1 => $this->session->get('appId'), 2 => $cproductName))
->execute();

foreach($discount as $cat){
$categoryProduct = VlProduct::query()
->where("app_id =?1")
->andWhere("productCategory =?2")
->bind(array(1 => $this->session->get('appId'), 2 => $cat->autokey))
->execute();
}


$data = array();
if(count($categoryProduct) > 0) {
foreach ($categoryProduct as $key) :
$data[] = array(
'userMessage' => 'OK',
'productCode' => $key->productCode,
'productName' => $key->productName,
'productPrice' => $key->productPrice,
'productDesc' => $key->productDesc,
'productShortDesc' => $key->productShortDesc,
'productStatus' => $key->productStatus,
'productImage' => $key->productImage,
'url' => $this->fileDomain.$this->session->get('appId').'/'
);
endforeach;
} else {
$data[] = array(
'userMessage' => 'Failed',
'more' => 'No Product Found'
);
}

return $this->respond($data);
}

public function searchDiscount(){

foreach ($this->searchFields as $field => $value) {
if($field == 'NAME'){
$productName = $value;
}else if($field == 'CODE'){
$productCode = $value;
}
}

$data = array();

if($productName != '' && $productCode != ''){
$query = VlDiscount::find(array(
'conditions' => 'productName LIKE ?1 or productCode LIKE ?2 and app_id = ?3',
'bind' => array(1 => $productName.'%', 2 => $productCode.'%', 3 =>$this->session->get('appId'))
));
} else if ($productName != ''){
$query = VlDiscount::find(array(
'conditions' => 'productName LIKE ?1 and app_id = ?3',
'bind' => array(1 => '%'.$productName.'%', 3 =>$this->session->get('appId'))
));
} else {
$query = VlDiscount::find(array(
'conditions' => 'productCode LIKE ?2 and app_id = ?3',
'bind' => array(2 => '%'.$productCode.'%', 3 =>$this->session->get('appId'))
));
}


if(count($query) > 0 ){
foreach ($query as $key) :
$data[] = array(
'productName' => $key->productName,
'discountDesc' => $key->discountDesc,
'productCode' => $key->productCode
);
endforeach;
} else {
foreach ($category->getMessages() as $key) :
$data[] = array(
'userMessage' => 'Failed',
'devMessage'=> $key->getMessage(),
'more' => 'No Found Results');
endforeach;
}

return $this->respond($data);
}

public function getDiscountInfo($id){

$query = VlDiscount::query()
->where("autokey = ?1")
->andWhere("app_id =?2")
->bind(array(1 => $id,2 =>$this->session->get('appId')))
->execute();

foreach ($query as $key) {
return $this->respond( array(
'key' => $key->autokey,
'productName' => $key->productName,
'productCode' => $key->productCode,
'discountDesc' => $key->discountDesc
));
}
}

public function addDiscount(){

foreach ($this->searchFields as $field => $value) {
if($field == 'NAME'){
$productName = $value;
}else if($field == 'CODE'){
$productCode = $value;
} else if($field == 'DESC'){
$discountDesc = $value;
}
}

$discount = new VlDiscount();

$discount->productName = $productName;
$discount->productCode = $productCode;
$discount->discountDesc = $discountDesc;
$discount->app_id = $this->session->get('appId');

$data = array();
if($discount->create() == false){
$devMessage = array();
foreach ($discount->getMessages() as $key){
$devMessage[] = $key->getMessage();
}
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => $devMessage,
'more' => 'Failed to create. One or more fields failed on validation.'
));
} else {
return $this->respond(array('userMessage' => 'OK'));
}
}


public function editDiscount(){

foreach ($this->searchFields as $field => $value) :
if($field == 'KEY'){
$key = $value;
} else if($field == 'NAME'){
$discountName = $value;
} else if($field == 'CODE'){
$discountCode = $value;
} else if($field == 'DESC'){
$discriptionDesc = $value;
}
endforeach;

$discount = VlDiscount::query()
->andWhere("autokey =?1")
->andWhere("app_id =?2")
->bind(array(1=>$key,2=>$this->session->get('appId')))
->execute();

if($discount->count() != 0){

$discountUpdate = VlDiscount::findFirst($key);
$discountUpdate->productName = $productName;
$discountUpdate->cproductCode = $productCode;
$discountUpdate->discountDesc = $discountDesc;

if($discountUpdate->update() == false){
$devMessage = array();
foreach ($discountUpdate->getMessages() as $key){
$devMessage[] = $key->getMessage();
}
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => $devMessage,
'more' => 'Failed to update. One or more fields failed on validation.'
));
} else {
return $this->respond(array('userMessage' => 'OK'));
}

}
}

public function deleteDiscount(){

foreach ($this->searchFields as $field => $value) :
if($field == 'keyList'){
$keyList = $value;
}
endforeach;

$ex = explode('|',$keyList);
$deleteError = 0;
foreach($ex as $x){

$category = VlCategory::query()
->andWhere("autokey =?1")
->andWhere("app_id =?2")
->bind(array(1=>(int)$x,2=>$this->session->get('appId')))
->execute();

foreach($discount as $cat){
$discountDelete = VlDiscount::findFirst($cat->autokey);
if ($discountDelete != false) {
if ($discountDelete->delete() == false) {
$deleteError++;
$devMessage = array();
foreach ($discount->getMessages() as $key){
$devMessage[] = $key->getMessage();
}


}
}
}
unset($discount);
}

if($deleteError == 0){
return $this->respond(array('userMessage' => 'OK'));
}else{
return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => $devMessage,
'more' => 'Failed to delete. One or more fields produced an error.'
));
}

return $this->respond(array(
'userMessage' => 'Failed',
'devMessage' => 'Cannot find user information',
'more' => 'Failed to update. One or more fields failed on validation.'
));

}
// end class
}


this is my VlDiscount.php :

<?php
namespace PhalconRest\Models;
use \PhalconRest\Exceptions\HTTPException, Phalcon\Mvc\Model\Resultset, Phalcon\Mvc\Model\Message;
use Phalcon\Mvc\Model\Validator\Uniqueness as Uniqueness;


class VlDiscount extends \Phalcon\Mvc\Model
{

/**
*
* @var integer
*/
public $autokey;

/**
*
* @var string
*/
public $productName;

/**
*
* @var string
*/
public $productCode;

/**
*
* @var string
*/
public $discountDesc;

/**
*
* @var integer
*/
public $app_id;

public function initialize() {
$this->hasMany("productCode", "VlProduct", "productCategory");
}

//validation befor inserting data...
public function beforeCreate() {

$this->validate(new Uniqueness(array(
"field" => "productName",
"message" => "Product Name is already used."
)));

$this->validate(new Uniqueness(array(
"field" => "productCode",
"message" => "Product Code is already used."
)));

if ($this->validationHasFailed() == true) {
return false;
}
}

//validatin before updating data
public function beforeUpdate() {

$this->validate(new Uniqueness(array(
"field" => "productName",
"message" => "Cannot update name already in the list."
)));

$this->validate(new Uniqueness(array(
"field" => "productCode",
"message" => "Cannot update product code is already in the list."
)));

if ($this->validationHasFailed() == true) {
return false;
}
}



}


my discount.js

$(function() {
getData();
$('#rows-count').on('change',function(){
rows = $('#rows-count').val();
page = 1;
getData();
});

$('body').on('keypress','#searchBox',function(e){
if (e.which == 13) {
getData();
}
});

$('body').on('click','.dataTables_filter span.btn', function(e){
getData();
});
});


function getData(){
notifyClose();
$('#statusContent').show();
$('#preloaderContent').show();
$.ajax({
type : 'GET',
async : false,
data :{
productName : $('#searchBox').val(),
rows: rows,
page: page
},
url : baseUrl+'/admin/getdiscount',
error: function(req,error){
notify('e',req.statusText);
},
dataType: 'json',
cache: false,
success : function(msg){
if(Object.keys(msg).length != 0){
$('#table_discount >tbody >tr').remove();
tblrow = 0;
$.each(msg[0].row,function(i,e){
tblrow++;
$('#table_discount > tbody:last').append('<tr id="tr_'+tblrow+'"><td class="align-center"><input type="checkbox" class="chkbox" value="'+e.key+'"><span class="lbl"></span></td><td><a href="javascript: void(0);" onclick="editPageLink('+e.key+');">'+e.productCode+'</a></td><td class="">'+e.productName+'</td><td class="hidden-phone">'+e.discountDesc+'</td></tr>');
});

$('#record-show-start').html(msg[0].currentPage);
$('#record-show-end').html(msg[0].noOfPage);
$('#page-item li').remove();
var pageHtml = '';

if(msg[0].currentPage == '1'){
pageHtml +='<li class="prev disabled"><a href="javascript: void(0);"><i class="icon-double-angle-left"></i></a></li>';
}else{
pageHtml +='<li class="prev"><a href="javascript: void(0);" onclick="displayPageItem('+msg[0].prevousPage+');"><i class="icon-double-angle-left"></i></a></li>';
}


for(var i = 1; i <= parseInt(msg[0].noOfPage);i++){
if(parseInt(msg[0].currentPage) == i){
pageHtml += '<li class="active"><a href="javascript: void(0);" onclick="displayPageItem('+i+');">'+i+'</a></li>';
}else{
pageHtml += '<li><a href="javascript: void(0);" onclick="displayPageItem('+i+');">'+i+'</a></li>';
}
}

if(msg[0].currentPage == msg[0].noOfPage){
pageHtml +='<li class="next disabled"><a href="javascript: void(0);"><i class="icon-double-angle-right"></i></a></li>';
}else{
pageHtml += '<li class="next"><a href="javascript: void(0);" onclick="displayPageItem('+msg[0].nextPage+');"><i class="icon-double-angle-right"></i></a></li>';
}
$('#page-item').html(pageHtml);
}
}
});
$('#statusContent').fadeOut();
$('#preloaderContent').delay(350).fadeOut('slow');


}


//creating or updating discount page...
function newPage(){
notifyClose();
displayInput();
saveType = 's';
}

function displayPageItem(newPage){
page = newPage;
getData();
}

function reloadPage(){
getData();
}

function closePage(){
reloadPage();
clearPage();
displayData();
}


function editPage(){

var count = 0;
$(".chkbox").each(function(){
var $this = $(this);
if ($this.is(':checked')) {
stringdata = $(this).val();
count++;
}
});
if(count == 0){
notify('w','Please select one item to continue..');
}else if(count > 1){
notify('w','Please select one item to continue..');
}else{
$.ajax({
type : 'GET',
async : false,
data : {
key : stringdata
},
url : baseUrl+'/admin/getdiscountinfo',
error: function(req,error){
notify('e',req.statusText);
},
dataType: 'json',
cache: false,
success : function(msg){
if(Object.keys(msg).length != 0){
newPage();
saveType = 'u';
key = msg[0].key;
$('#productCode').val(msg[0].productCode);
$('#productName').val(msg[0].productName);
$('#discountDesc').val(msg[0].discountDesc);
}
}
});
}
}

function editPageLink(id){
$.ajax({
type : 'GET',
async : false,
data : {
key : id
},
url : baseUrl+'/admin/getdiscountinfo',
error: function(req,error){
notify('e',req.statusText);
},
dataType: 'json',
cache: false,
success : function(msg){
if(Object.keys(msg).length != 0){
newPage();
saveType = 'u';
key = msg[0].key;
$('#productCode').val(msg[0].productCode);
$('#productName').val(msg[0].productName);
$('#discountDesc').val(msg[0].discountDesc);
}
}
});
}

function savePage(){
if(!$('input,select,textarea').jqBootstrapValidation("hasErrors")){
if(saveType == 's'){
url = baseUrl+'/admin/savediscount';
}else{
url = baseUrl+'/admin/updatediscount';
}
$.ajax({
type : 'GET',
async : false,
data : {
key : key,
productCode : $('#productCode').val(),
productName : $('#productName').val(),
discountDesc : $('#discountDesc').val()
},
url : url,
error: function(req,error){
notify('e',req.statusText);
},
dataType: 'json',
cache: false,
success : function(msg){
console.log(msg);
if(msg[0].userMessage =='OK'){
var productName = $('#productName').val();
closePage();
if(saveType == 's'){
notify('s',productName+' information has been saved.');
}else{
notify('s',productName+' information has been modified.');
}

}else{
var str = '';
$.each(msg[0].devMessage,function(e,i){
str += i +',';
});
notify('e',str.substring(0,str.length - 1));
}
}
});
}else{
var errors = $('input,select,textarea').jqBootstrapValidation("collectErrors");
$('#pageInput').submit();
}

}




//delete

function deletePage(){
var stringdata = '';
$(".chkbox").each(function() {
var $this = $(this);
if ($this.is(':checked')) {
stringdata += $(this).val() + '|';
}
});
if(stringdata == ''){
notify('w','Please select atleast one item to continue.');
}else{
$.ajax({
type : 'GET',
async : false,
data : {
keyList : stringdata
},
url : url = baseUrl+'/admin/deleteDiscount',
error: function(req,error){
notify('e',req.statusText);
},
dataType: 'json',
cache: false,
success : function(msg){
console.log(msg);
if(msg[0].userMessage =='OK'){
reloadPage();
notify('s','Selected data has been deleted!');
}else{
var str = '';
$.each(msg[0].devMessage,function(e,i){
str += i +',';
});
notify('e',str.substring(0,str.length - 1));
}
}
});
}
}

my discount.phtml:

<div class="row-fluid">
<div class="span12 pageData">
<div class="dataTables_wrapper" role="grid">
<div class="row-fluid">
<div class="pull-left">
<div id="table_report_length" class="dataTables_length">
<span>Display</span>
<select size="1" id="rows-count">
<option value="10" selected="selected">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select> <span> records</span>
</div>
</div>
<div class="pull-right">
<div class="dataTables_filter" id="table_report_filter">
<div class="input-append">
<input class="input-small" type="text" id="searchBox" placeholder="Category Name">
<span class="btn btn-small"><i class="icon-search" id="searchBtn"></i></span>
</div>
</div>
</div>
</div>
<!-- inner table -->
<table id="table_discount" class="table table-condensed table-striped">
<thead>
<tr>
<th width="1%" class="nowrap align-center">
<label><input type="checkbox" id="checkall-toggle" value="" title="Check All" /><span class="lbl"></span></label>
</th>
<th>Product Code</th>
<th>Product Name</th>
<th class="hidden-phone">Discount Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- end inner table -->
<div class="row-fluid">
<div class="pull-left">
<div class="dataTables_info" id="table_report_info">Page <span id="record-show-start"></span> to <span id="record-show-end"></span></div>
</div>
<div class="pull-right">
<div class="dataTables_paginate paging_bootstrap pagination">
<ul id="page-item">
<li class="prev disabled"><a href="#"><i class="icon-double-angle-left"></i></a></li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>

<li class="next"><a href="#"><i class="icon-double-angle-right"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>

<form id="pageInput" class="pageInput form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="productCode">Product Code</label>
<div class="controls">
<input type="text" id="productCode" name="productCode" placeholder="" class="span4" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="productName">Product Name</label>
<div class="controls">
<input type="text" id="productName" name="productName" maxlength="100" placeholder="" class="span4" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="discountDesc">Discount Description</label>
<div class="controls">
<textarea class="span4" id="discountDesc" name="discountDesc" placeholder="" required ></textarea>
</div>
</div>

</form>
</div>

Reply · Report Post