Bulk action in yii Grid View - javascript

I am new to Yii. I need to have a bulk action like bulk delete in CGrid view. I tried by doing in javascript and performing the action using AJAX call. But I dont get what I needed. Please help me solve this.
My view:
<?php $details=$details;
?>
<h3><?php echo $name; ?></h3>
<div id="content" style="margin: 0">
<?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'),
)); ?>
<?php $this->endWidget();?>
<h3><?php echo htmlspecialchars($title); ?></h3>
<h3><?php echo $title; ?></h3>
<div style="padding: 10px;">
<a href="<?php echo $this->createUrl('/Nimsoft/create?id='.$details->host_customer_id);?>" title="Create New Host" class="btn btn-primary circle_ok" style="text-decoration: none;" >Add New Host to Customer</a>
<a href="<?php echo $this->createUrl('/Nimsoft/Search_all?id='.$details->host_customer_id);?>" title="View All Hosts" class="btn btn-primary circle_ok" style="text-decoration: none;" >View All Hosts</a>
<a href="<?php echo $this->createUrl('/Nimsoft/Search_all',array('id'=>$details->host_customer_id,'isXLSDownload'=>1));?>" title="Export" class="btn btn-primary circle_ok" style="text-decoration: none;" >Export</a>
<a href="<?php echo $this->createUrl('/Nimsoft/Search_all',array('id'=>$details->host_customer_id,'isXLSDownload'=>2));?>" title="Export For All Customers" class="btn btn-primary circle_ok" style="text-decoration: none;" >Export For All Customers</a>
<div style="float:right">
<?php
echo CHtml::link('Upload Customer CSV', array('/Nimsoft/uploadCustomers?id='.$details->host_customer_id), array(
'onclick'=>'return hs.htmlExpand(this, { objectType: "iframe", wrapperClassName: "full-size", align: "center" } )',
'class'=>'btn btn-primary',
'id'=>'upload_link',
));
?>
</div>
<?php //echo CHtml::Button('Export CSV', array('class' => 'btn btn-primary circle_ok exportCSV-button'));
echo '<form method="post" name="exportCSV-form" id="exportCSV-form" action="' . yii::app()->createUrl('/export/exportCSV') . '">';
echo '<input type="hidden" name="filename" value="HostName">';
$this->renderPartial('_export_list', array(
'model' => $model,
));
echo '</form>';
?>
<div class="innerLR">
<div class="row-fluid">
<?php
Yii::app()->clientScript->registerScript('search_inc', "
$('.exportCSV-button').click(function() {
$.fn.yiiListView.update('exportListView', {
data: $('#search-pm-form').serialize() + '&export=true',
complete: function() {
$('#exportCSV-form').submit();
}
});
});
");?>
<?php
echo CHtml::button("Add Date Entries",array("id"=>"butt"));
?>
<?php
$obj=$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'yiisession-grid',//'host_grid',
'dataProvider'=>$dataProvider,
'type' => 'striped bordered',
'columns'=>array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn',
'selectableRows'=>2,
),
array( // display 'create_time' using an expression
'name'=>'host_name',
'value'=>'$data->host_name',
),
array(
'name'=>'host_serviceid',
'value'=>'$data->host_serviceid',
),
array(
'name'=>'status',
'value'=>'$data->status',
),
array(
'class'=>'CButtonColumn',
'template'=>'{edit_date}{update}{delete}',
'htmlOptions'=>array('width'=>'95px'),
'buttons' => array(
'edit_date' => array( //the name {reply} must be same
'label' => 'Add Date', // text label of the button
'url' => 'Yii::app()->createAbsoluteUrl("NimsoftHostsDetails/View", array("id"=>$data->host_id))',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/pencil.png', // image URL of the button. If not set or false, a text link is used, The image must be 16X16 pixels
),
),)
),
))
;
?>
</div>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
<div class="separator bottom"></div>
</div>
</div>
<div class="clearfix"></div>
<div id="footer" class="hidden-print">
<?php $this->renderPartial('application.views.layouts._footer_inc'); ?>
</div>
</div>
<script>
hs.preserveContent = false;
hs.dimmingOpacity = 0.75;
hs.zIndexCounter = 10000;
hs.showCredits = false;
// this will disable close when we click on other area than close button
hs.onDimmerClick = function() {
return false;
}
$('.exportCSV-button').click(function() {
$.fn.yiiListView.update('exportListView', {
data: $('#search-faq-form').serialize() + '&export=true',
complete: function() {
$('#exportCSV-form').submit();
}
});
});
</script>
<script type="text/javascript">
var gridId = "yiisession-grid";
$(function(){
$(document).on('click','#yiisession-grid a.bulk-action',function() {
return false;
});
});
function batchActions(values){
var url = $(this).attr('Nimsoft/select_all');
var ids = new Array();
if(values.size()>0){
values.each(function(idx){
ids.push($(this).val());
});
$.ajax({
type: "POST",
url: url,
data: {"ids":ids},
dataType:'json',
success: function(resp){
//alert( "Data Saved: " + resp);
if(resp.status == "success"){
$.fn.yiiGridView.update(gridId);
}else{
alert(resp.msg);
}
}
});
}
}
</script>
<?php
Yii::app()->clientScript->registerScript('edit_date','
$("#butt").click(function(){
var checked=$("#host_grid").yiiGridView("getChecked","host_grid_c1");
var count=checked.length;
if(count>0 && confirm("Do you want to delete these "+count+" item(s)"))
{
$.ajax({
data:{checked:checked},
url:"'.CHtml::normalizeUrl(array('item/remove')).'",
success:function(data){$("#host_grid").yiiGridView("update",{});},
});
}
});
');
?>
My Bulk action code is not working. Please correct me where I went wrong. Thanks in advance.

Answer for yii2:
Checkbox column in a gridview:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'id'=>'grid',
'country',
],
]);
Button that fires a javascript and sends a url like this: index.php?r=mycontroller/bulk&action=1&ids=2,6,7,8
this is the button:
<a href="#" onclick="bulkAction('p');">
this is the Javascript:
<script>
function bulkAction(a) {
var keys = $('#grid').yiiGridView('getSelectedRows');
window.location.href='<?php echo Url::to(['mycontroller/bulk']); ?>&action='+a+'&ids='+keys.join();
}
</script>

Related

Get taxonomy description when filtering custom post type

I'm using a custom post-type and I am doing the filtering using categories.
Each category has a description and I would like to show the description of the category when the category is selected like here
I found a way to show the description of the taxonomy from here
Html used:
<div class="col-lg-9">
<div class="lista-portofoliu">
<div class="row">
<?php while ($pquery->have_posts()) : $pquery->the_post();
$term_obj_list = get_the_terms(get_the_id(), 'portfolio_category');
$term_classes_a = array();
$img_data = array();
$img_string = ""; ?>
<?php foreach ($term_obj_list as $term) {
$term_classes_a[] = $term->slug;
$meniu_triggers[] = $term->slug;
$meniu_labels[] = $term->name;
$img_key = 'imagine_' . $term->slug;
$img_src = wp_get_attachment_image_src(get_field($img_key, get_the_id()), 'thumbnail');
if ($img_src) {
$img_data[] = 'data-' . $img_key . '="' . $img_src[0] . '"';
} else {
$img_data[] = 'data-' . $img_key . '="' . wp_get_attachment_image_src(get_field($img_key, get_the_id()), 'full') . '"';
}
foreach ($img_data as $imagine) :
$img_string .= $imagine;
endforeach;;
} ?>
<?php $term_classes = implode(" ", $term_classes_a); ?>
<div class="col-lg-4 p-1 m-0 item toate <?php echo $term_classes; ?>">
<div class=" item-content" <?php echo $img_string; ?> data-imagine_toate="<?php echo get_the_post_thumbnail_url(get_the_id(), 'thumbnail', true); ?>" style="background-image:url('<?php echo get_the_post_thumbnail_url(get_the_id(), 'thumbnail', true); ?>')">
<a href="<?php the_permalink(); ?>" class=" item-overlay">
<span class="item-title">
<?php the_title(); ?>
<br>
<br>
</span>
</a>
</div>
</div>
<?php endwhile;
?>
<?php
wp_reset_postdata(); ?>
</div>
<button type="button" id="more_posts" class="btn btn-dark loadMore center-block btn-pachete">Mai mult</button>
</div>
</div>
Thank you!
If you want to order everything by portfolio category, then you should first loop over each term in the portfolio_category taxonomy.
With each term, create a new query where you use the tax_query to only get the posts related to the current term we're looping over.
The result will be that each loop contains the category data and the posts related to that category.
You can output the category description by echoing the $term->description value.
<?php
$terms = get_terms('portfolio_category');
if (!is_wp_error($terms)) :
foreach ($terms as $term) : ?>
<div class="row">
<?php
$args = [
'post_type' => 'YOUR_CUSTOM_POST_TYPE',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => [
[
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => $term->term_id
]
]
];
$query = new WP_Query($args);
if ($query->have_posts()) : ?>
<div class="col-lg-4">
<?= $term->name; ?>
<?= $term->description; ?>
</div>
<?php
while ($query->have_posts()) :
$query->the_post(); ?>
<div class="col-lg-4">
<?php the_title(); ?>
</div>
<?php
endwhile
wp_reset_postdata();
endif; ?>
</div>
<?php
endforeach;
endif;

Video popup content - magnific popup

can anyone please help me to make video popup along with the content. I have created custom fields in wordpress and called in my php page and I have also added js code for popup but that is not working as expected. I need video on left and content on right in popup. Below is my code. Please help me in this
<ul class="video-component">
<?php foreach ( $video as $entry ) : ?>
<li>
<div class="video-item">
<a
href="<?= $entry[ 'video_url' ]; ?>"
data-link="<?= $entry[ 'video_url' ]; ?>"
data-description="<?= $entry[ 'video_description' ]; ?>"
data-title="<?= $entry[ 'title' ]; ?>"
class="thumbnail-wrapper"
>
<img
src="<?= $entry[ 'thumb' ][ 'sizes' ][ 'thumbnail-grid-square' ]; ?>"
alt="<?= $entry[ 'thumb' ][ 'alt' ]; ?>"
/>
<div class="desktop-title">
<?php if ( $entry[ 'title' ] ) : ?>
<p class="image-title">
<?= $entry[ 'title' ]; ?>
</p>
<?php endif; ?>
</div>
</a>
</div>
<div class="mobile-info">
<?php if ( $entry[ 'title' ] ) : ?>
<h3>
<?= $entry[ 'title' ]; ?>
</h3>
<?php endif; ?>
<?php if ( $entry[ 'video_description' ] ) : ?>
<p class="description">
<?= $entry[ 'video_description' ]; ?>
</p>
<?php endif; ?>
<?php if ( $entry[ 'video_url' ] ) : ?>
Read more
<?php endif; ?>
</div>
</li>
<?php endforeach; ?>
</ul>
//js code
const $ = require('jquery');
const x = require('magnific-popup');
export default function init() {
$('.video-component').magnificPopup({
delegate: '.thumbnail-wrapper',
type: 'iframe',
disableOn: 783,
gallery: {
enabled: true
},
iframe: {
titleSrc: function (item) {
let title = item.el.attr('data-title'),
description = item.el.attr('data-description'),
link = item.el.attr('data-link'),
btnHtml = '';
return `<h3>${title}</h3><p>${description}</p>`;
}
},
callbacks: {
beforeOpen: function () {
// just a hack that adds mfp-anim class to markup
this.st.iframe.markup = this.st.iframe.markup.replace('mfp-figure', 'mfp-iframe-scaler mfp-with-anim');
this.st.mainClass = 'mfp-3d-unfold';
},
markupParse: function (template, values, item) {
// Triggers each time when content of popup changes
console.log('Parsing:', template, values, item);
},
},
verticalFit: true,
removalDelay: 500,
mainClass: 'mfp-3d-unfold'
});

How to stop a Wordpress ajax load more button from continuously loading the last two posts repeatedly

I set up an ajax load more button in Wordpress. How do I detect that there are no more posts to call and to not reload the same posts? On click it repeatedly grabs the last two posts and loads those. I was having an issue with when posts 3, 4, 5, and 6 were showing initially on the page then clicking the load more button it would call posts 3, 2, and 1 instead of just post 2 and 1. I added an offset of 4. That seems to fix that but it still calls the last two posts if I keep clicking load more. Also is there a way to hide the button if no more posts are detected?
// the pages post query
<?php
$args = array(
'post_type' => 'financial-news',
'post_status' => 'publish',
'posts_per_page' => '4',
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => 1,
);
?>
<?php $my_posts = new WP_Query( $args ); ?>
<?php if ( $my_posts->have_posts() ) : ?>
<?php $wp_query = new WP_Query(); $wp_query->query( $args ); ?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>
<div class="blog-post-wrapper one-column">
<div class="post-inner">
<div class="article-image"><img src="<?php the_field('thumb_image'); ?>"/></div>
<div class="article-copy match-height">
<span class="date"><?php the_time('F j, Y'); ?></span>
<h1><?php the_title(); ?></h1>
<p><?php echo wp_trim_words( get_the_content(), 25, '' ); ?></p>
<p><a class="read_more" href="<?php the_permalink(); ?>">Read More</a></p>
</div><!--article-copy-->
</div>
</div><!--blog-post-wrapper-->
<?php endwhile; ?>
</div><!--blog-content-->
<?php endif; ?>
<?php wp_reset_postdata(); // reset the query ?>
<div class="center-link"><div class="loadmore btn orange-btn-outline">Load More</div></div>
// The jS for the load button
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {
var post_type = 'financial-news';
var posts_per_page = 3;
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>',
'type' : 'post',
'post_type' : post_type,
'posts_per_page': posts_per_page,
};
$.post(ajaxurl, data, function(response) {
$('.blog-content').append(response);
page++;
});
});
});
// the functions.php code to load the posts
// blog load more button
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
$paged = $_POST['page'];
$post_type = $_POST['post_type'];
$posts_per_page = $_POST['posts_per_page'];
$lay_out = $_POST['lay_out'];
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => $posts_per_page,
'offset' => 4,
'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>
<div class="blog-post-wrapper" >
<div <?php post_class('post-inner'); ?> id="post-<?php the_ID(); ?>">
<div class="article-image"><img src="<?php the_field('thumb_image'); ?>"/></div>
<div class="article-copy match-height">
<span class="date"><?php the_time('F j, Y'); ?></span>
<h1><?php the_title(); ?></h1>
<p><?php echo wp_trim_words( get_the_content(), 25, '' ); ?></p>
<p><a class="read_more" href="<?php the_permalink(); ?>">Read More</a></p>
</div><!--article-copy-->
</div>
</div><!--blog-post-wrapper-->
<?php endwhile; ?>
<?php
endif;
wp_die();
}

Bootstrap Search Form in Dropdown

I have a dropdown in my menu but when I click on the search form field inside the dropdown the dropdown instantly closes.
This is my code:
<button id="sharebutton" type="button" class="btn btn-sm btn-info" data-toggle="dropdown" data-hover="dropdown"
data-close-others="true"><i class="fa fa-search"></i> Search
</button>
<ul class="dropdown-menu extended notification">
<li>
<div class="form-group">
<?php echo $this->Form->create('Search', array('controller' => 'searches', 'action' => 'prodsearch')); ?>
<div class="input-group">
<?php echo $this->Form->input('newsearchterm', array('required' => true, 'class' => 'form-control', 'label' => false, 'placeholder' => 'Search Products...', 'name' => 'newsearchterm')); ?>
<span class="input-group-btn">
<?php
echo $this->Form->button(
'<i class="fa fa-search"></i>',
array(
'type' => 'submit',
'class' => 'btn blue',
),
array('escape' => 'false')
);
?>
</span>
</div>
</div>
<?php echo $this->Form->end(); ?>
</li>
</ul>
(I am using CakePHP which is why the form code is a bit funny)
Add stopPropagation() to the your search form field.
jQuery('.your-form-selector').click(function (e) {
e.stopPropagation();
});
Everything else will work as expected.
JQuery reference
I was just looking for the same thing and found it at here
Remove the "li" tags and try. Like this:
<div class="form-group">
<?php echo $this->Form->create('Search', array('controller' => 'searches', 'action' => 'prodsearch')); ?>
<div class="input-group">
<?php echo $this->Form->input('newsearchterm', array('required' => true, 'class' => 'form-control', 'label' => false, 'placeholder' => 'Search Products...', 'name' => 'newsearchterm')); ?>
<span class="input-group-btn">
<?php
echo $this->Form->button(
'<i class="fa fa-search"></i>',
array(
'type' => 'submit',
'class' => 'btn blue',
),
array('escape' => 'false')
);
?>
</span>
</div>
</div>
<?php echo $this->Form->end(); ?>
</ul>
This worked for me once in adding forms in Bootstrap nav dropdowns.

JS Close window on form submission

Update at bottom of post:
I have a page where when a button is pressed, a new window will popup with a form. Below is where I open the popup.
<a><span class="add-on"><i class="icon-plus" style="color: green;" onclick="window.open('<?php echo $this->Html->Url(array('controller' => 'customers', 'action' => 'add?popup')); ?>', 'Add Customer', 'height=630, width=430')"></i></span></a>
When the form is submitted, I need to close that window. The problem I am having now is that the window is closing before the form is fully getting submitted.
Popup Window Code:
<fieldset style="padding-left: 15px;">
<legend>Add Customer</legend>
<?php echo $this->Form->create('Customer', array('inputDefaults' => array('div' => false, 'label' => false))); ?>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<?php echo $this->Form->input('first_name', array('placeholder' => 'First Name')); ?>
</div>
</div>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<?php echo $this->Form->input('last_name', array('placeholder' => 'Last Name')); ?>
</div>
</div>
<div class="input-prepend">
<span class="add-on"><i class="icon-globe"></i></span>
<?php echo $this->Form->input('location', array('placeholder' => 'Location')); ?>
</div>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-phone"></i></span>
<?php echo $this->Form->input('phone_number', array('class' => 'maskedPhone', 'placeholder' => 'Phone Number')); ?>
</div>
</div>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<?php echo $this->Form->input('email', array('placeholder' => 'Email')); ?>
</div>
</div>
<!-- Close Form -->
<?php echo $this->Form->end(array(
'label' => 'Save Customer',
'id' => 'saveCust',
'class' => 'btn btn-primary',
'div' => false
)); ?>
<?php echo $this->Html->script('jquery.maskedinput.min', array('inline' => false));
echo $this->Html->script('maskedinput', array('inline' => false));
$this->start('script'); ?>
<script type="text/javascript">
$(document).ready(function () {
inputs.maskedInputs();
// Get queryString to close popup window
var queryString = window.location.search.substring(1);
if (queryString == "popup"){
$('#CustomerAddForm').submit(function() {
window.close();
});
}
});
</script>
<?php $this->end(); ?>
Trying to use Ajax call now with no luck:
$('#saveCust').click(function() {
alert("test");
$.ajax({
type: "POST",
url: "<?php echo $this->Html->Url(array('controller' => 'Customers', 'action' => 'add')); ?>",
data: $('#CustomerAddForm').serialize(),
success: function(data)
{
alert("Test");
window.close();
}
})
});
return false;
You have a race condition and the window.close will always win. You need to close when the form is DONE submitting.
Either convert it over to use an Ajax call or call the window.close() in the response of the form submission.

Categories