Related
Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom
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
Not really expecting to get answer but struggling with this 2 days now and have no idea whats going on.
So here what I have done:
Uploading file via AJAX and immediately starting processing it in backend.
$.ajax({
type : "post",
cache: false,
contentType: false,
processData: false,
url : formAction,
data : formData
});
In backend I writing session where storing current progress like 500 of 10000...
Then I calling another AJAX to check status from session, I calling this funcion every 1 second till responsve returns 'done'.
Looks legit to me, but problem is that after backend proccessing done, and first XHR changing status from 'pending' to 200 browsers freeze, looks like something is blocking it, like another request or somehing. chekc screens bellow.
So it's done, check is stopped, status is changed to 200, nothing happening but browsers freeze, tried Chrome, Firefox...Browser suggesting me to kill process, but if I wait some time it will refresh.
UPDATE
So i lie a little bit, I tried again do same but without ajax and saw similar issue, after backend processing complete, browser waiting response (spinning backwards)...So that is what cousin hanging.
Here is my backend it's Laravel
foreach ($chunks as $rows)
{
$current_chunk++;
if ( $current_chunk < $all_chunks ) {
Session::put(['import_progress'=>'Importing ' . $current_chunk * 150 . ' of ' . $all_results]);
Session::save();
} elseif ( $current_chunk >= $all_chunks ) {
Session::put(['import_progress'=>'done']);
}
foreach ($rows as $row)
{
// transakcija start
DB::transaction(function() use ($row) {
$code = $row[0];
$gender = $row[1];
$brand_name = filter_var($row[2],FILTER_SANITIZE_STRING);
$category = $row[3];
$subcategory = $row[4];
$condition = $row[5];
$details = $row[6];
$composition = $row[7];
$materials = $row[8];
$colors = $row[9];
$patterns = $row[10];
$country = $row[11];
$size = $row[12];
$m_a = $row[13];
$m_b = $row[14];
$m_c = $row[15];
$m_d = $row[16];
$m_e = $row[17];
$m_f = $row[18];
$m_g = $row[19];
$product = new Product();
$product->code = $code;
$product->gender = $gender;
$product->size = $country . ' | ' . $size;
$product->condition = $condition;
$product->measurement_a = $m_a;
$product->measurement_b = $m_b;
$product->measurement_c = $m_c;
$product->measurement_d = $m_d;
$product->measurement_e = $m_e;
$product->measurement_f = $m_f;
$product->measurement_g = $m_g;
$product->save();
if ( empty($code) ) {
$bad_prods[] = $product->id;
}
if ( !empty( $brand_name ) ) {
$brand = Brand::firstOrCreate(['brand_name'=>$brand_name]);
$product_b = new ProductBrand();
$product_b->brand_id = $brand->id;
$product_b->product_id = $product->id;
$product_b->save();
}
if ( !empty( $materials ) ) {
$materials_exp = explode(',',$materials);
foreach ($materials_exp as $material) {
$material = Material::firstOrCreate(['material_name'=>trim($material)]);
$product_m = new ProductMaterial();
$product_m->material_id = $material->id;
$product_m->product_id = $product->id;
$product_m->save();
}
}
if ( !empty( $patterns ) ) {
$patterns_exp = explode('/',$patterns);
foreach ($patterns_exp as $pattern) {
$pattern = Pattern::firstOrCreate(['pattern_name'=>trim($pattern)]);
$product_p = new ProductPattern();
$product_p->pattern_id = $pattern->id;
$product_p->product_id = $product->id;
$product_p->save();
}
}
if ( !empty( $colors ) ) {
$colors_exp = explode('/',$colors);
foreach ($colors_exp as $color) {
$color = Color::firstOrCreate(['color_name'=>trim($color)]);
$product_c = new ProductColor();
$product_c->color_id = $color->id;
$product_c->product_id = $product->id;
$product_c->save();
}
}
$product_t = new ProductTranslation();
$product_t->product_id = $product->id;
$product_t->product_title = $brand_name;
$product_t->product_description = '<p>'.$details.'</p><p>'.$composition.'</p>';
$product_t->save();
}); // end transakcija
}
}
Session::put(['import_progress'=>'done']);
Session::put(['bad_prods'=>$bad_prods]);
return redirect()->route('admin.import');
And here I'm checking status
public function status()
{
return response()->json([
'status' => Session::get('import_progress'),
'bad_prods' => Session::get('bad_prods')
]);
}
When processing is done I put simple exit(); at the end of processing Controller...Not sure why this works and any other return statement doesn't.
I am trying to figure out how to block a user from signing in to my site unless they are over a certain permission level. I am making my site public and once someone registers they are given the permission level 'bench'. Once I accept the user and change the permission level, then they are able to login. The way I am blocking the 'bench' permission level users is with a redirect to the index page(where they sign in at). However, I want to display some sort of alert that pop's up displaying a message that I create and then from the start not even allow that user to move forward.
I'm not sure if I can do this with validation or not. Something like if this user tries to log in, the script dies once it sees that the permission level is at the group 'bench'. Then a pop alert displays saying why.
This is how I allow the user to login..
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('userIndex.php');
} else {
$tryagain = '<span class="signinpanel">' . "The information you entered did not match our records." . '</span>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
I then redirect like this...
if($user->hasPermission('bench')) {
header("Location: http://sundayfundayleague.com");
die();
}
This is my permissions code:
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return true;
}
}
return false;
}
How can I go about doing this?
UPDATE:
I am not sure I am doing this correctly. I'm doing a die with it and showing an error message I made up.
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$permissionError = "Your membership request has not been accepted yet.";
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
if($user->hasPermission('bench')) {
die($permissionError);
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('userIndex.php');
} else {
$tryagain = '<span class="signinpanel">' . "The information you entered did not match our records." . '</span>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
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);