prestashop 1.6 attribute as textfield - attributes

im making a customizable product to sell in prestashop, its a pepper sauce where you can fully customize at your own taste... Im doing good and the attributes options in prestashop are good to set drop down select fields and outers stuff, but, i cant simple add a textbox! im trying to find a solution, but its complicated...
http://pimentaemcasa.com.br/home/8-pimenta-personalizada.html
you guys can see in the middle the custom options, the last one is the sauceĀ“s name, its a textbox but after the user clicks in "comprar" (add to cart) it goes nowhere, i need to post it together with the outer attributes, for now its just a textfield alone that send his value nowhere... anyone can help me attach the name with the order?
(the prestashop customize option in products let you put a textbox, buts its also needs that you hit "save" in the name before you hit "add to cart", awful, hey prestashop team, count the taps! ;p)
thaaanks!

I use the textfield customized data in this example, you should create a customized input data (called nickname in this example) for your product.
You can add a textbox and send its value to the ajax-cart.js in blockcart module,
in
add : function(idProduct, idCombination, addedFromProductPage, callerElement, quantity, whishlist)
you can add your input for example
var nickname = $('input[name=nickname]').val();
and send the value in the ajax call
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
/*************** added by TAREK ******************************/
data: 'controller=cart&add=1&ajax=true&qty=' + ((quantity && quantity !=
null) ? quantity : '1') + '&id_product=' + idProduct
+'&nickname='+nickname+ '&token=' + static_token + (
(parseInt(idCombination) && idCombination != null) ? '&ipa=' +
parseInt(idCombination): ''),
/*************** added by TAREK ******************************/
in cartController.php (override), in processChangeProductInCart function, after if (!$this->errors && $mode == 'add') you should the code that add the customized data value in the database
$authorized_text_fields = array('nickname');
foreach ($_POST as $field_name => $value)
if (in_array($field_name, $authorized_text_fields) && $value != '')
{
if (!Validate::isMessage($value))
$this->errors[] = Tools::displayError('Invalid message');
else {
$this->context->cart->deleteCustomizationToProduct((int)$this->id_product, 'nickname');
$this->context->cart->addTextFieldToProduct($this->id_product, 'nickname', Product::CUSTOMIZE_TEXTFIELD,Tools::getValue('nickname'));
}
}
else if (in_array($field_name, $authorized_text_fields) && $value == '')
$this->context->cart->deleteCustomizationToProduct((int)$this->id_product, 'nickname');
Hope this helps,
Cordially.

Related

Displaying list of all items with the same lookup fields in Display Form of that Lookup field in SharePoint 2013

I have 2 lists which are Room and Equipment.
In the Equipment list there is a lookup Field to the Room list .
I want to display all related Equipment in Room simple tabular Display Form.
How should I achieve this?
A general solution would be as follow
Check you can work with the REST API in JavaScript like below. (in this step you can just make sure the URL is returning XML data you requested)
http://portal/_api/web/lists/getByTitle('Equipments')/items/?$select=Title,ID&$filter=Room eq 'room1'
create a new custom DisplayForm with SharePoint Designer and add the following jQuery Script to read and generate the previous fetched data at the end of
<script src="/_layouts/15/CDN/Js/jquery-1.11.1.min.js" type="text/javascript" > </script>
<script type="text/javascript" >
function LoadEquipments(roomValue) {
$.ajax({
url : _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getByTitle('Equipments')/items/" +
"?$select=Title,ID" +
"&$filter=Room eq '" + roomValue + "'",
type : "GET",
headers : {
"accept" : "application/json;odata=verbose",
},
success : function (data) {
var equipments = [];
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
if (equipments.indexOf(results[i].Title) < 0)
equipments.push(results[i].Title);
}
var ullist = $('<ul/>');
for (var i = 0; i < equipments.length; i++)
$('<li/>').val(equipments[i]).html(equipments[i]).appendTo(ullist);
ullist.appendTo('#divEquipements');
$("#divEquipements ul li").css("font-size", "16px").css("color", "salmon");
},
error : function (err) {
alert(JSON.stringify(err));
}
});
}
$(document).ready(function () {
var roomVal = $("#TitleValue").text();
LoadEquipments(roomVal);
});
for previous code to work as you might guess you would better add id for new td to enclose the new requirements(for example a new tr as the last row which contains aa div with id='divEquipements' ) data and also just add id='TitleValue' to the td containing the room title (usually the first row)
OK there are a lot of possibilities for achieving this. Some possible and good looking solution can be:
Overload the click of the market value in the list(can be done using JSLink) to open a Modal dialog page where all the equipments are listed(fetched using REST query)
Overload the click of the market value in the list(can be done using JSLink) and redirect to the same page but with filters to the same view.
If the number of markets are not many, views can also be created per market(Not so good, but will reduce coding effort)
If its something else you are looking for, please let know. Hope this helps!

Creating alerts from changes at the item level in Netsuite

I am trying to incorporate a check at the item line level when creating an invoice. Basically if they are adding an item within a certain category (custitem8) i need an alert to pop up for the sales rep.
Not sure if this should be using fieldchanged or validateline.
Sorry Im not really a programmer and am learning on the job mostly by trial and error. Thanks for your help.
function ValidateLine(type)
{
if (nlapiGetCurrentLineItemValue('item', 'custitem8') = 'Order in Only - Not For Trade Guide')
{
alert("Order In Only, Please contact Purchasing");
}
return true;
}
The suggested code will not work, instead of using nlapiGetLineItemValue use nlapiGetCurrentLineItemValue.
the code should look like this.
postSourcing(sublistId, fieldId) {
if(sublistId == "item" && fieldId == "item") {
var itemId = nlapiGetCurrentLineItemValue(sublistId, fieldId);
var category = nlapiLookupField("item", itemId, "custitem8");
if(category == "Order in Only - Not For Trade Guide") {
alert("Order In Only, Please contact Purchasing");
}
}
}
I'm assuming you just need an alert when the user selects a line Item? If so, I would suggest using postSourcing(sublistId, fieldId) (though using validateLine(sublistId) works just fine).
As for the actual function content, I'm assuming (based on the field ID) "custitem8" is a field on the Item record. If so, you will have to load the field from the Item record first.
Based on my understanding of your post, I would go about it like this:
postSourcing(sublistId, fieldId) {
if(sublistId == "item" && fieldId == "item") {
var itemId = nlapiGetLineItemValue("item", "item");
var category = nlapiLookupField("item", itemId, "custitem8");
if(category == "Order in Only - Not For Trade Guide") {
alert("Order In Only, Please contact Purchasing");
}
}
}
And just a note, I don't really know the data type of the "custitem8" field, so I'm just assuming it's a free-form text field.

jquery-jable: How to display a field as read-only in the edit form?

I have a table pre-populated with the company LAN IP addresses with fields for associated data, status, etc. The (jquery-)jtable fields collection is configured like this.
fields: {
id: { title: 'ID'},
ip: { title: 'IP address, edit: false }
more: { ... }
}
This works but the problem is that when the edit dialog pops up the user can't see the ip address of the record being edited as jtable's edit form doesn't show the field.
I've read through the documentation but can't see any way to display a field as read-only in the edit form. Any ideas?
You don't need to hack the jTable library asset, this just leads to pains when you want to update to a later version. All you need to do is create a custom input via the jTable field option "input", see an example field setup to accomplish what you need here:
JobId: {
title: 'JobId',
create: true,
edit: true,
list: true,
input: function (data) {
if (data.value) {
return '<input type="text" readonly class="jtable-input-readonly" name="JobId" value="' + data.value + '"/>';
} else {
//nothing to worry about here for your situation, data.value is undefined so the else is for the create/add new record user interaction, create is false for your usage so this else is not needed but shown just so you know when it would be entered
}
},
width: '5%',
visibility: 'hidden'
},
And simple style class:
.jtable-input-readonly{
background-color:lightgray;
}
I have simple solution:
formCreated: function (event, data)
{
if(data.formType=='edit') {
$('#Edit-ip').prop('readonly', true);
$('#Edit-ip').addClass('jtable-input-readonly');
}
},
For dropdown make other options disabled except the current one:
$('#Edit-country option:not(:selected)').attr('disabled', true);
And simple style class:
.jtable-input-readonly{
background-color:lightgray;
}
I had to hack jtable.js. Start around line 2427. Changed lines are marked with '*'.
//Do not create element for non-editable fields
if (field.edit == false) {
//Label hack part 1: Unless 'hidden' we want to show fields even though they can't be edited. Disable the 'continue'.
* //continue;
}
//Hidden field
if (field.type == 'hidden') {
$editForm.append(self._createInputForHidden(fieldName, fieldValue));
continue;
}
//Create a container div for this input field and add to form
var $fieldContainer = $('<div class="jtable-input-field-container"></div>').appendTo($editForm);
//Create a label for input
$fieldContainer.append(self._createInputLabelForRecordField(fieldName));
//Label hack part 2: Create a label containing the field value.
* if (field.edit == false) {
* $fieldContainer.append(self._myCreateLabelWithText(fieldValue));
* continue; //Label hack: Unless 'hidden' we want to show fields even though they can't be edited.
* }
//Create input element with it's current value
After _createInputLabelForRecordField add in this function (around line 1430):
/* Hack part 3: Creates label containing non-editable field value.
*************************************************************************/
_myCreateLabelWithText: function (txt) {
return $('<div />')
.addClass('jtable-input-label')
.html(txt);
},
With the Metro theme both the field name and value will be grey colour.
Be careful with your update script that you're passing back to. No value will be passed back for the //edit: false// fields so don't include them in your update query.
A more simple version for dropdowns
$('#Edit-country').prop('disabled',true);
No need to disable all the options :)

jqGrid filterToolbar search

In trying to implement a filterToolbar search in jquery, but when I write in the textbox it doesnt send the value, the search field nor the operator: I used an example, here is the code in html file
jQuery(document).ready(function () {
var grid = $("#list");
$("#list").jqGrid({
url:'grid.php',
datatype: 'xml',
mtype: 'GET',
deepempty:true ,
colNames:['Id','Buscar','Desccripcion'],
colModel:[
{name:'id',index:'id', width:65, sorttype: 'int', hidden:true, search:false},
{name:'examen',index:'nombre', width:500, align:'left', search:true},
{name:'descripcion',index:'descripcion', width:100, sortable:false, hidden:true, search:false}
],
pager: jQuery('#pager'),
rowNum:25,
sortname: 'nombre',
sortorder: 'asc',
viewrecords: true,
gridview: true,
height: 'auto',
caption: 'Examenes',
height: "100%",
loadComplete: function() {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
$("#"+id+ " td:eq(1)", grid[0]).tooltip({
content: function(response) {
var rowData = grid.jqGrid('getRowData',this.parentNode.id);
return rowData.descripcion;
},
open: function() {
$(this).tooltip("widget").stop(false, true).hide().slideDown("fast");
},
close: function() {
$(this).tooltip("widget").stop(false, true).show().slideUp("fast");
}
}).tooltip("widget").addClass("ui-state-highlight");
}
}
});
$("#list").jqGrid('navGrid','#pager',{edit:false,add:false,del:false});
$("#list").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false,
defaultSearch: 'cn', ignoreCase: true});
});
and in the php file
$ops = array(
'eq'=>'=', //equal
'ne'=>'<>',//not equal
'lt'=>'<', //less than
'le'=>'<=',//less than or equal
'gt'=>'>', //greater than
'ge'=>'>=',//greater than or equal
'bw'=>'LIKE', //begins with
'bn'=>'NOT LIKE', //doesn't begin with
'in'=>'LIKE', //is in
'ni'=>'NOT LIKE', //is not in
'ew'=>'LIKE', //ends with
'en'=>'NOT LIKE', //doesn't end with
'cn'=>'LIKE', // contains
'nc'=>'NOT LIKE' //doesn't contain
);
function getWhereClause($col, $oper, $val){
global $ops;
if($oper == 'bw' || $oper == 'bn') $val .= '%';
if($oper == 'ew' || $oper == 'en' ) $val = '%'.$val;
if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%';
return " WHERE $col {$ops[$oper]} '$val' ";
}
$where = ""; //if there is no search request sent by jqgrid, $where should be empty
$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : false;
$searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: false;
$searchString = isset($_GET['searchString']) ? $_GET['searchString'] : false;
if ($_GET['_search'] == 'true') {
$where = getWhereClause($searchField,$searchOper,$searchString);
}
I saw the query, and $searchField,$searchOper,$searchString have no value
But when I use the button search on the navigation bar it works! I dont konw what is happening with the toolbarfilter
Thank You
You use the option stringResult: true of the toolbarfilter. In the case the full filter will be encoded in filters option (see here). Additionally there are no ignoreCase option of toolbarfilter method. There are ignoreCase option of jqGrid, but it works only in case of local searching.
So you have to change the server code to use filters parameter or to remove stringResult: true option. The removing of stringResult: true could be probably the best way in your case because you have only one searchable column. In the case you will get one additional parameter on the server side: examen. For example if the user would type physic in the only searching field the parameter examen=physic will be send without of any information about the searching operation. If you would need to implement filter searching in more as one column and if you would use different searching operation in different columns you will have to implement searching by filters parameter.
UPDATED: I wanted to include some general remarks to the code which you posted. You will have bad performance because of the usage
$("#"+id+ " td:eq(1)", grid[0])
The problem is that the web browser create internally index of elements by id. So the code $("#"+id+ " td:eq(1)") can use the id index and will work quickly. On the other side if you use grid[0] as the context of jQuery operation the web browser will be unable to use the index in the case and the finding of the corresponding <td> element will be much more slowly in case of large number rows.
To write the most effective code you should remind, that jQuery is the wrapper of the DOM which represent the page elements. jQuery is designed to support common DOM interface. On the other side there are many helpful specific DOM method for different HTML elements. For example DOM of the <table> element contain very helpful rows property which is supported by all (even very old) web browsers. In the same way DOM of <tr> contains property cells which you can use directly. You can find more information about the subject here. In your case the only thing which you need to know is that jqGrid create additional hidden row as the first row only to have fixed width of the grid columns. So you can either just start the enumeration of the rows from the index 1 (skipping the index 0) or verify whether the class of every row is jqgrow. If you don't use subgrids or grouping you can use the following simple code which is equivalent your original code
loadComplete: function() {
var i, rows = this.rows, l = rows.length;
for (i = 1; i < l; i++) { // we skip the first dummy hidden row
$(rows[i].cells(1)).tooltip({
content: function(response) {
var rowData = grid.jqGrid('getRowData',this.parentNode.id);
return rowData.descripcion;
},
open: function() {
$(this).tooltip("widget").stop(false, true).hide().slideDown("fast");
},
close: function() {
$(this).tooltip("widget").stop(false, true).show().slideUp("fast");
}
}).tooltip("widget").addClass("ui-state-highlight");
}
}

CRM 2011 - setting a default value with JScript

We have CRM 2011 on premise. The Contact entity was customized to use a lookup to a custom entity Country instead of just a text field. When creating a new Contact we would like the country field to be set to Canada by default. I have the following function that does that:
function SetDefaultCountryCode(countryFieldId) {
var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}";
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
On the form OnLoad I invoke the function like that:
// set Country fields to Canada if not set
SetDefaultCountryCode('cga_address1country');
We have two servers - DEV and TEST. This JScript works fine in DEV. When I run it in TEST it does not work because the Canada in TEST has different id (GUID) - when I create it manually. I was hoping I could export the Country entity values from DEV and import them in TEST preserving their GUIDs. Unfortunately this did not work. I export the data to Excel file and it has the GUIDs of the countries. I also delete any existing Country records in TEST before importing. When I try to import it the import succeeds but does not create any records. If I add a new row in the excel file without specifing a Guid it will import it. It seems to me the import functionality was not meant to preserve the GUIDs of the records. But this also means my script will not work because it depends on the GUIDs.
I have two questions here:
Is it possible to export / import entity data preserving the GUIDs ?
If I cannot have the same GUIDs in DEV and TEST how I can make the JScript to work properly?
Thank you in advance for any help / feedback.
It's very bad practice to hard code your GUIDs and you discovered the problems of it.
As you stated above, we cannot have the same GUIDs but we have the same name. So, we have to query the name of the country using JScript and jQuery to retrieve the GUID.
In order to retireve information from client-side (or Entity Form):
We will use/consume REST Endpoint (testing in browser).
Upload jQuery lib.
Upload Json2 lib.
Use the AJAX function from the jQuery library.
Define your entity, columns and criteria.
Lets, look for querying REST Endpoint.
http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'
Take this URL, subsitute your actual values and paste it into your browser, you'll find that the response is returned in XML format. If there is any error, please ensure that the Entity name and its attribute are case senisitve.
After seeing your your results, we are going to call this URL using an AJAX call.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: 'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'',
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
// now we have the GUID of Canada, now I can continue my process
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
But before you copy the code to your form, you have to download the jQuery lib from here
Then upload it as a Web resource, add this web resource to the Form load libs.
Here is the complete code to be put in the form load event handler:
var context = GetGlobalContext();
// retireve the invoice record id (Opened Form)
var invoiceId = context.getQueryStringParameters().id;
var customerId;
//Retrieve the server url, which differs on-premise from on-line and
//shouldn't be hard-coded.
// this will return something like http://yourHostName/yourOrg
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT;
function SetDefaultCountryCode(countryFieldId, odataUri) {
odataUri = odataUri + '/ContactSet?$select=ContactId,FullName&$filter=FullName eq \'Ahmed Shawki\'';
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
}
One more thing, don't forget to check "Pass execution context as first parameter" box on the form properties.
EDIT: Beside adding the jQuery library into the form load event handler, add the Json2 lib as a web resource.
For more information about the REST Endpoint.
It is indeed possible to export and import records along with their guids, just not natively. You'd have to build an app that would export the data for you, then create identical records through the CRM API in the target environment. You just have to clear out fields that aren't valid for create (createdon, statecode, etc.) and just specify the same Guid. CRM will then create the record with that Guid.
The old 4.0 Configuration Data Tool does this. I can't recall if it works against a 2011 org, but it could be a starting point.

Resources