I have add a custom field to get selected IDs using Metabox.
array(
'name' => __('Select projects', 'x2-backend'),
'id' => "{$prefix}similar_projects_list",
'type' => 'select_advanced',
'multiple' => true,
'options' => $pages_clients_list,
),
$args_clients = array(
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'hierarchical' => 1,
'exclude' => $post_id,
'include' => '',
'meta_key' => '',
'meta_value' => '',
'authors' => '',
'child_of' => 0,
'parent' => -1,
'exclude_tree' => '',
'number' => '',
'offset' => 0,
'post_type' => 'room',
'post_status' => 'publish'
);
$pages_clients = get_pages($args_clients);
foreach ($pages_clients as $pages_client) {
if ($pages_client->ID !`enter code here`= '') {
$pages_clients_list[$pages_client->ID] = $pages_client->post_title;
}
}
My view is using backbone js. below is my code.
<script type="text/template" id="villashome-item-tpl-similar-projects">
<article class="promosgrid-el withborder with-buttons <?php echo ($sproject->room_bookonlinelink == '' && $sproject->room_enquiryform != 1 ? 'buttonNotActive' : ''); ?> with-grdient with-overlay">
<h3 class="title">
<a title="<%= md.name %>" href="<%= md.permalink %>"><%= md.name %></a>
</h3>
<h4 class="subtitle"><%= md.secondtext_title %></h4>
<div class="img-cont">
<div class="img-hover-overlay">
<a title="<%= md.seo_title %>" href="<%= md.permalink %>">
<img itemprop="image" alt="" src="<%= md.image_thumb_desktop %>" />
</a>
<a title="<%= md.seo_title %>" href="<%= md.permalink %>">
<div class="img-hover-text"><?php echo ___('+ more info', 'x2-frontend', 'villa_collection_more_info'); ?></div>
</a>
</div>
</div>
</article>
</script>
The loadmore button code is here
<?php
$IDs = get_post_meta( get_the_id() , 'ct_mb_similar_projects_list', false );
$total_rooms = x2_get_similar_projects($IDs);
// var_dump(count($total_rooms));
if ( count($total_rooms)>3 ) { ?>
<div id="villas-load-more-div" class="spacer-el loadmore-wrp">
<a id="villas-load-more" class="btns load-more btn-stroke scrollto-action loadmore-gallery-action" href="#"><?php echo ___('Load more X2 Clients', 'x2-frontend', 'gallery_loadmorephotos_btn'); ?></a>
</div>
<?php } ?>
This button call to the following code in my script.js file
if($('.homepage-villas-similar-projects').length>0){
// $.stellar('refresh');
$('.homepage-villas-similar-projects').easyLoad2({
'tpl_selector':'#villashome-item-tpl-similar-projects',
'loadstep': 3,
'getDataType':'getsimilarprojects',
'offset': 3,
});
}
From this script call getsimilarprojects function in my plugin.js via easyload2 function.
easyload2 function is on my plugin.js
$.fn.easyLoad2 = function (options) {
var el = $(this);
var settings = $.extend({
'tpl_selector': '#blogpost-item-tpl',
'loadstep': 4,
'loadbtn': '.load-more',
'getDataType': 'getposts',
'offset': 0
}, options);
var el_ = $(this);
var jsonurl_ = directory_uri;
var Model = Backbone.Model.extend();
var Collection = Backbone.Collection.extend({
model: Model,
url: jsonurl_
});
var View = Backbone.View.extend({
el: el_,
initialize: function () {
var self = this;
_.each(this.model, function (v, i, l) {
this.template = _.template($(settings.tpl_selector).html(), {md: v});
var d = $(this.template);
self.$el.append(d);
}); $.stellar('refresh');
}
});
var func = {
countData: (settings.offset > 0 ? settings.offset : 0),
myData: '',
step: settings.loadstep,
loadaction: true,
init: function () {
var self = this;
self.scrollTriggers();
if (settings.offset == 0) {
self.data();
}
$('body').on('loadmoredata', function () {
self.data();
});
},
scrollTriggers: function () {
if (this.loadaction === false) {
return;
}
if ($(settings.loadbtn).length === 0) {
$(window).on("scroll", function () {
if (this.loadaction === true) {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$('body').trigger('loadmoredata');
}
}
});
} else {
$(settings.loadbtn).on('click', function (e) {
e.preventDefault();
$('body').trigger('loadmoredata');
});
}
},
setCountData: function () {
this.countData += this.myData.length;
},
data: function () {
var self = this;
var myCollection = new Collection();
myCollection.url = jsonurl_ + '?' + settings.getDataType + '=' + self.countData + '&items=' + self.step;
// console.log(myCollection.url);
myCollection.fetch({success: function () {
self.myData = myCollection.toJSON();
self.setCountData();
self.tpl();
}});
},
tpl: function () {
var self = this;
if (self.myData.length !== self.step) {
self.step = self.myData.length;
}
if (self.myData.length === 0) {
self.loadaction = false;
return;
}
if (self.myData[0].count === void 0) {
} else {
if (self.countData >= self.myData[0].count) {
$(settings.loadbtn).hide();
}
}
var myView = new View({model: self.myData});
var scrolltoElement = el_.find('li').eq(self.countData - self.step);
if (self.countData - self.step > 0) {
setTimeout(function () {
$('body').stop(true, true).scrollTo(scrolltoElement, 700, {axis: 'y', offset: {top: 0}, onAfter: function () {
}});
}, 1000);
}
}
};
func.init();
};
My getsimilarprojects() is here
if ( isset( $_REQUEST['getsimilarprojects'] ) ) {
add_action( 'wp_loaded', 'getsimilarprojects');
}
function getsimilarprojects() {
header('Content-type: application/json');
$offset = $_REQUEST['getsimilarprojects'];
$items = $_REQUEST['items'];
$IDs = get_post_meta( get_the_id() , 'ct_mb_similar_projects_list', false );
$args_rooms_ = array(
'posts_per_page' => -1,
'post_type' => 'room',
'posts_per_page' => ($items == 0)? -1: $items,
'offset' => ($offset == 0) ? 0: $offset,
'orderby' => 'menu_order',
'order' => 'ASC',
'post__in' => $IDs,
);
$rooms_query_ = new WP_Query($args_rooms_);
$ar = array();
$i = 0;
while ($rooms_query_->have_posts()) {
$rooms_query_->the_post();
$x2postmeta_room = setX2Globals(get_the_ID());
$ar[$i]['id'] = get_the_ID();
$ar[$i]['name'] = get_the_title();
$ar[$i]['permalink'] = get_permalink();
$ar[$i]['homepageactive'] = ( $x2postmeta_room->room_homepage_dropdown == 1 ? 1 : 0 );
$ar[$i]['order'] = $x2postmeta_room->room_meta_order;
$ar[$i]['price'] = $x2postmeta_room->room_price;
$ar[$i]['feature_title'] = ( $x2postmeta_room->room_feature_title != '' ? $x2postmeta_room->room_feature_title : get_the_title() );
$ar[$i]['feature_status'] = ( $x2postmeta_room->room_feature_status == 1 ? true : false );
$ar[$i]['image_thumb_desktop'] = getFeaturedImage(get_post_thumbnail_id(), 'x2_thumb_374x270', 'x2_thumb_374x270');
$ar[$i]['seo_title_btn'] = $x2postmeta_room->room_seo_title;
$ar[$i]['count'] = $rooms_query_->found_posts;
$i++;
}
wp_reset_query();
echo json_encode($ar);
die();
}
The problem is I cannot get the $IDs value for 'post__in'.
In this section does not get get_the_id(); value. Why is it? & How can I solve this?
Related
Hi guys i tried many things to solve this but i dont really know how this works.
What i want:
-Change the list of operators after change the fieldcampaign (done).
-Change the value typeform from text to filetype and from filetype to texttype depending of which operator i select.
Persist whats inside the value input if its a texttype.
This is my Form
namespace App\Form\Type;
class FiltercampaignvalueType extends AbstractType
{
private $campaign;
private $filtergroup;
private $class;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->campaign = $options['attr']['campaign'];
$this->filtergroup = $options['attr']['filtergroup'];
$this->class = 'row';
// dd($this);
$builder->add('fieldcampaign', EntityType::class, array(
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.campaign = :campaign')
->setParameter('campaign', $this->campaign)
->orderBy('u.name', 'ASC');
},
'class' => Fieldcampaign::class,
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'label' => false,
'placeholder' => 'Choose a field',
'attr' => array(
'class' => 'fieldcampaign_select',
'onchange' => 'return preseclet(this);'
)
)
);
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
// checks if the Product object is "new"
// If no data is passed to the form, the data is "null".
// This should be considered a new "Product"
if (!$data || null === $data->getId()) {
$form->add('operator', EntityType::class, array(
'class' => Operator::class,
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'label' => false,
'placeholder' => 'Choose an operator'
)
);
}
// dd($event->getForm(), $event->getData());
});
$formModifier = function (FormInterface $form, Fieldtype $type = null) {
//$positions = null === $sport ? [] : $sport->getAvailablePositions();
$form->add('operator', EntityType::class, array(
'class' => Operator::class,
'query_builder' => function (EntityRepository $er) use ($type) {
return $er->createQueryBuilder('u')
->where('u.fieldtype = :fieldtype')
->setParameter('fieldtype', $type);
//->orderBy('u.name', 'ASC');
},
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'label' => false,
'placeholder' => 'Choose an operator'
)
);
};
$builder->add('value', TextType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert value')
)
);
$builder->add('filtercampaigngroup', EntityType::class, array(
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.id = :id')
->setParameter('id', $this->filtergroup)
->orderBy('u.name', 'ASC');
},
'class' => Filtercampaigngroup::class,
'label' => false,
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
'attr' => array(
'readonly' => true,
)
)
);
$value="";
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
if($data !== null) {
if($data->getOperator() !== null) {
if ($data->getOperator()->getId() == 26 || $data->getOperator()->getId() == 25){
$value="file";
/* $builder->add('value', TextType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert value')
)
);*/
}else{
$value = "number";
}
$formModifier($event->getForm(), $data->getOperator()->getFieldtype());
} else {
$formModifier($event->getForm(), null);
}
} else {
$formModifier($event->getForm(), $data);
}
}
);
if ($value == "file"){
$builder->add('value', FileType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert File')
)
);
}else{
$builder->add('value', TextType::class, array (
'label' => 'Value',
'required' => false,
'label' => false,
'attr' => array(
'placeholder' => 'Insert value')
)
);
}
$builder->get('fieldcampaign')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$type = $event->getForm()->getData()->getType();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $type);
}
);
/* $builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$data = $event->getData();
//var_dump($data['company']);
//var_dump($company);
//$formModifierOffer($event->getForm(), $data['company']);
/* if(array_key_exists('company', $data)) {
$formModifierOffer($event->getForm(), $data['company']);
}
if(array_key_exists('name', $data)) {
$formModifierAction($event->getForm(), $data['name']);
}
if(array_key_exists('action', $data)) {
$formModifierPrice($event->getForm(), $data['action']);
}
});
*/
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Filtercampaign::class,
'csrf_protection' => false,
]);
}
}
My twig:
{% extends 'index.html.twig' %}
{% block body %}
<div class="col-sm-12">
<div class="row">
<h2>{{section.action|capitalize}} {{section.title}}</h2>
<div id="result"></div>
</div>
<div id="filternav" class="row">
<div>
<a class="btn btn-outline-secondary btn-sm" href="../">◄ Back</a>
</div>
</div>
<div class="col-sm-12">
{% form_theme form 'bootstrap_singlelinecollection_layout.html.twig' %}
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</div>
</div>
<script>
var $collectionHolder;
// setup an "add a tag" link
var $addTagButton = $('<button type="button" class="btn btn-default add_tag_link"><span class="glyphicon glyphicon-plus"><i class="fas fa-plus"></i></span></button>');
var $newLinkLi = $('.multiple').append($addTagButton);
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('div.multiple');
// add the "add a tag" anchor and li to the tags ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagButton.on('click', function(e) {
// add a new tag form (see next code block)
addTagForm($collectionHolder, $newLinkLi);
});
// add a delete link to all of the existing tag form li elements
$collectionHolder.find('>.form-group').each(function() {
addTagFormDeleteLink($(this));
});
//addTagFormDeleteLink($newFormLi);
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<div class="col-sm-1 float-left"><button type="button" class="btn btn-default remove_tag_link"><span class="glyphicon glyphicon-minus"><i class="fas fa-minus"></i></span></button></div>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
});
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
var newForm = prototype;
// You need this only if you didn't set 'label' => false in your tags field in TaskType
// Replace '__name__label__' in the prototype's HTML to
// instead be a number based on how many items we have
// newForm = newForm.replace(/__name__label__/g, index);
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
newForm = newForm.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<div></div>').append(newForm);
console.log($newLinkLi);
$newLinkLi.after($newFormLi);
//preseclet();
/*$newFormLi[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].addEventListener('change',function(){
var data = {};
data[this.name] = this.value;
console.log(data);
var $form = $(this).closest('form');
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#form_filters_0_fieldcampaign').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#form_filters_0_fieldcampaign')
);
// Position field now displays the appropriate positions.
}
});
});*/
//console.log($newFormLi[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0]);
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<div class="col-sm-1 float-left"><button type="button" class="btn btn-default remove_tag_link"><span class="glyphicon glyphicon-minus"><i class="fas fa-minus"></i></span></button></div>');
$tagFormLi.children()[0].append($removeFormButton[0]);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
addTagFormDeleteLink($newFormLi);
}
</script>
<script>
function preseclet(field) {
var form = field.closest('form');
var data = {};
data[field.name] = field.value;
console.log(form.method)
// Submit data via AJAX to the form's action path.
$.ajax({
url : form.action,
type: form.method,
data : data,
success: function(html) {
//$element.parent().parent().replaceWith(
field.parentNode.parentNode.replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#form_filters')[0]
);
// Position field now displays the appropriate positions.
document.getElementById("form_filters_0_operator").addEventListener("change", changeValueField)
}
});
}
valuefield()
function valuefield(){
if (typeof document.getElementById("form_filters_0_operator") == "object"){
//console.log(document.getElementById("form_filters_0_operator").value);
//document.getElementById("form_filters_0_operator").onchange = function(){changeValueField};
document.getElementById("form_filters_0_operator").addEventListener("change", changeValueField)
}
}
function changeValueField(){
console.log( document.getElementById("form_filters_0_operator").value);
if(document.getElementById("form_filters_0_operator").value == 25 || document.getElementById("form_filters_0_operator").value == 26){
document.getElementById("form_filters_0_value").type = "file";
}else {
document.getElementById("form_filters_0_value").type = "text";
}
}
if(document.getElementById("form_filters_0_operator").value == 25 || document.getElementById("form_filters_0_operator").value == 26){
document.getElementById("form_filters_0_value").type = "file";
}else {
document.getElementById("form_filters_0_value").type = "text";
}
</script>
{% endblock %}
The function on the controller(dont think is gonna be usefull but just in case):
public function create2(Request $request, $id) {
$this->section->action = 'create';
$em = $this->getDoctrine()->getManager();
$filtergroup = $this->getDoctrine()->getRepository(Filtercampaigngroup::class)->findOneById($id);
$campaign = $filtergroup->getCampaign();
$boolean = $filtergroup->getBoolean();
if($boolean == 0) {
$b = 'AND';
} elseif($boolean == 1) {
$b = 'OR';
} else {
$b = 'NOT';
}
$this->section->title = 'Filter #' . $id . ' ('.$b.')';
$filters = $filtergroup->getFilters();
if ($filters->isEmpty()) {
$filter = new Filtercampaign;
$filtergroup->addFilter($filter);
}
$form = $this->createFormBuilder($filtergroup)
->add('filters', CollectionType::class, array(
'entry_type' => FiltercampaignvalueType::class,
'entry_options' => array(
'label' => false,
'attr' => array(
'campaign' => $campaign->getId(),
'filtergroup' => $filtergroup->getId()
)
),
'by_reference' => true,
'allow_add' => true,
'allow_delete' => true,
'attr' => array('class'=>'multiple inline')
))
/* ->add('testfield', \Symfony\Component\Form\Extension\Core\Type\FileType::class, array(
"mapped"=> false
))*/
->add('save', SubmitType::class, array('label' => ucfirst($this->section->action) . ' ' . ucfirst($this->section->title)))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entity = $form->getData();
$em->persist($entity);
$em->flush();
$this->addFlash(
'success',
'Filter #'.$id.' edited!'
);
return $this->redirectToRoute('admin_campaign_filter');
}
return $this->render('project_field.html.twig', array(
'form' => $form->createView(),
'section' => $this->section
));
}
Any type of help is welcomed cause im so so so so so so so so so lost
There is a working AJAX pagination with custom posts. But when you select a category the pagination switches the posts, but automatically selects the first page in the pagination page selection. How do I fix it? All the files below.
page-ajax-pagination.php
<section class="navigation-ajax-taxonomy">
<div class="container">
<div class="row">
<div class="col-12">
<div class="taxonomy-list">
<?php
if ($terms = get_terms(array('taxonomy' => 'types_of_elements', 'orderby' => 'name'))) :
echo '<a class="taxonomy-list__item active" href="#!" data-category="">' . esc_html__("ALL", "default") . '</a>';
foreach ($terms as $term) :
echo '<a class="taxonomy-list__item" href="#!" data-category="' . $term->slug . '">' . $term->name . '</a>';
endforeach;
endif;
?>
</di
</div>
</div>
</section>
<?php
$elements_args = array(
'post_type' => 'element',
'posts_per_page' => 1,
'order' => 'ASC',
'orderby' => 'title'
);
$elements = new WP_Query($elements_args); ?>
<?php if ($elements->have_posts()) : ?>
<section class="more-with-cat">
<div class="container">
<div class="row" id="ajax-pagination">
<?php while ($elements->have_posts()) :
$elements->the_post() ?>
<div class="col-12 col-md-6 col-lg-3 p-2">
<?php get_template_part('parts/loop', 'element'); ?>
</div>
<?php endwhile;
wp_reset_postdata(); ?>
</div>
<ul id="js-pagination" class="blog__pagination" data-max-pages="<?php echo $elements->max_num_pages; ?>"></ul>
</div>
</section>
<?php endif; ?>
<?php get_footer(); ?>
ajax_callback.php
function loadmore_pagination_ajax()
{
$response = [
'template' => '',
];
$tax = isset($_GET['value']) ? $_GET['value'] : '';
$page = (isset($_GET['paged'])) ? $_GET['paged'] : 1;
$elements_args = [
'post_type' => 'element',
'posts_per_page' => 1,
'paged' => $page,
'order' => 'ASC',
'orderby' => 'title',
];
if (!empty($tax)) {
$elements_args['tax_query'] = [
[
'taxonomy' => 'types_of_elements',
'field' => 'slug',
'terms' => $tax,
]
];
}
$elements = new WP_Query($elements_args);
if ($_GET['value'] !== '') {
$response['total'] = $elements->max_num_pages;
}
if ($elements->have_posts()) :
while ($elements->have_posts()) :
$elements->the_post();
$response['template'] .= '<div class="col-12 col-md-6 col-lg-3 p-2">';
$response['template'] .= return_template('loop-element');
$response['template'] .= ' </div>';
endwhile;
endif;
wp_reset_query();
wp_send_json($response);
}
add_action('wp_ajax_nopriv_loadmore_pagination_ajax', 'loadmore_pagination_ajax');
add_action('wp_ajax_loadmore_pagination_ajax', 'loadmore_pagination_ajax');
main.js
/**
* AJAX PAGINATION (page-ajax-pagination.php)
*/
function loadPaginationPosts(value, page) {
$.ajax({
type: 'GET',
dataType: 'json',
url: wpAjax.ajaxurl,
data: {
action: 'loadmore_pagination_ajax',
value: value,
paged: page,
},
}).done(function (response) {
$('#ajax-pagination').html(response.template);
if (response.total) {
blogPagination(value, response.total);
}
});
}
/**
* CUSTOM PAGINATION
*/
function blogPagination(currentFilter, totalPages) {
$('#js-pagination').pagination({
total: totalPages,
current: 1,
length: 1,
size: 2, // Prev/Next text
prev: 'Previous',
next: 'Next',
// fired on each click
click: function (e) {
loadPaginationPosts(currentFilter, e.current);
console.log(e.current);
},
});
}
$('.taxonomy-list__item').on('click', function () {
$('.taxonomy-list__item').removeClass('active');
$(this).addClass('active');
loadPaginationPosts($(this).data('category'), 1);
blogPagination(currentFilter, totalPages);
});
// Init Pagination
let currentFilter = $('.taxonomy-list').find('.active').data('category');
let totalPages = parseInt($('#js-pagination').attr('data-max-pages'));
blogPagination(currentFilter, totalPages);
pagination.js
/*!
* Pagination v1.4.1 (https://github.com/nashaofu/pagination)
* Copyright 2016 nashaofu
* Licensed under MIT
*/
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof define === 'function' && define.cmd) {
// eslint-disable-next-line no-unused-vars
define(function (require, exports, module) {
factory(require('jquery'));
});
} else {
factory(jQuery);
}
})(function ($) {
'use strict';
var Pagination = function ($target, options) {
this.$target = $target;
this.options = $.extend(
{},
Pagination.DEFAULTS,
this.$target.data('pagination'),
typeof options == 'object' && options
);
this.init();
};
Pagination.VERSION = '1.4.0';
Pagination.DEFAULTS = {
total: 1,
current: 1,
length: 10,
size: 2,
prev: '<',
next: '>',
// eslint-disable-next-line no-unused-vars
click: function (e) {},
};
Pagination.prototype = {
init: function () {
if (this.options.total < 1) {
this.options.total = 1;
}
if (this.options.current < 1) {
this.options.current = 1;
}
if (this.options.length < 1) {
this.options.length = 1;
}
if (
this.options.current >
Math.ceil(this.options.total / this.options.length)
) {
this.options.current = Math.ceil(
this.options.total / this.options.length
);
}
if (this.options.size < 1) {
this.options.size = 1;
}
if ('function' === typeof this.options.ajax) {
var me = this;
this.options.ajax(
{
current: me.options.current,
length: me.options.length,
total: me.options.total,
},
function (options) {
return me.refresh(options);
},
me.$target
);
} else {
this.render();
}
this.onClick();
},
render: function () {
var options = this.options,
$target = this.$target;
$target.empty();
// 上一页
$target.append(
'<li><a herf="javascript:void(0)" data-page="prev">' +
options.prev +
'</a></li>'
);
var page = this.getPages();
if (page.start > 1) {
$target.append(
'<li><a herf="javascript:void(0)" data-page="' +
1 +
'">' +
1 +
'</a></li>'
);
$target.append('<li><span>...</span></li>');
}
for (var i = page.start; i <= page.end; i++) {
$target.append(
'<li><a herf="javascript:void(0)" data-page="' +
i +
'">' +
i +
'</a></li>'
);
}
if (page.end < Math.ceil(options.total / options.length)) {
$target.append('<li><span>...</span></li>');
$target.append(
'<li><a herf="javascript:void(0)" data-page="' +
Math.ceil(options.total / options.length) +
'">' +
Math.ceil(options.total / options.length) +
'</a></li>'
);
}
$target.append(
'<li><a herf="javascript:void(0)" data-page="next">' +
options.next +
'</a></li>'
);
$target
.find('li>a[data-page="' + options.current + '"]')
.parent()
.addClass('active');
if (options.current <= 1) {
$target.find('li>a[data-page="prev"]').parent().addClass('disabled');
}
if (options.current >= Math.ceil(options.total / options.length)) {
$target.find('li>a[data-page="next"]').parent().addClass('disabled');
}
},
getPages: function () {
// eslint-disable-next-line no-unused-vars
var $target = this.$target,
options = this.options,
start = options.current - options.size,
end = options.current + options.size;
if (
options.current >=
Math.ceil(options.total / options.length) - options.size
) {
start -=
options.current -
Math.ceil(options.total / options.length) +
options.size;
}
if (options.current <= options.size) {
end += options.size - options.current + 1;
}
if (start < 1) {
start = 1;
}
if (end > Math.ceil(options.total / options.length)) {
end = Math.ceil(options.total / options.length);
}
var pages = {
start: start,
end: end,
};
return pages;
},
onClick: function () {
var $target = this.$target,
options = this.options,
me = this;
// eslint-disable-next-line no-unused-vars
$target.off('click');
// eslint-disable-next-line no-unused-vars
$target.on('click', '>li>a[data-page]', function (e) {
if (
$(this).parent().hasClass('disabled') ||
$(this).parent().hasClass('active')
) {
return;
}
var button = $(this).data('page');
switch (button) {
case 'prev':
if (options.current > 1) {
options.current--;
}
break;
case 'next':
if (options.current < Math.ceil(options.total)) {
options.current++;
}
break;
default:
button = parseInt(button);
if (!isNaN(button)) {
options.current = parseInt(button);
}
break;
}
var temp = {
current: options.current,
length: options.length,
total: options.total,
};
if ('function' === typeof options.ajax) {
options.ajax(
temp,
function (options) {
return me.refresh(options);
},
$target
);
} else {
me.render();
}
options.click(temp, $target);
});
},
refresh: function (options) {
if ('object' === typeof options) {
if (options.total) {
this.options.total = options.total;
}
if (options.length) {
this.options.length = options.length;
}
}
this.render();
},
};
$.fn.pagination = function (options) {
this.each(function () {
$(this).data('pagination', new Pagination($(this), options));
});
return this;
};
});
functions.php
wp_localize_script(
'main.js',
'wpAjax',
[
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('project_nonce'),
]
);
When I click on pagination link (page number) it gives me post_type, taxonomy, term_name. I passed the variables with JQuery Variables to Ajax wordpress function. The Ajax function is receiving the vaiables. But WP_Query loop does not work with the passed data.
JavaScript Code:
<script>
$(".category--pagination").on("click", "a", function (e) {
e.preventDefault();
var link = $(this).attr("href");
if (link.indexOf("/page/") >= 0) {
brands_page = parseInt(link.substr(link.indexOf("/page/") + 6, 4));
} else {
brands_page = 1;
}
mzm_filter_taxonomy();
});
// mzm_filter_tax
function mzm_filter_taxonomy() {
$("#brandCategoryItemDisplay").addClass("loading");
var post_type = $("#post_type").val();
var taxonomy = $("#taxonomy").val();
var term_slug = $("#term_slug").val();
var term_name = $("#term_name").val();
//console.log(post_type);
// console.log(taxonomy);
// console.log(term_name);
if (brands_page == undefined) {
brands_page = 1;
}
var data = {
action: "mzm_filter_taxonomy",
post_type: post_type,
taxonomy:taxonomy,
term_slug:term_slug,
term_name:term_name,
page:brands_page,
};
$.post(mzm_filter.ajax_url, data, function (response, textStatus, jqXHR) {
if (response.success) {
console.log("executed success");
$("#brandCategoryItemDisplay").removeClass("loading");
$("#brandCategoryItemDisplay").html(response.data.items);
$(".category--pagination").html(response.data.pagination);
//$("#taxonomy_pagination").html(response.data.pagination);
}
});
}
</script>
Wordpress Ajax Function:
function mzm_filter_taxonomy()
{
$post_type = isset($_POST['post_type']) ? filter_var(trim($_POST['post_type']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$taxonomy = isset($_POST['taxonomy']) ? filter_var(trim($_POST['taxonomy']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$term_slug = isset($_POST['term_slug']) ? filter_var(trim($_POST['term_slug']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$term_name = isset($_POST['term_name']) ? filter_var(trim($_POST['term_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
$perpage = mzm_brand_perpage();
$paged = (isset($_POST['page']) && intval($_POST['page'])) ? intval($_POST['page']) : 1;
// $sort = ( isset( $_POST['sort'] ) && intval( $_POST['sort'] ) ) ? intval( $_POST['sort'] ) : 1;
// $sort = (isset($_POST['sort'])) ? intval($_POST['sort']) : 1;
// $args = array(
// 'post_type' => $post_type,
// 'hide_empty' => false,
// 'posts_per_page' => $perpage,
// 'paged' => $paged,
// 'post_status' => 'publish',
// 'tax_query' => array(
// array (
// 'taxonomy' => $taxonomy,
// 'field' => 'slug',
// 'terms' => $term_slug,
// )
// ),
// );
$the_query = new WP_Query( array(
'post_type' => $post_type,
'tax_query' => array(
array (
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term_slug,
)
),
) );
// $the_query = new WP_Query($args);
ob_start();
// echo $post_type . '<br>';
// echo $taxonomy . '<br>';
// echo $term_name . '<br>';
// echo $term_slug . '<br>';
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
the_post();
// echo mzm_render_single_brand_card();
echo the_title();
}
wp_reset_postdata();
} else {
echo '<div class="no-criteria-search">Sorry, no posts matched your criteria.</div>';
}
$html = ob_get_clean();
$result = array(
'items' => $html,
'pagination' => 'mzm_render_pagination($the_query)',
);
wp_send_json_success($result);
}
add_action('wp_ajax_nopriv_mzm_filter_taxonomy', 'mzm_filter_taxonomy');
add_action('wp_ajax_mzm_filter_taxonomy', 'mzm_filter_taxonomy');
I am trying paginate via Ajax request. Other all scripts are working. But this is a single taxonomy page. On this page the loop doesn't executes. It gives server error 500.
I solved it myself.
The problem was in wp_query loop. I using custom $args and the loop object was $the_query.
So,
the_post();
//should be
$the_query->the_post();
I am create widget in magento 2.3 that extend funcitonality of vendor Catalog List Product. By default Catalog List Product (CLP) does not allow to create and handle several condition control on same page. My widget allow to create several condition control.
Technically each my conditions control open in new modal window.
When the user need to create condition then he must click on button named "Choose"
Modal window opens and user set the conditions. When the user configures and ready to save condition then he click to button named "Save" on modal window ajax request sending to server and server respond decoded value to parent form input. The user close modal window and click on Save button on parent form. Widget saved. All done. Everything is right until this step:
When user want to edit saved widget and opens modal window saved data converts to aplicable form by another ajax and jQuery Prepend newchild
< li >
to < ul >
But prepended data becomes not interactable- user cannot edit and delete loaded rule.
widget.xml
<parameter name="cond1" xsi:type="block" visible="true" required="false">
<label translate="true">First Conditions</label>
<block class="MonteShot\MegaWidget\Block\Adminhtml\Conditions\Conditions">
<data>
<item name="condition" xsi:type="array">
<item name="id1" xsi:type="string" translate="true">1</item>
</item>
</data>
</block>
</parameter>
MonteShot\MegaWidget\Block\Adminhtml\Conditions\Conditions
<?php
namespace MonteShot\MegaWidget\Block\Adminhtml\Conditions;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Widget\Block\BlockInterface;
/**
* Class Conditions
*/
class Conditions extends Generic implements TabInterface, BlockInterface
{
/**
* Conditions constructor.
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Framework\Data\FormFactory $formFactory
* #param \Magento\Rule\Block\Conditions $conditions
* #param \Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset
* #param \Magento\Framework\Registry $coreRegistry
* #param \MonteShot\MegaWidget\Model\RuleFactory $ruleModelFactory
* #param \Magento\CatalogWidget\Model\RuleFactory $ruleFactory
* #param \Magento\Widget\Helper\Conditions $conditionsHelper
* #param \Magento\Cms\Model\PageFactory $pageFactory
* #param \Magento\Framework\App\Response\Http $response
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Rule\Block\Conditions $conditions,
\Magento\Backend\Block\Widget\Form\Renderer\Fieldset $rendererFieldset,
\Magento\Framework\Registry $coreRegistry,
\MonteShot\MegaWidget\Model\RuleFactory $ruleModelFactory,
\Magento\CatalogWidget\Model\RuleFactory $ruleFactory,
\Magento\Widget\Helper\Conditions $conditionsHelper,
\Magento\Cms\Model\PageFactory $pageFactory,
\Magento\Framework\App\Response\Http $response,
array $data = []
)
{
$this->response = $response;
$this->conditionsHelper = $conditionsHelper;
$this->ruleFactory = $ruleFactory;
$this->ruleModelFactory = $ruleModelFactory;
$this->_pageFactory = $pageFactory;
$this->coreRegistry = $coreRegistry;
$this->rendererFieldset = $rendererFieldset;
$this->conditions = $conditions;
parent::__construct($context, $coreRegistry, $formFactory, $data);
}
/**
* {#inheritdoc}
*/
public function getTabLabel()
{
return __('Conditions');
}
/**
/**
* #param \Magento\Framework\Data\Form\Element\AbstractElement $element
* #return \Magento\Framework\Data\Form\Element\AbstractElement
* #throws \Magento\Framework\Exception\LocalizedException
*/
public function prepareElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$uniqId = $this->mathRandom->getUniqueHash($element->getId());
$sourceUrl = $this->getUrl(
'megawidget/conditions_rule_conditioncontent/conditionpagecontroller',
[
'name' => $element->getData('name'),
'uniq_id' => $uniqId,
'button_num' => $this->getData('condition')[key($this->getData('condition'))]
]);
$chooser = $this->getLayout()->createBlock(
\MonteShot\MegaWidget\Block\Adminhtml\Widget\Chooser::class
)->setElement(
$element
)->setConfig(
$this->getConfig()
)->setFieldsetId(
$this->getFieldsetId()
)->setSourceUrl(
$sourceUrl
)->setUniqId(
$uniqId
)->setValue($this->getData('condition')[key($this->getData('condition'))]);
if ($element->getValue()) {
$page = $this->_pageFactory->create()->load((int)$element->getValue());
if ($page->getId()) {
$chooser->setLabel($this->escapeHtml($page->getTitle()));
}
}
$element->setData('after_element_html', $chooser->toHtml());
return $element;
}
/**
* Prepare form before rendering HTML
*
* #return Generic
* #throws \Magento\Framework\Exception\LocalizedException
*/
protected function _prepareForm()
{
$model = $this->ruleFactory->create();
// $model = $this->ruleModelFactory->create();
$id = $this->_request->getParam('uniq_id');
$name = $this->_request->getParam('name');
$cuttedName = trim(str_replace('parameters', '', $name), '[]');
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form_modal',
'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
[
'uniq_id' => $this->_request->getParam('uniq_id'),
'button_num' => $this->_request->getParam('button_num'),
'name' => $this->_request->getParam('name'),
]),
'method' => 'post',
],
]
);
$form->setUseContainer(true);
$form->setHtmlIdPrefix('rule_');
$this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
$renderer = $this->rendererFieldset->setTemplate(
'Magento_CatalogRule::promo/fieldset.phtml'
)->setNewChildUrl(
$this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
);
$fieldset = $form->addFieldset(
'conditions_fieldset',
[
'legend' => __(
'Apply the rule only if the following conditions are met (leave blank for all products).'
)
]
)->setRenderer(
$renderer
);
// $model->getConditions()->setJsFormObject('rule_conditions_fieldset');
// $model->setData('element_value', substr_replace($_POST['element_value'], '', 0, 26));
$model->getConditions()->setJsFormObject('rule_conditions_fieldset');
$fieldset->addField(
'conditions',
'text',
['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions')]
)->setRule(
$model
)->setRenderer(
$this->conditions
);
$label = $id . 'label';
$valueId = $id . 'value';
$fieldset->addField(
'button-save',
'hidden',
['name' => 'select',
'label' => __('Save condition'),
'title' => __('Save condition'),
'class' => 'action-close',
'data-role' => 'closeBtn',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
],
'after_element_html' => '
<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){
jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {
var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '",
data: { form_key: window.FORM_KEY,serializedArray:serArr},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery("input[name=\'' . $name . '\']")[0].value=response.data;
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$fieldset->addField(
'script-area',
'hidden',
['name' => 'select',
'class' => 'script-area-hidden',
'data_attribute' => [
'mage-init' => ['hidden' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
],
'after_element_html' => '
<script>
require([\'jquery\',\'jqueryForm\'],
function ($,jqueryForm){
jQuery(document).ready(function (jQuery) {
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset") . '",
data: {JsonToHtml:jQuery("input[name=\'' . $name . '\']")[0].value, form: window.FORM_KEY},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery(document.querySelector("#conditions__1__children")).prepend(response.data);
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
// $model->getConditions()->setJsFormObject('rule_conditions_fieldset');
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
}
//Magento\Widget\Helper\Conditions encode when save button has been pressed
And code in modal window
$model = $this->ruleFactory->create();
// $model = $this->ruleModelFactory->create();
$id = $this->_request->getParam('uniq_id');
$name = $this->_request->getParam('name');
$cuttedName = trim(str_replace('parameters', '', $name), '[]');
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form_modal',
'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
[
'uniq_id' => $this->_request->getParam('uniq_id'),
'button_num' => $this->_request->getParam('button_num'),
'name' => $this->_request->getParam('name'),
]),
'method' => 'post',
],
]
);
$form->setUseContainer(true);
$form->setHtmlIdPrefix('rule_');
$this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
$renderer = $this->rendererFieldset->setTemplate(
'Magento_CatalogRule::promo/fieldset.phtml'
)->setNewChildUrl(
$this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
);
$fieldset = $form->addFieldset(
'conditions_fieldset',
[
'legend' => __(
'Apply the rule only if the following conditions are met (leave blank for all products).'
)
]
)->setRenderer(
$renderer
);
// $model->getConditions()->setJsFormObject('rule_conditions_fieldset');
// $model->setData('element_value', substr_replace($_POST['element_value'], '', 0, 26));
$model->getConditions()->setJsFormObject('rule_conditions_fieldset');
$fieldset->addField(
'conditions',
'text',
['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions')]
)->setRule(
$model
)->setRenderer(
$this->conditions
);
// $fieldset->addElement($this->getLayout()->createBlock(\MonteShot\MegaWidget\Renderer\Conditions::class));
$label = $id . 'label';
$valueId = $id . 'value';
$fieldset->addField(
'button-save',
'hidden',
['name' => 'select',
'label' => __('Save condition'),
'title' => __('Save condition'),
'class' => 'action-close',
'data-role' => 'closeBtn',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
],
'after_element_html' => '
<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){
jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {
var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '",
data: { form_key: window.FORM_KEY,serializedArray:serArr},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery("input[name=\'' . $name . '\']")[0].value=response.data;
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$fieldset->addField(
'script-area',
'hidden',
['name' => 'select',
'class' => 'script-area-hidden',
'data_attribute' => [
'mage-init' => ['hidden' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
],
'after_element_html' => '
<script>
require([\'jquery\',\'jqueryForm\'],
function ($,jqueryForm){
jQuery(document).ready(function (jQuery) {
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset") . '",
data: {JsonToHtml:jQuery("input[name=\'' . $name . '\']")[0].value, form: window.FORM_KEY},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery(document.querySelector("#conditions__1__children")).prepend(response.data);
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
PrepareData Controller
<?php
/**
* Copyright (c) 2019. MonteShot
*/
namespace MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule;
use Magento\Framework\Json\Helper\Data as JsonHelper;
/**
* Class PrepareData
*/
class PrepareData extends \MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule
{
/**
* #param \Magento\Backend\App\Action\Context $context
* #param \Magento\Framework\Registry $coreRegistry
* #param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
* #param \Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter
* #param \MonteShot\MegaWidget\Model\RuleFactory $ruleFactory
* #param \Magento\Widget\Helper\Conditions $conditionsHelper
* #param \Psr\Log\LoggerInterface $logger
* #param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* #param JsonHelper $jsonHelper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
\MonteShot\MegaWidget\Model\RuleFactory $ruleFactory,
\Magento\Widget\Helper\Conditions $conditionsHelper,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
JsonHelper $jsonHelper
)
{
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->conditionsHelper = $conditionsHelper;
parent::__construct($context, $coreRegistry, $fileFactory, $dateFilter, $ruleFactory, $logger);
}
/**
* #return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void
*/
public function execute()
{
if (!$this->getRequest()->getPostValue()) {
$this->_redirect('megawidget/*/');
}
try {
$serializedConditionArray =
$this->conditionsHelper->decode($this->getRequest()->getParam('serializedArray'));
$templateArray = [];
foreach ($serializedConditionArray as $index => $singleArrItem) {
if ($singleArrItem['name'] == 'form_key') {
unset($serializedConditionArray[$index]);
continue;
}
if ($singleArrItem['name'] == 'select') {
unset($serializedConditionArray[$index]);
continue;
}
if (!empty($templateArray[str_replace('rule', '', $singleArrItem['name'])])) {
$templateArray[str_replace('rule', '', $singleArrItem['name'])] .= ',' . $singleArrItem['value'];
} else {
$templateArray[str_replace('rule', '', $singleArrItem['name'])] = $singleArrItem['value'];
}
//$templateArray[str_replace('rule', '', $singleArrItem['name'])] = $singleArrItem['value'];
}
$finalArr = [];
foreach ($templateArray as $index => $data) {
$indexName = $this->get_string_between(str_replace('[conditions]', '', $index), '[', ']');
$paramName = $this->get_string_between(str_replace('[conditions][' . $indexName . ']', '', $index), '[', ']');
$multiValue = str_replace('parameters[conditions][' . $indexName . ']' . '[' . $paramName . ']', '', $index);
if ($paramName == 'value' && strpos($data, ',')) {
$finalArr[$indexName][$paramName] = [$data];
} else {
$finalArr[$indexName][$paramName] = $data;
}
if ($paramName == 'value' && $multiValue == '[]') {
if ($finalArr[$indexName][$paramName]) {
if ($finalArr[$indexName][$paramName]) {
$temp = $finalArr[$indexName][$paramName];
unset($finalArr[$indexName][$paramName]);
$finalArr[$indexName][$paramName][0] = $data;
} else {
$finalArr[$indexName][$paramName][0] .= ',' . $data;
}
} else {
$finalArr[$indexName][$paramName][0] = [$data];
}
}
}
$this->data = $this->conditionsHelper->encode($finalArr);
$this->message = 'success';
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
$id = (int)$this->getRequest()->getParam('rule_id');
if (!empty($id)) {
$this->_redirect('megawidget/*/edit', ['id' => $id]);
} else {
$this->_redirect('megawidget/*/new');
}
return;
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the rule data. Please review the error log.')
);
$this->error = $e->getMessage();
$this->message = 'success';
$this->logger->critical($e);
$data = !empty($data) ? $data : [];
$this->_session->setPageData($data);
$this->_redirect('megawidget/*/edit', ['id' => $this->getRequest()->getParam('rule_id')]);
return;
}
$resultJson = $this->resultJsonFactory->create();
$resultData = substr(substr($this->jsonHelper->jsonEncode($this->data), 1), 0, -1);
return $resultJson->setData([
'message' => $this->message,
'data' => $resultData,
'error' => $this->error
]);
}
protected function get_string_between($string, $start, $end)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
}
Controller that return data that ready to prepend in jQuery
<?php
/**
* Copyright (c) 2019. MonteShot
*/
namespace MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule;
use Magento\Framework\Json\Helper\Data as JsonHelper;
class NewConditionHtmlCatalog extends \MonteShot\MegaWidget\Controller\Adminhtml\Conditions\Rule
{
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
\MonteShot\MegaWidget\Model\RuleFactory $ruleFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Widget\Helper\Conditions $conditions,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
JsonHelper $jsonHelper,
\Magento\CatalogWidget\Model\RuleFactory $ruleCatalogFactory,
\Magento\Rule\Model\Condition\CombineFactory $combineModelFactory
)
{
$this->combineModelFactory = $combineModelFactory;
$this->ruleCatalogFactory = $ruleCatalogFactory;
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->conditions = $conditions;
parent::__construct($context, $coreRegistry, $fileFactory, $dateFilter, $ruleFactory, $logger);
}
public function execute()
{
if (!empty($this->getRequest()->getParam('id'))) {
$id = $this->getRequest()->getParam('id');
$typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type')));
$type = $typeArr[0];
$model = $this->_objectManager->create(
$type
)->setId(
$id
)->setType(
$type
)->setRule(
$this->ruleFactory->create()
)->setPrefix(
'conditions'
);
if (!empty($typeArr[1])) {
$model->setAttribute($typeArr[1]);
}
if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) {
$model->setJsFormObject($this->getRequest()->getParam('form'));
$html = $model->asHtmlRecursive();
} else {
$html = '';
}
return $this->getResponse()->setBody($html);
} elseif (!empty($this->getRequest()->getParam('JsonToHtml'))) {
$conditionDecoded = $this->conditions->decode($this->getRequest()->getParam('JsonToHtml'));
foreach ($conditionDecoded as $idx => $condition) {
if ($idx == '1') {
continue;
} else {
$id = $idx;
$type = $conditionDecoded[$idx]['type'];
$rule = $this->ruleCatalogFactory->create();
// $rule->setConditions($conditionDecoded);
$combineModel = $this->combineModelFactory->create();
$combineModel->loadArray($conditionDecoded);
$validateResult = $rule->validateData(new \Magento\Framework\DataObject($rule->getData()));
if ($validateResult !== true) {
foreach ($validateResult as $errorMessage) {
$this->message = $errorMessage;
}
return;
}
$rule->loadPost($rule->getData());
$model = $this->_objectManager->create(
$type
)->setId(
$id
)->setType(
$type
)->setPrefix(
'conditions'
)->setData(
'conditions', $rule
)->setRule(
$rule
);
if (!empty($conditionDecoded[$idx]['attribute'])) {
$model->setAttribute($conditionDecoded[$idx]['attribute']);
}
if (!empty($conditionDecoded[$idx]['value'])) {
$model->setValue($conditionDecoded[$idx]['value']);
}
}
if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) {
// if (empty($this->data)) {
// $model->setJsFormObject($this->getRequest()->getParam('form'));
// $this->data = '<li class>' . $model->asHtmlRecursive() . '</li>';
// $this->data = $model->asHtmlRecursive();
// } else {
$model->setJsFormObject($this->getRequest()->getParam('form'));
$this->data = '<li class>' . $model->asHtmlRecursive() . '</li>';
//$this->data = $this->data . "\n" . '<li class>' . $model->asHtmlRecursive() . '</li>';
// }
} else {
$this->data = '';
}
$this->getResponse()->setBody($this->data);
}
}
}
// return $this->getResponse()->setBody($this->data);
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'message' => $this->message,
'data' => $this->data,
'error' => $this->error
]);
}
}
How i can return interactivity to loaded data
protected function _prepareForm()
{
$model = $this->ruleFactory->create();
// $model = $this->ruleModelFactory->create();
$id = $this->_request->getParam('uniq_id');
$name = $this->_request->getParam('name');
$cuttedName = trim(str_replace('parameters', '', $name), '[]');
// if ($this->ruleResourceCollection->getSize() == 0) {
//
// } else {
// if (!$id) {
// $model = $this->ruleResourceCollection
// ->addFieldToFilter(\MonteShot\MegaWidget\Model\Rule::UNIQ_BUTTON_ID,
// $id
// )->load();
// }
// }
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form_modal',
'action' => $this->getUrl('megawidget/conditions_rule/savewidget',
[
'uniq_id' => $this->_request->getParam('uniq_id'),
'button_num' => $this->_request->getParam('button_num'),
'name' => $this->_request->getParam('name'),
]),
'method' => 'post',
],
]
);
$form->setUseContainer(true);
$form->setHtmlIdPrefix('rule_');
$this->getLayout()->createBlock("Magento\Widget\Block\Adminhtml\Widget\Options");
$renderer = $this->rendererFieldset->setTemplate(
'Magento_CatalogRule::promo/fieldset.phtml'
)->setNewChildUrl(
$this->getUrl('megawidget/conditions_rule/newConditionHtmlCatalog/form/rule_conditions_fieldset')
);
$fieldset = $form->addFieldset(
'conditions_fieldset',
[
'legend' => __(
'Apply the rule only if the following conditions are met (leave blank for all products).'
)
]
)->setRenderer(
$renderer
);
$model->getConditions()->setJsFormObject('rule_conditions_fieldset');
try {
$conditions = $this->conditionsHelper->decode($this->getRequest()->getParam('element_value'));
$model->loadPost(['conditions' => $conditions]);
} catch (\InvalidArgumentException $invalidArgumentException) {
//do nothing
}
$element = $fieldset->addField(
'condition',
'text',
['name' => 'conditions',
'label' => __('Condition'),
'title' => __('Condition'),
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form_modal']],
]
])
->setRule(
$model
)->setRenderer(
$this->conditions
);
$sourceUrl = $this->getUrl(
'megawidget/conditions_rule_conditioncontent/conditionmodalpagecontroller');
$condition = $this->getLayout()->createBlock(
\MonteShot\MegaWidget\Block\Adminhtml\Widget\Options::class
)->setElement(
$element
)->setConfig(
$this->getConfig()
)->setFieldsetId(
$this->getFieldsetId()
)->setSourceUrl(
$sourceUrl
)->setConfig(
$this->getConfig()
)->setFieldsetId(
$this->getFieldsetId()
)->setUniqId(
$id
);
// $fieldset->addElement($this->getLayout()->createBlock(\MonteShot\MegaWidget\Renderer\Conditions::class));
$label = $id . 'label';
$valueId = $id . 'value';
$fieldset->addField(
'button-save',
'hidden',
['name' => 'select',
'label' => __('Save condition'),
'title' => __('Save condition'),
'class' => 'action-close',
'data-role' => 'closeBtn',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveandcontinue', 'target' => '#edit_form']],
],
'after_element_html' => '
<button data-role="closeBtn" id="rule_button-save-submit-' . $cuttedName . '" type="button">Save</button>
<script>
require([\'jquery\',\'jqueryForm\',\'Magento_Ui/js/modal/modal\'], function (jQuery,jqueryForm,modal){
jQuery(document).on(\'click\', "#rule_button-save-submit-' . $cuttedName . '", function () {
var serArr=JSON.stringify(jQuery("#edit_form_modal").serializeArray());
jQuery.ajax({
url: "' . $this->getUrl("megawidget/conditions_rule/preparedata") . '",
data: { form_key: window.FORM_KEY,serializedArray:serArr},
type: \'post\',
success: function (response) {
console.log(response.data);
jQuery("input[name=\'' . $name . '\']")[0].value=response.data;
},
error: function (response) {
alert(response.message);
console.log(response.message);
}
});
});
});
</script>
']);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
I have the following problem. I have a city that I want to put two boxes Dates (From-To). When selecting a period of time I want to update the grid, but right here is the problem. Here's my code so far
$dateisOn = CHtml::textField('Event[from_date]', '',
array('id' => 'from', 'data-date-format' => 'yyyy-mm-dd')) .
' До ' . CHtml::textField('Event[from_date]', '',
array('id' => 'to', 'data-date-format' => 'yyyy-mm-dd'));
$this->widget('ext.widgets.StyledGridWidget', array(
'id' => 'event-grid',
'dataProvider' => $model->search(),
'enablePagination' => false,
'filter' => $model,
'columns' => array(
array(
'name' => 'product_id',
'value' => '$data->product_id'
),
array(
'name' => 'cnt',
'header' => 'Брой',
'value' => '$data->cnt'
),
array(
'name' => 'code',
'value' => '$data->code'
),
array(
'name' => 'date',
'filter' => $dateisOn,
),
),
));
Here is js datepicker:
var checkin = $('#from').datepicker({
onRender: function(date) {
}
}).on('changeDate', function(ev) {
var newDate = new Date(ev.date);
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
checkin.hide();
$('#to')[0].focus();
}).data('datepicker');
var checkout = $('#to').datepicker({
onRender: function(date) {
}
}).on('changeDate', function(ev) {
checkout.hide();
}).data('datepicker');
And this is a my model function search
public function search() {
//var_dump($this->date_first); exit;
$criteria = new CDbCriteria;
$criteria->with = (array('order', 'product'));
$criteria->compare('product.id', $this->product_id);
$criteria->compare('product.code', $this->code);
$criteria->compare('cnt', $this->cnt);
$criteria->select = 'count(t.product_id) AS cnt, t.product_id, product.code';
$criteria->order = 'cnt DESC';
$criteria->group='t.product_id';
$criteria->limit = 10;
if (!empty($this->from_date) && empty($this->to_date)) {
$criteria->condition = "order.updated_at >= '$this->from_date'";
} elseif (!empty($this->to_date) && empty($this->from_date)) {
$criteria->condition = "order.updated_at <= '$this->to_date'";
} elseif (!empty($this->to_date) && !empty($this->from_date)) {
$criteria->condition = "order.updated_at >= '$this->from_date' and order.updated_at <= '$this->to_date'";
}
$criteria->together = true;
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
First, you should fix the to_date field :
$dateisOn = CHtml::textField('Event[from_date]', '',
array('id' => 'from', 'data-date-format' => 'yyyy-mm-dd')) .
' До ' . CHtml::textField('Event[to_date]', '',
array('id' => 'to', 'data-date-format' => 'yyyy-mm-dd'));
You could also modify your search function, you can simply use :
$criteria->compare('order.updated_at', '>='.$this->from_date);
$criteria->compare('order.updated_at', '<='.$this->to_date);