add value to textarea based on selected autocomplete option in opencart - php

One new column added to DB by me to add descriptions to attributes in Opencart and i can easily add/edit descriptions from admin panel but i have a problem in product_form page. I want to add automatically attribute description to every product when i choose attribute name.
In Opencart admin can choose attributes for products from autocomplete box but every time admin should add attribute descriptions manually. For example attribute 'Gold'. Every time when admin choose attribute 'Gold' he have to add description for gold manually. I want to retrieve attribute description from DB column 'protext' to automatically fill related textarea when admin. So when selected 'Gold' from input box related text should be appear in related textarea for description.
This is code that edited by me in product form but doesn't work.
your help will be appreciated.
function attributeautocomplete(attribute_row) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item.attribute_group,
label: item.name,
label2: item.protext,
value: item.attribute_id
}
}));
}
});
},
'select': function(item) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').val(item['label']);
$('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').val(item['value']);
$('input[name=\'related\']').val('');
}
$('textarea[name=\'product_attribute[' + attribute_row + '][product_attribute_description][text]\']').autocomplete({
'append': function(item) {
$('textarea[name=\'product_attribute[' + attribute_row + '][product_attribute_description][text]\']').val(item['protext']);
}
});
}

For this you have to change code in Controller file from where ajax is returning result. Path Admin > Controller > Catalog > Attribute -> function autocomplete(). Add "protext" code after name row or after any other key you want (I wrote 1 so that you can find code in file and can add after this)
'name' => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
line
'protext' => html_entity_decode($result['protext'], ENT_QUOTES, 'UTF-8'),
This is how, you will get this in tpl file.
Database is already fetching with * so you don't need to change any code there.
You already added code for tpl so it will work fine.
Note - It's better to make these changes using vqmod or ocmod. My OC version 2.0.2.0

Related

wp admin populate select dropdown after checkbox change

I have custom post types called: Categories, Messages and Tools. I also have custom taxonomy called Subcategories.
Category has custom ACF post object field where you can select values from existing Tools, you also have to select Subcategory
Messages have custom taxonomy radio field where you have to select one of the Subcategories.
Messages can also have Tools, but only those that belong to the Category that has the same Subcategory as the message.
I'm using conditional logic to show Tools post object field when Subcategory is selected for the Message.
My problem is that I'm having hard time limiting Tools available in Message to only those that are from the Category with the same subcategory.
I've actually managed to get the list of Tools that can be displayed with change event listener on Subcategory radio and ajax, but I just dont know how to populate the Tool post object field.
$(window).on("load", function() {
if (typeof(acf) == 'undefined') {
return;
}
// radio taxonomy select
var field = acf.getField('field_5dcd325ceb231');
field.on('change', function(e) {
// the field I would like to populate with the Tools I get in response
var mandatory_tools = acf.getField('field_5dc1444f9dde7');
// selected Subcategory Id
var subcategory_id = field.val();
if (!subcategory_id) {
return;
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'get_subcategory_tools',
subcategory_id: subcategory_id,
},
success: function( response ) {
response = JSON.parse( response );
// console.log(response);
if (response.success) {
// I get the array of object with tools that I want to be available for selection
let tools = response.tools;
// how to limit the selection to only those Tools that are in tools variable,
instead of showing all tools
}
},
error: function (xhr, status, error) {
console.log( xhr.responseText );
}
});
});
});
Subcategory taxonomy radio field in Messages
Post object field for selecting Tools in Messages in which I only want to have Tools that are in response, instead of all of them
After some research it seems that it isnt possible to modify acf post object fields with ajax.
I got around this by creating acf select field and filling it with the stuff I need.
Select field can be updated by ajax

Display hidden div if no more data found

So currently I'm searching for 10 new posts and the Ajax searches in the same page from the page and I use $_GET['limits'] in my PHP query to scan the server for all requested data.
So what I'd like to do is if there is no new data to show the 'No More Posts' Div. I tried using t.length===0 with no luck, now I don't know if its because t isn't an array or whether I put it in the wrong place in my success.
var streams_stream_count=10;
function streams_stream_load(targetID){
$('#loadmorestreamoneajaxloadertarget').show();
$.ajax({
method: 'get',
url : 'stream2.php?limits='+streams_stream_count+'&targetID='+targetID,
dataType : 'text',
success: function (t) {
$('#streams_stream_container').fadeIn('slow').html(t);
$(document).scroll(function(){
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
streams_stream_count+=10;streams_stream_load(targetID);
}
});
},
complete: function(){
$('#loadmorestreamoneajaxloadertarget').hide();
}
});
}
And my hidden div to show if no new data.
<div id='nomoreposts' style='display:none;'>No more Posts</div>
UPDATE
I use $sqlLimit=mysqli_real_escape_string($mysqli,$_GET['limit'])
$call="SELECT * FROM streamdata ORDER BY streamitem_timestamp DESC LIMIT $sqlLimit";
You can also do like this :- Write code in backend (PHP function) and return html if no data found "No more Posts", also send one parameter true/false. On the bases of the parameter show html in your fronted.

kendoAutoComplete for multiple dataTextField

The code below works for autocomplete for FileNo (field) only. i want this function to work for other attributes of employee too. i.e FirstName, LastName
dataTextField: "FileNo" <---------------- here dataTextField gets sing field. how could it be for multiple fields?
Since you are the one that knows on which columns want to search, my recommendation is:
Implement index.php/hr_management/manage_hr/search_employee/ in such way that is able to do the search for any of the columns that you want (FileNo, FirstName, LastName...).
This service will return three columns (at least) providing an id, column name on which you found the match and match value.
match value is used for displaying values in the autocomplete.
Once selected value on autocomplete use the column name and match value for filtering on the grid.
You should use template to change what is displayed in the dropdownlist of the autocomplete. Then the dataTextField will only be used inside the input element.
Here is how it goes to create template.
Kendo Autocomplete has dataTextField that accepts a field name(e.g. employeeID, employeeName etc. of a datasource ) to use for filtering items.
To use multiple fields, you have to set one of the fields to hold concatenated fields during parsing of datasource in your schema as given below.
Then set your filter of AutoComplete to "contains"
I did it as follows.
var myDataSrc = new kendo.data.DataSource({
transport: {
read: {
type:"GET",
url:clientDataURL,
dataType: "jsonp",
contentType: "application/json",
}
},
schema: {
parse: function(clntDB) {
$.each(clntDB, function(ky, clnt) {
clnt.firstName = clnt.clientUID + " | " + clnt.firstName+ " " + clnt.lastName;
});
return clntDB;
}
},
pageSize: 4 // Number of Items to show during input
});
/// See the firstName above it's reconstructed to hold concatenated lastname , ID and firstname string.
Next step is to use parsed firstName as a value of dataTextField of kendo Autocomplete.
Then
var selectedClntID; //// Actually, this aims at getting the ID for future use
$("#YOURSEARCHINPUTID").kendoAutoComplete({
dataSource: myDataSrc ,
template: tmplSrchdClnt, // YOUR TEMPLATE like "<div>firstName</div>"
dataTextField:"firstName",
filter:"contains", /// DON'T FORGET TO ADD THIS
minLength : 1 ,
select: function(e) {
var selectedClnt = this.dataItem(e.item.index()),
x = kendo.stringify(selectedClnt);
selectedClntID = JSON.parse(x);
}
// headerTemplate: '<div><h2>ID - LastName</h2></div>'
});
However, tough to find resource indicating like this, it's awesome when you see it working.This is engine of my project when it comes to autocompletion. I did it this way.
Alternatively, you can convert to
data = new Employee(firstname, lastname, ID); // on client side
function Employee( firstname, lastname, ID ){
this.filterStr = firstname + ""+lastname+" "+ID;
}
give data to kendo AutoComplete dataSource and use filterStr as dataTextField.
Another code example adding a new field to the datacourse to use as dataTextField.
// Build our data source object.
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: readUrl,
}
},
group: {field: "region"},
schema: {
data: function(response) {
$.each(response, function(k, v) {
response[k].searchString = v.airport + " " + v.iataCode;
});
return response;
}
}
});
$(selector).kendoAutoComplete({
dataTextField: "searchString",
filter: "contains",
template: '<span class="k-state-default">#: data.airport # (#: data.iataCode #)</span>',
height: 400,
dataSource: dataSource,
});

JQuery PHP AJAX filter based on multiple checkbox array

I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/

How does AJAX handle multiples instances of a variable?

I am currently editing a WordPress plugin, which allows you to filter posts by category, once a category is selected, the posts for that caregory are displayed as a checklist on the widget, the user can select the posts they wish to display in their sidebar/widget area of the theme.
I have taken the widget to the point that the user can select their post, the widget allows a single post to be selected, however if more than one is selected and the save button is pressed, the form returns only the last slected post.
After some searching, I have found the problem to be on the form return.
It is either to do with the update, or the way AJAX handles multiple instances of a variable.
the information posted to the server is as follows:
action save-widget
add_new
id_base single_post_super_widget
multi_number
savewidgets 9bc3d79f1c
sidebar lcp-sb
widget-height 200
widget-id single_post_super_widget-2
widget-single_post_super_widget[2][object_to_use] 5005
widget-single_post_super_widget[2][object_to_use] 4892
widget-single_post_super_widget[2][object_to_use] 4607
widget-single_post_super_widget[2][object_type] 72
widget-single_post_super_widget[2][paged] 1
widget-single_post_super_widget[2][tab] all
widget-single_post_super_widget[2][title_override]
widget-width 400
widget_number 2
Where object_to_use is the post(s) being selected.
the information being sent is defined here:
var theArgs = {
action: jQuery('input.widget_class:hidden', widgetDiv).first().val() + '-get-metabox',
widget: widgetDivId,
number: widgetNumber,
blog_id: jQuery(widgetInputBase + 'blog_id').val(),
object_type: jQuery(widgetInputBase + 'object_type').val(),
tab: currentTab,
paged: currentPage,
object_to_use: jQuery('input[type=checkbox][name$="[object_to_use]['+currentTab+']"]:checked', widgetDiv).first().val(),
title_override: jQuery(widgetInputBase + 'title_override').val(),
excerpt_override: jQuery(widgetInputBase + 'excerpt_override').val(),
searched: ('search' == currentTab) ? jQuery('input.quick-search', widgetDiv).first().val() : ''
};
and the jQuery.post action:
jQuery.post(
ajaxurl,
theArgs,
function( r ) {
jQuery('.ajax-feedback').css('visibility', 'hidden');
if ( r && r.length > 2 ) {
jQuery('div.widget-content', widgetDiv).html(r);
}
}
);
In relation to the question, widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this? Does each post/variable have to be unique?
widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this?
There is nothing Ajax specific about this. You just get multiple copies of the key in the data submitted to the server.
Does each post/variable have to be unique?
No.
In most server side environments, you can get all the data just by using the right function. For example with Perl's CGI.pm module, you just get the parameter in list context:
my #thing = $cgi->param('widget-single_post_super_widget[2][object_to_use]');
… and it will 'just work'.
PHP is special. If the name ends in [] then it will just create an array in $_POST and friends. If it doesn't, then it will discard all but the last item. (Unless I'm misremembering and it keeps the first instead).
You can use ajax using jQuery.. then you can pass multiple instances of variable :-
like this :-
if(roleId !='' && roleId != '16'){
jQuery('#user_id_div').hide();
jQuery('#loading_image').show().html("<label> </label> <img src='<?php echo $this->webroot; ?>img/ajax-loader.gif' alt='Loading...'>");
urlData = "<?php echo Router::url(array('controller' => 'users', 'action' => 'getmultipleVendors')) ?>" ;
postData = "vendorType=" + roleId;
jQuery.ajax({
url: urlData,
data: postData,
success: function(data) {
jQuery('#PromoCodeUserId').html(data);
jQuery('#user_id_div').show();
jQuery('#loading_image').hide();
}
});
in postdata field you can post many data as avariables..

Categories