I am trying to create a map in javascript using apex:repeat tag but it's not working as per expectations.
Below is the VF page and controller I have created :
<apex:page controller="ProductFieldsTestController">
<script type="text/javascript">
var productIdMap = {};
<apex:repeat value="{!listProducts}" var="prods">
var newprod = new product();
<apex:repeat value="{!productFields}" var="fieldName">
var fieldName = '{!fieldName}';
var fieldValue = '{!prods[fieldName]}';
console.log('-------- FieldName = ' + fieldName)
if(isNaN(fieldValue)) {
console.log('String = ' + fieldValue);
newprod[fieldName] = '{!JSENCODE(prods[fieldName])}';
}else{
console.log('Number = ' + fieldValue);
newprod[fieldName] = '';
}
</apex:repeat>
productIdMap['{!prods.Id}'] = newprod;
</apex:repeat>
function product() {}
</script>
</apex:page>
public class ProductFieldsTestController {
public static Set<String> productFields = new Set<String>{'Id', 'Name', 'ProductCode', 'CreatedById', 'Test_Number__c' };
public ProductFieldsTestController() {
}
public List<Product2> getListProducts() {
List<Product2> products = [Select id, name, ProductCode, CreatedById, Test_Number__c from Product2 limit 1];
return products ;
}
public List<String> getProductFields () {
return new List<String>(productFields);
}
}
When I am trying to access the VF page , below exception is occurring:
Incorrect parameter type for function 'JSENCODE()'. Expected Text, received Number
Error is in expression '{!JSENCODE(prods[fieldName])}' in component <apex:repeat> in page productfieldstest
What I have noticed is that salesforce is trying to execute the JSENCODE line irrespective of the IF conditions. I have tried every possible way to make this happen, but no success. Can anyone please suggest what issue is this ?