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
Related
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 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?
Hi, I would like it to be like in the image and if the phone number don't match then it would not validate
really need help, thanks
This is my answer to adding custom field in the billing section
add_filter( 'woocommerce_checkout_fields' , 'bbloomer_add_field_and_reorder_fields' );
function bbloomer_add_field_and_reorder_fields( $fields ) {
if (!$_POST['shipping_method_tax_exempt']) {
unset($fields['extra_fields']['claimant_name']);
unset($fields['extra_fields']['description_illness']);
unset($fields['extra_fields']['vat_confirm']);
}
// Add New Fields
$fields['billing']['billing_phone_confirm'] = array(
'label' => __('Phone confirm', 'woocommerce'),
'required' => true,
'class' => array('form-row-last'),
'clear' => false
);
/*$fields['shipping']['shipping_houseno'] = array(
'label' => __('House Number', 'woocommerce'),
'placeholder' => _x('House Number', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-last'),
'clear' => false
);*/
// Remove Address_2 Fields
unset($fields['billing']['billing_address_2']);
//unset($fields['shipping']['shipping_address_2']);
// Make Address_1 Fields Half Width
//$fields['billing']['billing_address_1']['class'] = array('form-row-first');
//$fields['shipping']['shipping_address_1']['class'] = array('form-row-first');
$fields['billing']['billing_country_field']['class'] = array('form-row-first');
// Billing: Sort Fields
$newfields['billing']['billing_first_name'] = $fields['billing']['billing_first_name'];
$newfields['billing']['billing_last_name'] = $fields['billing']['billing_last_name'];
$newfields['billing']['billing_company'] = $fields['billing']['billing_company'];
$newfields['billing']['billing_email'] = $fields['billing']['billing_email'];
$newfields['billing']['billing_phone'] = $fields['billing']['billing_phone'];
$newfields['billing']['billing_phone_confirm'] = $fields['billing']['billing_phone_confirm'];
$newfields['billing']['billing_country'] = $fields['billing']['billing_country'];
$newfields['billing']['billing_address_1'] = $fields['billing']['billing_address_1'];
//$newfields['billing']['billing_address_2'] = $fields['billing']['billing_address_2'];
$newfields['billing']['billing_city'] = $fields['billing']['billing_city'];
$newfields['billing']['billing_postcode'] = $fields['billing']['billing_postcode'];
$newfields['billing']['billing_state'] = $fields['billing']['billing_state'];
// Shipping: Sort Fields
$newfields['shipping']['shipping_first_name'] = $fields['shipping']['shipping_first_name'];
$newfields['shipping']['shipping_last_name'] = $fields['shipping']['shipping_last_name'];
$newfields['shipping']['shipping_company'] = $fields['shipping']['shipping_company'];
$newfields['shipping']['shipping_country'] = $fields['shipping']['shipping_country'];
$newfields['shipping']['shipping_address_1'] = $fields['shipping']['shipping_address_1'];
$newfields['shipping']['shipping_houseno'] = $fields['shipping']['shipping_houseno'];
$newfields['shipping']['shipping_city'] = $fields['shipping']['shipping_city'];
$newfields['shipping']['shipping_state'] = $fields['shipping']['shipping_state'];
$newfields['shipping']['shipping_postcode'] = $fields['shipping']['shipping_postcode'];
$checkout_fields = array_merge( $fields, $newfields);
return $checkout_fields;
}
now the problem is the confirmation, it should not validate if it does not match
here is what I'm using now
add_action( 'woocommerce_after_checkout_validation', 'wc_check_confirm_phone_matches_checkout', 10, 2 );
function wc_check_confirm_phone_matches_checkout( $posted ) {
$checkout = WC()->checkout;
if ( strcmp( $posted['billing_phone'], $posted['billing_phone_confirm_field'] ) !== 0 ) {
wc_add_notice( __( 'Phone number do not match.', 'woocommerce' ), 'error' );
}
}
The problem here is that is always shows "Phone number do not match." even if it matches, need help on this
/**
Add the field to the checkout page
*/
add_action( 'woocommerce_after_order_notes', 'some_custom_checkout_field' );
functionsome_custom_checkout_field( $checkout ) {
echo '' . __('Heading') . '';
woocommerce_form_field( 'some_field_name', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Additional Field'),
'placeholder' => __('Some hint'),
'required' => true,
), $checkout->get_value( 'some_field_name' ));
echo '';
}
I have a php page that is making a couple of ajax calls. The first ajax call is made and on success it activates a second ajax function. Each function has die() at the end. No matter what I do, die() keeps outputting a "0" to the screen. I tried commenting the die() out of the first ajax function, but it never processes the ajax request when I do that. The loading gif just keeps spinning. When I comment out the die() in the second function, it outputs "0" twice. I have no clue why it keeps printing that to the screen.
This is the first function.
function json_info() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
// create a new array to store projects
$projectsArray = array();
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
$projectsArray = array();
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
$image = get_field('project_photo');
$image = $image['sizes']['thumbnail'];
$projectsArray[] = array(
'title' => get_the_title(),
'lat' => get_field('latitude'),
'long' => get_field('longitude'),
'status' => get_field('status'),
'industry' => get_field('industry'),
'state' => get_field('state'),
'link' => get_permalink(),
'photo' => $image,
'num' => $paged
);
endwhile; endif;
wp_reset_query();
} // end of isset
?>
<?php
echo json_encode($projectsArray);
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info', 'json_info' );
add_action( 'wp_ajax_nopriv_json_info', 'json_info' );
And this is the second function:
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
?>
<li class="group">
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
And this is the ajax call to both functions:
function run_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info',
'state' : state,
'status' : markets,
'services' : services
},
success:function(data) {
// This outputs the result of the ajax request
var jsonData = JSON.parse(data);
do_ajax();
} /*,
error: function(errorThrown){
console.log(errorThrown);
}*/
}); // end of ajax call for json_info
function do_ajax() {
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
}
I'm not sure what I'm missing or doing wrong that is causing the "0" to print to the screen.
Well, it turns out that I'm an idiot, and I was just overlooking the problem. There was a third function called by ajax, and I didn't have die() at the end of it. I was thinking the issue was in my second function since the 0 was showing up in the div where I was printing that content.
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);