-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
14Questions
-
6Replies
Hyperlink not working in LWC in datatable
Hi,
I want to dispay Name field as hyperlink in the datatable in lwc.below JS is not working as expected.i am getting blank rows.however i can see the linkName is returning value in console.log.I was albel to do that through lightning component but not sure why its not returning.
below is the JS file.
import { LightningElement, track } from 'lwc';
import serachAccs from '@salesforce/apex/accountSearchController.retriveAccs';
// datatable columns
const columns = [
{
label: 'Account Name', fieldName: 'linkName', type: 'url', sortable: true,
typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}
},
]
export default class AccountSearch extends LightningElement {
@track searchData;
@track columns = columns;
@track errorMsg = '';
strSearchAccName = '';
handleAccountName(event) {
this.strSearchAccName = event.detail.value;
}
handleSearch() {
if(!this.strSearchAccName) {
this.errorMsg = 'Please enter account name to search.';
this.searchData = undefined;
return;
}
serachAccs({strAccName : this.strSearchAccName})
.then(result => {
// console.log(result);
// result = Object.assign({}, result);
result.forEach(function(item) {
let obj = {linkName: '/' + item.Id};
let clone = Object.assign({}, obj);
// ChromeSamples.log(clone);
// Object.assign({item.linkName:item.Id});
console.log(item.Id);
// item.linkName= '/' + item.Id;
console.log("This is"+obj.linkName);
});
this.searchData = result;
})
}
}
Please help.
I want to dispay Name field as hyperlink in the datatable in lwc.below JS is not working as expected.i am getting blank rows.however i can see the linkName is returning value in console.log.I was albel to do that through lightning component but not sure why its not returning.
below is the JS file.
import { LightningElement, track } from 'lwc';
import serachAccs from '@salesforce/apex/accountSearchController.retriveAccs';
// datatable columns
const columns = [
{
label: 'Account Name', fieldName: 'linkName', type: 'url', sortable: true,
typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}
},
]
export default class AccountSearch extends LightningElement {
@track searchData;
@track columns = columns;
@track errorMsg = '';
strSearchAccName = '';
handleAccountName(event) {
this.strSearchAccName = event.detail.value;
}
handleSearch() {
if(!this.strSearchAccName) {
this.errorMsg = 'Please enter account name to search.';
this.searchData = undefined;
return;
}
serachAccs({strAccName : this.strSearchAccName})
.then(result => {
// console.log(result);
// result = Object.assign({}, result);
result.forEach(function(item) {
let obj = {linkName: '/' + item.Id};
let clone = Object.assign({}, obj);
// ChromeSamples.log(clone);
// Object.assign({item.linkName:item.Id});
console.log(item.Id);
// item.linkName= '/' + item.Id;
console.log("This is"+obj.linkName);
});
this.searchData = result;
})
}
}
Please help.
- BHASKAR GANGULY
- April 04, 2020
- Like
- 0
test classes run on destination org
HI,
I have a generic question arround running apex test classes before deploying to destination org.
I am running salesforce CLI command sfdx force:apex:test:run.
my question is how to run the test classes present in source folder before deploying that in destination org.
if a certain test class in not present in destination org will that fail?
if i am running the following command
sfdx force:apex:test:run -l RunLocalTests -d <path to outputdir> -u me@my.org
its running for all the test classes that is present in that destination org.
Please suggest.
Thanks,
Bhaskar
I have a generic question arround running apex test classes before deploying to destination org.
I am running salesforce CLI command sfdx force:apex:test:run.
my question is how to run the test classes present in source folder before deploying that in destination org.
if a certain test class in not present in destination org will that fail?
if i am running the following command
sfdx force:apex:test:run -l RunLocalTests -d <path to outputdir> -u me@my.org
its running for all the test classes that is present in that destination org.
Please suggest.
Thanks,
Bhaskar
- BHASKAR GANGULY
- May 29, 2019
- Like
- 0
Uncaught Action failed: c:SLR$controller$valChanged [Cannot read property 'config' of undefined]
Hi All,
I am getting the below error while trying to set customize error.
below is my controller code :
valChanged : function(component, event, helper) {
var newValue = event.getParam("value");
var oldValue = event.getParam("oldValue");
var epp= component.find("Selected_Claims_Service_Level__c");
var eppval = epp.get('v.value');
// alert(eppval);
// alert("value name changed from '" + oldValue + "' to '" + newValue + "'");
if(newValue =='')
{
alert("i am in");
component.find("Selected_Claims_Service_Level__c").set("v.errors", [{message:"This is not a right selection"}]);
}
},
below is my component code part.
<lightning:recordEditForm aura:id="formStep1"
recordId="{!v.recordId}"
objectApiName="Service_Level_Assessment__c"
onload="{!c.handleOnload}"
onsubmit="{!c.handleOnSubmit}"
onsuccess="{!c.nextTab}"
onerror="{!c.handleOnError}"
class="slds-card__body_inner">
<lightning:messages/>
<div class="slds-grid slds-gutters">
<div class="slds-col slds-size_1-of-2">
<lightning:inputField onchange="{!c.checkHelp}" disabled="{!v.isReadOnly}" aura:id="Selected_Claims_Service_Level__c" fieldName="Selected_Claims_Service_Level__c" value ="{!v.expenseName}" />
<a href="/resource/DTHServiceLevelClaimsPdf" target="_blank">Click here for descriptions</a>
</div>
Can somebody help me why i am getting this error?
I am getting the below error while trying to set customize error.
below is my controller code :
valChanged : function(component, event, helper) {
var newValue = event.getParam("value");
var oldValue = event.getParam("oldValue");
var epp= component.find("Selected_Claims_Service_Level__c");
var eppval = epp.get('v.value');
// alert(eppval);
// alert("value name changed from '" + oldValue + "' to '" + newValue + "'");
if(newValue =='')
{
alert("i am in");
component.find("Selected_Claims_Service_Level__c").set("v.errors", [{message:"This is not a right selection"}]);
}
},
below is my component code part.
<lightning:recordEditForm aura:id="formStep1"
recordId="{!v.recordId}"
objectApiName="Service_Level_Assessment__c"
onload="{!c.handleOnload}"
onsubmit="{!c.handleOnSubmit}"
onsuccess="{!c.nextTab}"
onerror="{!c.handleOnError}"
class="slds-card__body_inner">
<lightning:messages/>
<div class="slds-grid slds-gutters">
<div class="slds-col slds-size_1-of-2">
<lightning:inputField onchange="{!c.checkHelp}" disabled="{!v.isReadOnly}" aura:id="Selected_Claims_Service_Level__c" fieldName="Selected_Claims_Service_Level__c" value ="{!v.expenseName}" />
<a href="/resource/DTHServiceLevelClaimsPdf" target="_blank">Click here for descriptions</a>
</div>
Can somebody help me why i am getting this error?
- BHASKAR GANGULY
- May 21, 2019
- Like
- 0
This command is required to run from within an SFDX project.
Hi All,
While running the below CLI command
sfdx force:source:deploy -x C:\Users\COG12537\Desktop\sfdx\sfdx2\manifest\package.xml -u myorg
i am getting the below error.
This command is required to run from within an SFDX project.
However this is a dx project.Please help me understnd the issue.
Thanks,
Bhaskar
While running the below CLI command
sfdx force:source:deploy -x C:\Users\COG12537\Desktop\sfdx\sfdx2\manifest\package.xml -u myorg
i am getting the below error.
This command is required to run from within an SFDX project.
However this is a dx project.Please help me understnd the issue.
Thanks,
Bhaskar
- BHASKAR GANGULY
- May 14, 2019
- Like
- 0
sfdx command not working after npm install --global sfdx-cli
Hi All,
i have node.js installed in my pcversion is v.8.12,0.
i am trying to install salesforce cli by using npm install --global sfdx-cli command.
the install seems to be successful as its extracting all the metadata.However after installation while running the SFDX command its not working.Also i was not able to find any folder created as a result of cli installation.
Can anybody help me here.
Thanks,
Bhaskar
i have node.js installed in my pcversion is v.8.12,0.
i am trying to install salesforce cli by using npm install --global sfdx-cli command.
the install seems to be successful as its extracting all the metadata.However after installation while running the SFDX command its not working.Also i was not able to find any folder created as a result of cli installation.
Can anybody help me here.
Thanks,
Bhaskar
- BHASKAR GANGULY
- April 11, 2019
- Like
- 0
automate deployment through jenkins pr
Hi,
i am trying to enable Continuous integration and delivery for one of my projects with salesforce DX,.My requirement is whenever a push happens in Github it should connect to jenkins.As part of continuos integration i want to authorize devhub,create the scratch org,push the source code to scratch org,test apex classes and then deploy the code in some other target org. I was able to do all the steps till test apex classes. My confusion is how to deploy the source code to some other target org as i don't want to deploy the code to dev hub org.Do i need to set up JWT for the target org as well along with the connected app and extra set of environment variables. Please guide me here. Please find below the github repository for the working jenkins file. https://github.com/bganguly1984/Jenkinsdemo/blob/newb/Jenkinsfile
Thanks,
Bhaskar
i am trying to enable Continuous integration and delivery for one of my projects with salesforce DX,.My requirement is whenever a push happens in Github it should connect to jenkins.As part of continuos integration i want to authorize devhub,create the scratch org,push the source code to scratch org,test apex classes and then deploy the code in some other target org. I was able to do all the steps till test apex classes. My confusion is how to deploy the source code to some other target org as i don't want to deploy the code to dev hub org.Do i need to set up JWT for the target org as well along with the connected app and extra set of environment variables. Please guide me here. Please find below the github repository for the working jenkins file. https://github.com/bganguly1984/Jenkinsdemo/blob/newb/Jenkinsfile
Thanks,
Bhaskar
- BHASKAR GANGULY
- April 03, 2019
- Like
- 0
jason.deserialize is returning null
Hi All,
i am trying to parsing the below jason into my object.but while using the deserialize method its comming as Null.
not sure what i am missinh here.
Jason response :
{"invoiceList":[{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],"invoiceNumber":1},{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}]}
Wrapper class for data structure :
public class WrapperListinvoice {
public List<invoicelist> invoicepp;
public class invoicelist{
public double totalprice;
public DateTime Statementdate;
public list<Lineitems> sline;
public integer invoicenum;
}
public class Lineitems{
public double unitprice;
public double quantity;
public string productname;
}
}
calling class :
HttpRequest res= new HttpRequest();
res.setEndpoint('https://docsample.herokuapp.com/jsonSample');
res.setMethod('GET');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Accept','application/json');
Http hes= new Http();
httpresponse repp=hes.send(res);
string s=repp.getBody();
integer status =repp.getStatusCode();
//list<responseBean> assp= new list<responseBean>();
WrapperListinvoice responseBean=(WrapperListinvoice) JSON.deserialize(s,WrapperListinvoice.class);
system.debug(responseBean);
Can somebody please help me to understand what i am missing here.
Thanks,
Bhaskar
i am trying to parsing the below jason into my object.but while using the deserialize method its comming as Null.
not sure what i am missinh here.
Jason response :
{"invoiceList":[{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],"invoiceNumber":1},{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}]}
Wrapper class for data structure :
public class WrapperListinvoice {
public List<invoicelist> invoicepp;
public class invoicelist{
public double totalprice;
public DateTime Statementdate;
public list<Lineitems> sline;
public integer invoicenum;
}
public class Lineitems{
public double unitprice;
public double quantity;
public string productname;
}
}
calling class :
HttpRequest res= new HttpRequest();
res.setEndpoint('https://docsample.herokuapp.com/jsonSample');
res.setMethod('GET');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Accept','application/json');
Http hes= new Http();
httpresponse repp=hes.send(res);
string s=repp.getBody();
integer status =repp.getStatusCode();
//list<responseBean> assp= new list<responseBean>();
WrapperListinvoice responseBean=(WrapperListinvoice) JSON.deserialize(s,WrapperListinvoice.class);
system.debug(responseBean);
Can somebody please help me to understand what i am missing here.
Thanks,
Bhaskar
- BHASKAR GANGULY
- January 18, 2019
- Like
- 0
Apex Advanced superbadge Challange 8 :Challenge Not yet complete... here's what's wrong: Ensure that product2Controller is still working as specified in the earlier challenge.
Hi All,
i am gettingbelow error while trying to verify this.
Challenge Not yet complete... here's what's wrong:
Ensure that product2Controller is still working as specified in the earlier challenge.
Someone please help me to get it through.i am stuck on this for last couple of days.
Below are my classes :
Constants :
public class Constants {
public static final Integer DEFAULT_ROWS = 5;
public static final String SELECT_ONE = Label.Select_One;
public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low;
public static final List<Schema.PicklistEntry> PRODUCT_FAMILY = Product2.Family.getDescribe().getPicklistValues();
public static final String DRAFT_ORDER_STATUS = 'Draft';
public static final String ACTIVATED_ORDER_STATUS = 'Activated';
public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements';
public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.';
public static final Id STANDARD_PRICEBOOK_ID = '01s6A0000031LaYQAU'; //Test.isRunningTest() ? Test.getStandardPricebookId() : [SELECT Id FROM PriceBook2 WHERE isStandard = true LIMIT 1].Id;
}
AnnouncementQueueable
/**
* @name AnnouncementQueueable
* @description This class posts Chatter Announcements
**/
public class AnnouncementQueueable implements system.Queueable{
public List<ConnectApi.AnnouncementInput> toPost;
public AnnouncementQueueable(List<ConnectApi.AnnouncementInput> toPost){
this.toPost = toPost;
}
public void execute(QueueableContext context){
PostAnnouncements(toPost);
}
/**
* @name postAnnouncements
* @description This method is provided for you to facilitate the Super Badge
**/
public static void PostAnnouncements(List<ConnectApi.AnnouncementInput> announcements){
while ( announcements.size() > 0 ){
if ( Limits.getDMLStatements() < Limits.getLimitDMLStatements() && !test.isRunningTest()){
ConnectApi.AnnouncementInput a = announcements.remove(0);
ConnectApi.Announcements.postAnnouncement('internal', a);
} else {
AnnouncementQueueable announcementQueuable = new AnnouncementQueueable(announcements);
break;
}
}
if (announcements.size() > 0 && !test.isRunningTest()){
AnnouncementQueueable q = new AnnouncementQueueable(announcements);
System.enqueueJob(q);
//ToDo: Enqueue the above instance of announcementQueueable
}
}
}
ChartHelper
public without sharing class ChartHelper {
@AuraEnabled// Make sure annotation should be applied for this method
public static List<chartData> GetInventory(){
List<chartData> cht = new List<chartData>();
for(AggregateResult ar : [SELECT Family family, Sum(Quantity_Remaining__c) total
FROM Product2
WHERE Quantity_Remaining__c > 0 GROUP BY Family]){
cht.add(new chartData((String)ar.get('family'), Integer.valueOf(ar.get('total'))));
}
return cht;
}
public class ChartData {
public String name {get;set;}
public Decimal val {get;set;}
public ChartData(String name, Decimal val){
this.name = name;
this.val = val;
}
}
}
OrderExtension:
/**
* @name OrderExtension
* @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {
public Order orderRecord {get;set;}
public List<OrderItem> orderItemList {get;set;}
public String selectedFamily {get;set;}
public List<chartHelper.chartData> pieData {get;set;}
public Decimal total {get;set;}
public Map<Id,OrderItem> orderItemMap;
ApexPages.StandardSetController standardSetController;
public OrderExtension(ApexPages.StandardController standardController){
orderRecord = (Order)standardController.getRecord();
orderItemMap = new Map<id,OrderItem>();
if ( orderRecord.Id != null ){
orderRecord = queryOrderRecord(orderRecord.Id);
}
resetSsc();
total = 0;
for (OrderItem oi : orderRecord.OrderItems) {
orderItemMap.put(oi.Product2Id, oi);
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<ChartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
total += oi.UnitPrice * oi.Quantity;
}
}
PopulateOrderItems();
}
void resetSsc() {
String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
+ ' FROM PricebookEntry WHERE IsActive = TRUE';
if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
query += ' AND Product2.Family = \'' + selectedFamily + '\'';
}
query += ' ORDER BY Name';
standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
standardSetController.setPageSize(Constants.DEFAULT_ROWS);
}
//ToDo: Implement your own method to populate orderItemList
// that you will call after pagination and/or family selection
void PopulateOrderItems() {
orderItemList = new List<OrderItem>();
for (SObject obj : standardSetController.getRecords()) {
PricebookEntry pbe = (PricebookEntry)obj;
if (orderItemMap.containsKey(pbe.Product2Id)) {
orderItemList.add(orderItemMap.get(pbe.Product2Id));
} else {
orderItemList.add(new OrderItem(
PricebookEntryId=pbe.Id,
Product2Id=pbe.Product2Id,
UnitPrice=pbe.UnitPrice,
Quantity=0,
Product2=pbe.Product2
));
}
}
}
/**
* @name OnFieldChange
* @description
**/
public void OnFieldChange(){
//ToDo: Implement logic to store the values changed on the page
for (OrderItem oi : orderItemList) {
orderItemMap.put(oi.Product2Id, oi);
}
// and populate pieData
pieData = null;
total = 0;
for (OrderItem oi : orderItemMap.values()) {
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<chartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
// and populate total
total += oi.UnitPrice * oi.Quantity;
}
}
}
/**
* @name SelectFamily
* @description
**/
public void SelectFamily(){
//ToDo: Implement logic to filter based on the selected product family
resetSsc();
PopulateOrderItems();
}
/**
* @name Save
* @description
**/
public void Save(){
//ToDo: Implement logic to save the Order and populated OrderItems
System.Savepoint sp = Database.setSavepoint();
try {
if (null == orderRecord.Pricebook2Id) {
orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
}
upsert orderRecord;
List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
List<OrderItem> orderItemsToDelete = new List<OrderItem>();
for (OrderItem oi : orderItemList) {
if (oi.Quantity > 0) {
if (null == oi.OrderId) {
oi.OrderId = orderRecord.Id;
}
orderItemsToUpsert.add(oi);
} else if (oi.Id != null) {
orderItemsToDelete.add(oi);
}
}
upsert orderItemsToUpsert;
delete orderItemsToDelete;
} catch (Exception e) {
Database.rollback(sp);
apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
}
}
/**
* @name First
* @description
**/
public void First(){
standardSetController.first();
PopulateOrderItems();
}
/**
* @name Next
* @description
**/
public void Next(){
standardSetController.next();
PopulateOrderItems();
}
/**
* @name Previous
* @description
**/
public void Previous(){
standardSetController.previous();
PopulateOrderItems();
}
/**
* @name Last
* @description
**/
public void Last(){
standardSetController.last();
PopulateOrderItems();
}
/**
* @name GetHasPrevious
* @description
**/
public Boolean GetHasPrevious(){
return standardSetController.getHasPrevious();
}
/**
* @name GetHasNext
* @description
**/
public Boolean GetHasNext(){
return standardSetController.getHasNext();
}
/**
* @name GetTotalPages
* @description
**/
public Integer GetTotalPages(){
return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
}
/**
* @name GetPageNumber
* @description
**/
public Integer GetPageNumber(){
return standardSetController.getPageNumber();
}
/**
* @name GetFamilyOptions
* @description
**/
public List<SelectOption> GetFamilyOptions() {
List<SelectOption> options = new List<SelectOption>{
new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
};
for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
options.add(new SelectOption(ple.getValue(), ple.getLabel()));
}
return options;
}
/**
* @name QueryOrderRecord
* @description
**/
public static Order QueryOrderRecord(Id orderId){
return [
SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
(
SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
FROM OrderItems
)
FROM Order
WHERE Id = :orderId
];
}
}
OrderHelper :
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for (Integer i = 0; i < newList.size(); i++) {
if(newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS) {
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity FROM OrderItem WHERE OrderId In :activatedOrderIds];
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
for(OrderItem oi : items) {
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN:productIds]);
AggregateResult[] aggregatedResults = [SELECT Product2Id, SUM(Quantity) aggregatedQuantity FROM OrderItem WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : aggregatedResults) {
productMap.get((String)ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('aggregatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap != null && productMap.size() > 0) {
update productMap.values();
}
}
}
OrderTests:
@isTest(SeeAllData=true)
public class OrderTests {
public static Map<String, List<Object>> testData;
@isTest static void OrderUpdate_UnitTest (){
// TestDataFactory.InsertTestData(5);
// List<Account> accts=new List<Account>();
Account a=new Account();
a.Name='Account';
a.Rating='Hot';
insert a;
List<Order> orders=new List<Order>();
// Integer k=0;
//Contract c=new Contract(AccountId=accts.get(k).Id,Status='Draft',StartDate =date.today(),ContractTerm =12);
Order o=new Order();
o.AccountId=a.Id;
o.EffectiveDate=date.today();
//o.Pricebook2Id='01s6A0000031LaYQAU';
//o.ContractId=c.Id ;
o.Status='Draft';
// k++;
insert o;
List<Product2> pros=new List<Product2>();
Integer picklistSize=Constants.PRODUCT_FAMILY.size();
Integer j=0;
for(Integer s=0;s<5;s++){
Product2 p=new Product2();
p.Name='Side';
p.IsActive=true;
p.Initial_Inventory__c =10;
p.Family=Constants.PRODUCT_FAMILY[j].getValue();
p.Quantity_Ordered__c=10;
if(j==picklistSize-1){
j=0;
}else{
j++;
}
pros.add(p);
}
insert pros;
Order rec = [select id, Status from Order limit 1];
Product2 prod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 where name ='Side' limit 1];
system.debug('product2Controller => '+prod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c => '+prod.Quantity_Remaining__c);
rec.status = constants.ACTIVATED_ORDER_STATUS;
Update rec;
Product2 updatedprod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 Where name ='Side' limit 1];
system.debug('itial_Inventory__c =>'+updatedprod.Initial_Inventory__c);
system.debug('Quantity_Ordered__c =>'+updatedprod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c =>'+updatedprod.Quantity_Remaining__c);
TestDataFactory.VerifyQuantityOrdered(prod,updatedprod,constants.DEFAULT_ROWS);
//upsert updatedprod;
}
@isTest(SeeAllData=true) static void OrderExtension_UnitTest(){
Order rec = [select id, Status from Order limit 1];
PageReference pageRef = Page.OrderEdit;
Test.setCurrentPage(pageRef);
pageRef.getParameters().put('id',rec.id);
ApexPages.StandardController sc = new ApexPages.standardController(rec);
OrderExtension cc = new OrderExtension(sc);
cc.SelectFamily();
cc.OnFieldChange();
cc.Save();
cc.First();
cc.Next();
cc.Previous();
cc.Last();
cc.GetHasPrevious();
cc.GetHasNext();
cc.GetTotalPages();
cc.GetFamilyOptions();
ChartHelper.GetInventory();
//Constants.getStdPriceBook();
}
//@testSetup static void SetupTestData (){
//}
}
Thanks,
BHaskar
i am gettingbelow error while trying to verify this.
Challenge Not yet complete... here's what's wrong:
Ensure that product2Controller is still working as specified in the earlier challenge.
Someone please help me to get it through.i am stuck on this for last couple of days.
Below are my classes :
Constants :
public class Constants {
public static final Integer DEFAULT_ROWS = 5;
public static final String SELECT_ONE = Label.Select_One;
public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low;
public static final List<Schema.PicklistEntry> PRODUCT_FAMILY = Product2.Family.getDescribe().getPicklistValues();
public static final String DRAFT_ORDER_STATUS = 'Draft';
public static final String ACTIVATED_ORDER_STATUS = 'Activated';
public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements';
public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.';
public static final Id STANDARD_PRICEBOOK_ID = '01s6A0000031LaYQAU'; //Test.isRunningTest() ? Test.getStandardPricebookId() : [SELECT Id FROM PriceBook2 WHERE isStandard = true LIMIT 1].Id;
}
AnnouncementQueueable
/**
* @name AnnouncementQueueable
* @description This class posts Chatter Announcements
**/
public class AnnouncementQueueable implements system.Queueable{
public List<ConnectApi.AnnouncementInput> toPost;
public AnnouncementQueueable(List<ConnectApi.AnnouncementInput> toPost){
this.toPost = toPost;
}
public void execute(QueueableContext context){
PostAnnouncements(toPost);
}
/**
* @name postAnnouncements
* @description This method is provided for you to facilitate the Super Badge
**/
public static void PostAnnouncements(List<ConnectApi.AnnouncementInput> announcements){
while ( announcements.size() > 0 ){
if ( Limits.getDMLStatements() < Limits.getLimitDMLStatements() && !test.isRunningTest()){
ConnectApi.AnnouncementInput a = announcements.remove(0);
ConnectApi.Announcements.postAnnouncement('internal', a);
} else {
AnnouncementQueueable announcementQueuable = new AnnouncementQueueable(announcements);
break;
}
}
if (announcements.size() > 0 && !test.isRunningTest()){
AnnouncementQueueable q = new AnnouncementQueueable(announcements);
System.enqueueJob(q);
//ToDo: Enqueue the above instance of announcementQueueable
}
}
}
ChartHelper
public without sharing class ChartHelper {
@AuraEnabled// Make sure annotation should be applied for this method
public static List<chartData> GetInventory(){
List<chartData> cht = new List<chartData>();
for(AggregateResult ar : [SELECT Family family, Sum(Quantity_Remaining__c) total
FROM Product2
WHERE Quantity_Remaining__c > 0 GROUP BY Family]){
cht.add(new chartData((String)ar.get('family'), Integer.valueOf(ar.get('total'))));
}
return cht;
}
public class ChartData {
public String name {get;set;}
public Decimal val {get;set;}
public ChartData(String name, Decimal val){
this.name = name;
this.val = val;
}
}
}
OrderExtension:
/**
* @name OrderExtension
* @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {
public Order orderRecord {get;set;}
public List<OrderItem> orderItemList {get;set;}
public String selectedFamily {get;set;}
public List<chartHelper.chartData> pieData {get;set;}
public Decimal total {get;set;}
public Map<Id,OrderItem> orderItemMap;
ApexPages.StandardSetController standardSetController;
public OrderExtension(ApexPages.StandardController standardController){
orderRecord = (Order)standardController.getRecord();
orderItemMap = new Map<id,OrderItem>();
if ( orderRecord.Id != null ){
orderRecord = queryOrderRecord(orderRecord.Id);
}
resetSsc();
total = 0;
for (OrderItem oi : orderRecord.OrderItems) {
orderItemMap.put(oi.Product2Id, oi);
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<ChartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
total += oi.UnitPrice * oi.Quantity;
}
}
PopulateOrderItems();
}
void resetSsc() {
String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
+ ' FROM PricebookEntry WHERE IsActive = TRUE';
if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
query += ' AND Product2.Family = \'' + selectedFamily + '\'';
}
query += ' ORDER BY Name';
standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
standardSetController.setPageSize(Constants.DEFAULT_ROWS);
}
//ToDo: Implement your own method to populate orderItemList
// that you will call after pagination and/or family selection
void PopulateOrderItems() {
orderItemList = new List<OrderItem>();
for (SObject obj : standardSetController.getRecords()) {
PricebookEntry pbe = (PricebookEntry)obj;
if (orderItemMap.containsKey(pbe.Product2Id)) {
orderItemList.add(orderItemMap.get(pbe.Product2Id));
} else {
orderItemList.add(new OrderItem(
PricebookEntryId=pbe.Id,
Product2Id=pbe.Product2Id,
UnitPrice=pbe.UnitPrice,
Quantity=0,
Product2=pbe.Product2
));
}
}
}
/**
* @name OnFieldChange
* @description
**/
public void OnFieldChange(){
//ToDo: Implement logic to store the values changed on the page
for (OrderItem oi : orderItemList) {
orderItemMap.put(oi.Product2Id, oi);
}
// and populate pieData
pieData = null;
total = 0;
for (OrderItem oi : orderItemMap.values()) {
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<chartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
// and populate total
total += oi.UnitPrice * oi.Quantity;
}
}
}
/**
* @name SelectFamily
* @description
**/
public void SelectFamily(){
//ToDo: Implement logic to filter based on the selected product family
resetSsc();
PopulateOrderItems();
}
/**
* @name Save
* @description
**/
public void Save(){
//ToDo: Implement logic to save the Order and populated OrderItems
System.Savepoint sp = Database.setSavepoint();
try {
if (null == orderRecord.Pricebook2Id) {
orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
}
upsert orderRecord;
List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
List<OrderItem> orderItemsToDelete = new List<OrderItem>();
for (OrderItem oi : orderItemList) {
if (oi.Quantity > 0) {
if (null == oi.OrderId) {
oi.OrderId = orderRecord.Id;
}
orderItemsToUpsert.add(oi);
} else if (oi.Id != null) {
orderItemsToDelete.add(oi);
}
}
upsert orderItemsToUpsert;
delete orderItemsToDelete;
} catch (Exception e) {
Database.rollback(sp);
apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
}
}
/**
* @name First
* @description
**/
public void First(){
standardSetController.first();
PopulateOrderItems();
}
/**
* @name Next
* @description
**/
public void Next(){
standardSetController.next();
PopulateOrderItems();
}
/**
* @name Previous
* @description
**/
public void Previous(){
standardSetController.previous();
PopulateOrderItems();
}
/**
* @name Last
* @description
**/
public void Last(){
standardSetController.last();
PopulateOrderItems();
}
/**
* @name GetHasPrevious
* @description
**/
public Boolean GetHasPrevious(){
return standardSetController.getHasPrevious();
}
/**
* @name GetHasNext
* @description
**/
public Boolean GetHasNext(){
return standardSetController.getHasNext();
}
/**
* @name GetTotalPages
* @description
**/
public Integer GetTotalPages(){
return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
}
/**
* @name GetPageNumber
* @description
**/
public Integer GetPageNumber(){
return standardSetController.getPageNumber();
}
/**
* @name GetFamilyOptions
* @description
**/
public List<SelectOption> GetFamilyOptions() {
List<SelectOption> options = new List<SelectOption>{
new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
};
for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
options.add(new SelectOption(ple.getValue(), ple.getLabel()));
}
return options;
}
/**
* @name QueryOrderRecord
* @description
**/
public static Order QueryOrderRecord(Id orderId){
return [
SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
(
SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
FROM OrderItems
)
FROM Order
WHERE Id = :orderId
];
}
}
OrderHelper :
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for (Integer i = 0; i < newList.size(); i++) {
if(newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS) {
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity FROM OrderItem WHERE OrderId In :activatedOrderIds];
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
for(OrderItem oi : items) {
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN:productIds]);
AggregateResult[] aggregatedResults = [SELECT Product2Id, SUM(Quantity) aggregatedQuantity FROM OrderItem WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : aggregatedResults) {
productMap.get((String)ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('aggregatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap != null && productMap.size() > 0) {
update productMap.values();
}
}
}
OrderTests:
@isTest(SeeAllData=true)
public class OrderTests {
public static Map<String, List<Object>> testData;
@isTest static void OrderUpdate_UnitTest (){
// TestDataFactory.InsertTestData(5);
// List<Account> accts=new List<Account>();
Account a=new Account();
a.Name='Account';
a.Rating='Hot';
insert a;
List<Order> orders=new List<Order>();
// Integer k=0;
//Contract c=new Contract(AccountId=accts.get(k).Id,Status='Draft',StartDate =date.today(),ContractTerm =12);
Order o=new Order();
o.AccountId=a.Id;
o.EffectiveDate=date.today();
//o.Pricebook2Id='01s6A0000031LaYQAU';
//o.ContractId=c.Id ;
o.Status='Draft';
// k++;
insert o;
List<Product2> pros=new List<Product2>();
Integer picklistSize=Constants.PRODUCT_FAMILY.size();
Integer j=0;
for(Integer s=0;s<5;s++){
Product2 p=new Product2();
p.Name='Side';
p.IsActive=true;
p.Initial_Inventory__c =10;
p.Family=Constants.PRODUCT_FAMILY[j].getValue();
p.Quantity_Ordered__c=10;
if(j==picklistSize-1){
j=0;
}else{
j++;
}
pros.add(p);
}
insert pros;
Order rec = [select id, Status from Order limit 1];
Product2 prod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 where name ='Side' limit 1];
system.debug('product2Controller => '+prod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c => '+prod.Quantity_Remaining__c);
rec.status = constants.ACTIVATED_ORDER_STATUS;
Update rec;
Product2 updatedprod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 Where name ='Side' limit 1];
system.debug('itial_Inventory__c =>'+updatedprod.Initial_Inventory__c);
system.debug('Quantity_Ordered__c =>'+updatedprod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c =>'+updatedprod.Quantity_Remaining__c);
TestDataFactory.VerifyQuantityOrdered(prod,updatedprod,constants.DEFAULT_ROWS);
//upsert updatedprod;
}
@isTest(SeeAllData=true) static void OrderExtension_UnitTest(){
Order rec = [select id, Status from Order limit 1];
PageReference pageRef = Page.OrderEdit;
Test.setCurrentPage(pageRef);
pageRef.getParameters().put('id',rec.id);
ApexPages.StandardController sc = new ApexPages.standardController(rec);
OrderExtension cc = new OrderExtension(sc);
cc.SelectFamily();
cc.OnFieldChange();
cc.Save();
cc.First();
cc.Next();
cc.Previous();
cc.Last();
cc.GetHasPrevious();
cc.GetHasNext();
cc.GetTotalPages();
cc.GetFamilyOptions();
ChartHelper.GetInventory();
//Constants.getStdPriceBook();
}
//@testSetup static void SetupTestData (){
//}
}
Thanks,
BHaskar
- BHASKAR GANGULY
- October 25, 2018
- Like
- 0
too many DML apex superbadge
HI,
i am doing the Apex Specialist superbadge.I have completed the 1st 3 challenges successfully.
while doing the 4 th challenge i am getting govornence limits exception for bulk testing.
can some body please verify my code and tell me what is the problem here.i am stuck in this for lat 2 days.Please help.
below is my code :
This is the Trigger :
trigger MaintenanceRequest on Case (before update, after update) {
// call MaintenanceRequestHelper.updateWorkOrders
//list<case> scase1=[select id from case where id in := trigger.new.id limit 200];
// set<Id> ccase=new set<Id>();
if(trigger.isafter)
{
for(Case c:trigger.new)
{
if((c.Type=='Routine Maintenance' || c.Type=='Repair'))
{
if(c.status=='Closed')
{
// c.adderror('Hi this is bhaskar');
//ccase.add(c.id);
MaintenanceRequestHelper.updateWorkOrders(trigger.new);
}
}
}
}
}
Helper Class :
public class MaintenanceRequestHelper {
public static void updateWorkOrders(list<case> scase){
list<case> acc= new list<Case>();
// list<product2> pp =[select Maintenance_Cycle__c,(select id from case) from product2];
// scase=[select id from case where id in :limit 200];
list<id> sid= new list<id>();
for(case aa:scase)
{
sid.add(aa.Equipment__c);
}
system.debug('sid :'+sid.size());
list<product2> sp=[select id,Maintenance_Cycle__c from product2 where Id =:sid];
system.debug(sp.size());
Map<id, product2> emailToUserMap = new Map<id, product2>();
for (product2 u : sp) {
emailToUserMap.put(u.id, u);
}
for(case a:scase)
{
// product2 p=[select Maintenance_Cycle__c from product2 where Id =:a.Equipment__c];
// double p1= double.valueOf(emailToUserMap.get(Maintenance_Cycle__c));
product2 pp= new product2();
pp= emailToUserMap.get(a.Equipment__c);
decimal p= pp.Maintenance_Cycle__c;
integer p2=p.intValue();
acc.add(new case(type='Routine Maintenance',status='New',Vehicle__c=a.Vehicle__c,Equipment__c=a.Equipment__c,subject='New Routin Maintenance',Date_Reported__c=system.today(),Date_Due__c=(system.today()+p2)));
// a.Date_Due__c
}
insert acc;
}
}
Test class :
/*
* This class can be safely deleted from your org.
* It was only used to ensure 100% test coverage
* for the managed package installation.
*/
@IsTest
private class InstallationTests {
static testmethod void testMaintenancebulkRequest()
{
list<case> a= new list<case>();
list<case> aa= new list<case>();
Vehicle__c v=new Vehicle__c(name='Test BMV');
insert v;
product2 p=new product2(name='Test Product',Maintenance_Cycle__c=10);
insert p;
for(integer i =0;i<200;i++)
{
a.add(new case(type='Repair',status='New'));
}
test.startTest();
insert a;
for(case cc:a)
{
cc.Status='Closed';
cc.Vehicle__c=v.id;
cc.Equipment__c=p.id;
aa.add(cc);
}
// system.debug(aa.size());
update aa;
test.stopTest();
}
}
Thanks,
Bhaskar
i am doing the Apex Specialist superbadge.I have completed the 1st 3 challenges successfully.
while doing the 4 th challenge i am getting govornence limits exception for bulk testing.
can some body please verify my code and tell me what is the problem here.i am stuck in this for lat 2 days.Please help.
below is my code :
This is the Trigger :
trigger MaintenanceRequest on Case (before update, after update) {
// call MaintenanceRequestHelper.updateWorkOrders
//list<case> scase1=[select id from case where id in := trigger.new.id limit 200];
// set<Id> ccase=new set<Id>();
if(trigger.isafter)
{
for(Case c:trigger.new)
{
if((c.Type=='Routine Maintenance' || c.Type=='Repair'))
{
if(c.status=='Closed')
{
// c.adderror('Hi this is bhaskar');
//ccase.add(c.id);
MaintenanceRequestHelper.updateWorkOrders(trigger.new);
}
}
}
}
}
Helper Class :
public class MaintenanceRequestHelper {
public static void updateWorkOrders(list<case> scase){
list<case> acc= new list<Case>();
// list<product2> pp =[select Maintenance_Cycle__c,(select id from case) from product2];
// scase=[select id from case where id in :limit 200];
list<id> sid= new list<id>();
for(case aa:scase)
{
sid.add(aa.Equipment__c);
}
system.debug('sid :'+sid.size());
list<product2> sp=[select id,Maintenance_Cycle__c from product2 where Id =:sid];
system.debug(sp.size());
Map<id, product2> emailToUserMap = new Map<id, product2>();
for (product2 u : sp) {
emailToUserMap.put(u.id, u);
}
for(case a:scase)
{
// product2 p=[select Maintenance_Cycle__c from product2 where Id =:a.Equipment__c];
// double p1= double.valueOf(emailToUserMap.get(Maintenance_Cycle__c));
product2 pp= new product2();
pp= emailToUserMap.get(a.Equipment__c);
decimal p= pp.Maintenance_Cycle__c;
integer p2=p.intValue();
acc.add(new case(type='Routine Maintenance',status='New',Vehicle__c=a.Vehicle__c,Equipment__c=a.Equipment__c,subject='New Routin Maintenance',Date_Reported__c=system.today(),Date_Due__c=(system.today()+p2)));
// a.Date_Due__c
}
insert acc;
}
}
Test class :
/*
* This class can be safely deleted from your org.
* It was only used to ensure 100% test coverage
* for the managed package installation.
*/
@IsTest
private class InstallationTests {
static testmethod void testMaintenancebulkRequest()
{
list<case> a= new list<case>();
list<case> aa= new list<case>();
Vehicle__c v=new Vehicle__c(name='Test BMV');
insert v;
product2 p=new product2(name='Test Product',Maintenance_Cycle__c=10);
insert p;
for(integer i =0;i<200;i++)
{
a.add(new case(type='Repair',status='New'));
}
test.startTest();
insert a;
for(case cc:a)
{
cc.Status='Closed';
cc.Vehicle__c=v.id;
cc.Equipment__c=p.id;
aa.add(cc);
}
// system.debug(aa.size());
update aa;
test.stopTest();
}
}
Thanks,
Bhaskar
- BHASKAR GANGULY
- August 27, 2018
- Like
- 0
Wrapper Class issue in Inbound webservice
Hi,
I am new to Salesforce.
I am creating a Apex Soap Inbound WSDL where i want to inserrt multiple Account and its Child Comtacts in a single Request.
I trired with Wrapper class.But as i did not mentioned the Account and List<Contact> as Webservice i am getting error while calling through SOAP UI.
I was also can't make Account and Contact as Webservice as the size of the WSDL was extremly huge.I want to make this WSDL generic.
Can anyone please guide me here.
i want to make my webservice generic.
This is my Code below :
global class createaccountcontact{
global class Wrapperaccountcon{
Account acc1;
List<Contact> con;
}
webservice static list<string> createacc(list<Wrapperaccountcon> acc)
{
list<string> app = new list<String>();
for(Wrapperaccountcon accon : acc)
{
Account a = new Account();
a.name = accon.acc1.name;
insert a;
for(Contact c:accon.con)
{
Contact conc = new Contact();
//conc.lastname=accon.con.lastname;
insert conc;
conc.accountid= a.Id;
update conc;
}
app.add(a.Id);
}
return app;
}
}
I am new to Salesforce.
I am creating a Apex Soap Inbound WSDL where i want to inserrt multiple Account and its Child Comtacts in a single Request.
I trired with Wrapper class.But as i did not mentioned the Account and List<Contact> as Webservice i am getting error while calling through SOAP UI.
I was also can't make Account and Contact as Webservice as the size of the WSDL was extremly huge.I want to make this WSDL generic.
Can anyone please guide me here.
i want to make my webservice generic.
This is my Code below :
global class createaccountcontact{
global class Wrapperaccountcon{
Account acc1;
List<Contact> con;
}
webservice static list<string> createacc(list<Wrapperaccountcon> acc)
{
list<string> app = new list<String>();
for(Wrapperaccountcon accon : acc)
{
Account a = new Account();
a.name = accon.acc1.name;
insert a;
for(Contact c:accon.con)
{
Contact conc = new Contact();
//conc.lastname=accon.con.lastname;
insert conc;
conc.accountid= a.Id;
update conc;
}
app.add(a.Id);
}
return app;
}
}
- BHASKAR GANGULY
- January 22, 2018
- Like
- 0
issue testing webservice callouts soap
Hi,
i am getting null object error while trying to test the Mock of a webservice callout.
following is my WSDL2Apex class generated :
//Generated by wsdl2apex
public class parksServices {
public class byCountryResponse {
public String[] return_x;
private String[] return_x_type_info = new String[]{'return','http://parks.services/',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};
private String[] field_order_type_info = new String[]{'return_x'};
}
public class byCountry {
public String arg0;
private String[] arg0_type_info = new String[]{'arg0','http://parks.services/',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};
private String[] field_order_type_info = new String[]{'arg0'};
}
public class ParksImplPort {
public String endpoint_x = 'https://th-apex-soap-service.herokuapp.com/service/parks';
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://parks.services/', 'parksServices'};
public String[] byCountry(String arg0) {
parksServices.byCountry request_x = new parksServices.byCountry();
request_x.arg0 = arg0;
parksServices.byCountryResponse response_x;
Map<String, parksServices.byCountryResponse> response_map_x = new Map<String, parksServices.byCountryResponse>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'',
'http://parks.services/',
'byCountry',
'http://parks.services/',
'byCountryResponse',
'parksServices.byCountryResponse'}
);
response_x = response_map_x.get('response_x');
return response_x.return_x;
}
}
}
My Main Callout class :
public class Parkstub {
public static list<string> parkstub1( string a)
{
parksServices.ParksImplPort parklist = new parksServices.ParksImplPort();
return parklist.byCountry(a);
}
}
Mock Class
@isTest
global class ParkstubMock implements WebServiceMock {
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
// start - specify the response you want to send
parksServices.byCountryResponse response_x1 = new parksServices.byCountryResponse();
response_x1.return_x.add('Yellowstone');
response_x1.return_x.add('Mackinac National Park');
response_x1.return_x.add('Yosemite');
// response_x.return_x = 3.0;
// end
response.put('response_x', response_x1);
}
}
Test Class :
@isTest
public class ParkStubTest {
@isTest static void testCallout1() {
// This causes a fake response to be generated
Test.setMock(WebServiceMock.class, new ParkstubMock());
// Call the method that invokes a callout
string a = 'United States';
// Double y = 2.0;
list<string> result = Parkstub.parkstub1(a);
// Verify that a fake result is returned
//System.assertEquals(3.0, result);
}
}
While running the test class its giving me the error of attempt to dereference Null object for Mockclass.How should i create the instance for the list of string?
Please help me.
Thanks,
Bhaskar
i am getting null object error while trying to test the Mock of a webservice callout.
following is my WSDL2Apex class generated :
//Generated by wsdl2apex
public class parksServices {
public class byCountryResponse {
public String[] return_x;
private String[] return_x_type_info = new String[]{'return','http://parks.services/',null,'0','-1','false'};
private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};
private String[] field_order_type_info = new String[]{'return_x'};
}
public class byCountry {
public String arg0;
private String[] arg0_type_info = new String[]{'arg0','http://parks.services/',null,'0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};
private String[] field_order_type_info = new String[]{'arg0'};
}
public class ParksImplPort {
public String endpoint_x = 'https://th-apex-soap-service.herokuapp.com/service/parks';
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
private String[] ns_map_type_info = new String[]{'http://parks.services/', 'parksServices'};
public String[] byCountry(String arg0) {
parksServices.byCountry request_x = new parksServices.byCountry();
request_x.arg0 = arg0;
parksServices.byCountryResponse response_x;
Map<String, parksServices.byCountryResponse> response_map_x = new Map<String, parksServices.byCountryResponse>();
response_map_x.put('response_x', response_x);
WebServiceCallout.invoke(
this,
request_x,
response_map_x,
new String[]{endpoint_x,
'',
'http://parks.services/',
'byCountry',
'http://parks.services/',
'byCountryResponse',
'parksServices.byCountryResponse'}
);
response_x = response_map_x.get('response_x');
return response_x.return_x;
}
}
}
My Main Callout class :
public class Parkstub {
public static list<string> parkstub1( string a)
{
parksServices.ParksImplPort parklist = new parksServices.ParksImplPort();
return parklist.byCountry(a);
}
}
Mock Class
@isTest
global class ParkstubMock implements WebServiceMock {
global void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType) {
// start - specify the response you want to send
parksServices.byCountryResponse response_x1 = new parksServices.byCountryResponse();
response_x1.return_x.add('Yellowstone');
response_x1.return_x.add('Mackinac National Park');
response_x1.return_x.add('Yosemite');
// response_x.return_x = 3.0;
// end
response.put('response_x', response_x1);
}
}
Test Class :
@isTest
public class ParkStubTest {
@isTest static void testCallout1() {
// This causes a fake response to be generated
Test.setMock(WebServiceMock.class, new ParkstubMock());
// Call the method that invokes a callout
string a = 'United States';
// Double y = 2.0;
list<string> result = Parkstub.parkstub1(a);
// Verify that a fake result is returned
//System.assertEquals(3.0, result);
}
}
While running the test class its giving me the error of attempt to dereference Null object for Mockclass.How should i create the instance for the list of string?
Please help me.
Thanks,
Bhaskar
- BHASKAR GANGULY
- January 07, 2018
- Like
- 0
List values not showing in visualforce page
Hi,
I am calling a webservice through HTTP callout and trying to parsing the data and showing that in Visualforce page.
when i am debuging the list is returning value however when i am trying to show it through VF nothing is comming.Please help.
My VisualForce page :
<apex:page controller="FirstHTTP" sidebar="false">
<apex:Form >
<apex:pageBlock title="Contact Details">
<apex:PageBlockTable value="{!spp}" var="b">
<apex:column value="{!b.sconlist}" headervalue="Id"/>
<apex:column value="{!b.snamelist}" headervalue="Name"/>
</apex:PageBlockTable>
</apex:pageBlock>
</apex:Form>
</apex:page>
Controller Class :
public class FirstHTTP {
// Public Wrapper1 swrapper1;
Public FirstHTTP()
{
HTTPRequest s = New HTTPRequest();
S.setEndpoint('https://api.androidhive.info/contacts/');
s.setMethod('GET');
HTTP H1 = new HTTP();
HTTPResponse Resp =H1.send(s);
string sresponse =Resp.getBody();
// System.debug(sresponse);
// swrapper1 = new list<wrapper1>();
list<String> sid = new list<String>();
JSONParser parser = JSON.createParser(sresponse);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'id')) {
// Get the value.
parser.nextToken();
sid.add(parser.getText());
// Compute the grand total price for all invoices.
// system.debug(sid);
}
}
list<String> sname = new list<String>();
JSONParser parser1 = JSON.createParser(sresponse);
while (parser1.nextToken() != null) {
if ((parser1.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser1.getText() == 'name')) {
// Get the value.
parser1.nextToken();
sname.add(parser1.getText());
// Compute the grand total price for all invoices.
// system.debug(sid);
}
}
list<wrapper1> spp = new list<wrapper1>();
// system.debug(Sid.size());
for(integer i=0;i<Sid.size();i++)
{
swrapper1 = new Wrapper1();
swrapper1.sconlist = sid[i];
swrapper1.snamelist = sname[i];
spp.add(swrapper1);
// system.debug(slist);
}
// system.debug(slist);
}
public list<Wrapper1> spp{set;get;}
public Wrapper1 swrapper1{set;get;}
public class Wrapper1{
public string sconlist{set;get;}
public string snamelist{set;get;}
}
}
I am calling a webservice through HTTP callout and trying to parsing the data and showing that in Visualforce page.
when i am debuging the list is returning value however when i am trying to show it through VF nothing is comming.Please help.
My VisualForce page :
<apex:page controller="FirstHTTP" sidebar="false">
<apex:Form >
<apex:pageBlock title="Contact Details">
<apex:PageBlockTable value="{!spp}" var="b">
<apex:column value="{!b.sconlist}" headervalue="Id"/>
<apex:column value="{!b.snamelist}" headervalue="Name"/>
</apex:PageBlockTable>
</apex:pageBlock>
</apex:Form>
</apex:page>
Controller Class :
public class FirstHTTP {
// Public Wrapper1 swrapper1;
Public FirstHTTP()
{
HTTPRequest s = New HTTPRequest();
S.setEndpoint('https://api.androidhive.info/contacts/');
s.setMethod('GET');
HTTP H1 = new HTTP();
HTTPResponse Resp =H1.send(s);
string sresponse =Resp.getBody();
// System.debug(sresponse);
// swrapper1 = new list<wrapper1>();
list<String> sid = new list<String>();
JSONParser parser = JSON.createParser(sresponse);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'id')) {
// Get the value.
parser.nextToken();
sid.add(parser.getText());
// Compute the grand total price for all invoices.
// system.debug(sid);
}
}
list<String> sname = new list<String>();
JSONParser parser1 = JSON.createParser(sresponse);
while (parser1.nextToken() != null) {
if ((parser1.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser1.getText() == 'name')) {
// Get the value.
parser1.nextToken();
sname.add(parser1.getText());
// Compute the grand total price for all invoices.
// system.debug(sid);
}
}
list<wrapper1> spp = new list<wrapper1>();
// system.debug(Sid.size());
for(integer i=0;i<Sid.size();i++)
{
swrapper1 = new Wrapper1();
swrapper1.sconlist = sid[i];
swrapper1.snamelist = sname[i];
spp.add(swrapper1);
// system.debug(slist);
}
// system.debug(slist);
}
public list<Wrapper1> spp{set;get;}
public Wrapper1 swrapper1{set;get;}
public class Wrapper1{
public string sconlist{set;get;}
public string snamelist{set;get;}
}
}
- BHASKAR GANGULY
- December 20, 2017
- Like
- 0
Apex PageReference clarification
HI,
I am new to Apex Programing.
I am trying to create a simple program using Visualforce where i am inserting Account data.I want to nevigate to the newly created Account Record by click on Save Button.But its not working.
Can some bosy help me here.
My VisualForce code :
<apex:page controller="TDname" sidebar="false">
<apex:form >
<apex:outputLabel >Account Name :</apex:outputLabel>
<apex:inputText value="{!Accname}"/>
<apex:commandButton value="Save" action="{!AccSave}"/>
</apex:form>
</apex:page>
My Apex Class :
public class TDname {
public string Accname{Set;Get;}
public void AccSave()
{
Account a = new Account();
a.name = Accname;
Insert a;
}
Public PageReference save()
{
PageReference acctPage = new ApexPages.StandardController(account).view();
acctPage.setRedirect(true);
return acctPage;
}
}
I am new to Apex Programing.
I am trying to create a simple program using Visualforce where i am inserting Account data.I want to nevigate to the newly created Account Record by click on Save Button.But its not working.
Can some bosy help me here.
My VisualForce code :
<apex:page controller="TDname" sidebar="false">
<apex:form >
<apex:outputLabel >Account Name :</apex:outputLabel>
<apex:inputText value="{!Accname}"/>
<apex:commandButton value="Save" action="{!AccSave}"/>
</apex:form>
</apex:page>
My Apex Class :
public class TDname {
public string Accname{Set;Get;}
public void AccSave()
{
Account a = new Account();
a.name = Accname;
Insert a;
}
Public PageReference save()
{
PageReference acctPage = new ApexPages.StandardController(account).view();
acctPage.setRedirect(true);
return acctPage;
}
}
- BHASKAR GANGULY
- August 29, 2017
- Like
- 0
Apex Callout
HI Everyone,
Can somebody help me with an E2E Apex callout example along with test class to test that. I am looking for exact steps and Smaple code.
Thanks, Bhaskar
Can somebody help me with an E2E Apex callout example along with test class to test that. I am looking for exact steps and Smaple code.
Thanks, Bhaskar
- BHASKAR GANGULY
- August 28, 2017
- Like
- 0
sfdx command not working after npm install --global sfdx-cli
Hi All,
i have node.js installed in my pcversion is v.8.12,0.
i am trying to install salesforce cli by using npm install --global sfdx-cli command.
the install seems to be successful as its extracting all the metadata.However after installation while running the SFDX command its not working.Also i was not able to find any folder created as a result of cli installation.
Can anybody help me here.
Thanks,
Bhaskar
i have node.js installed in my pcversion is v.8.12,0.
i am trying to install salesforce cli by using npm install --global sfdx-cli command.
the install seems to be successful as its extracting all the metadata.However after installation while running the SFDX command its not working.Also i was not able to find any folder created as a result of cli installation.
Can anybody help me here.
Thanks,
Bhaskar
- BHASKAR GANGULY
- April 11, 2019
- Like
- 0
jason.deserialize is returning null
Hi All,
i am trying to parsing the below jason into my object.but while using the deserialize method its comming as Null.
not sure what i am missinh here.
Jason response :
{"invoiceList":[{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],"invoiceNumber":1},{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}]}
Wrapper class for data structure :
public class WrapperListinvoice {
public List<invoicelist> invoicepp;
public class invoicelist{
public double totalprice;
public DateTime Statementdate;
public list<Lineitems> sline;
public integer invoicenum;
}
public class Lineitems{
public double unitprice;
public double quantity;
public string productname;
}
}
calling class :
HttpRequest res= new HttpRequest();
res.setEndpoint('https://docsample.herokuapp.com/jsonSample');
res.setMethod('GET');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Accept','application/json');
Http hes= new Http();
httpresponse repp=hes.send(res);
string s=repp.getBody();
integer status =repp.getStatusCode();
//list<responseBean> assp= new list<responseBean>();
WrapperListinvoice responseBean=(WrapperListinvoice) JSON.deserialize(s,WrapperListinvoice.class);
system.debug(responseBean);
Can somebody please help me to understand what i am missing here.
Thanks,
Bhaskar
i am trying to parsing the below jason into my object.but while using the deserialize method its comming as Null.
not sure what i am missinh here.
Jason response :
{"invoiceList":[{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],"invoiceNumber":1},{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}]}
Wrapper class for data structure :
public class WrapperListinvoice {
public List<invoicelist> invoicepp;
public class invoicelist{
public double totalprice;
public DateTime Statementdate;
public list<Lineitems> sline;
public integer invoicenum;
}
public class Lineitems{
public double unitprice;
public double quantity;
public string productname;
}
}
calling class :
HttpRequest res= new HttpRequest();
res.setEndpoint('https://docsample.herokuapp.com/jsonSample');
res.setMethod('GET');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Accept','application/json');
Http hes= new Http();
httpresponse repp=hes.send(res);
string s=repp.getBody();
integer status =repp.getStatusCode();
//list<responseBean> assp= new list<responseBean>();
WrapperListinvoice responseBean=(WrapperListinvoice) JSON.deserialize(s,WrapperListinvoice.class);
system.debug(responseBean);
Can somebody please help me to understand what i am missing here.
Thanks,
Bhaskar
- BHASKAR GANGULY
- January 18, 2019
- Like
- 0
Apex Advanced superbadge Challange 8 :Challenge Not yet complete... here's what's wrong: Ensure that product2Controller is still working as specified in the earlier challenge.
Hi All,
i am gettingbelow error while trying to verify this.
Challenge Not yet complete... here's what's wrong:
Ensure that product2Controller is still working as specified in the earlier challenge.
Someone please help me to get it through.i am stuck on this for last couple of days.
Below are my classes :
Constants :
public class Constants {
public static final Integer DEFAULT_ROWS = 5;
public static final String SELECT_ONE = Label.Select_One;
public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low;
public static final List<Schema.PicklistEntry> PRODUCT_FAMILY = Product2.Family.getDescribe().getPicklistValues();
public static final String DRAFT_ORDER_STATUS = 'Draft';
public static final String ACTIVATED_ORDER_STATUS = 'Activated';
public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements';
public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.';
public static final Id STANDARD_PRICEBOOK_ID = '01s6A0000031LaYQAU'; //Test.isRunningTest() ? Test.getStandardPricebookId() : [SELECT Id FROM PriceBook2 WHERE isStandard = true LIMIT 1].Id;
}
AnnouncementQueueable
/**
* @name AnnouncementQueueable
* @description This class posts Chatter Announcements
**/
public class AnnouncementQueueable implements system.Queueable{
public List<ConnectApi.AnnouncementInput> toPost;
public AnnouncementQueueable(List<ConnectApi.AnnouncementInput> toPost){
this.toPost = toPost;
}
public void execute(QueueableContext context){
PostAnnouncements(toPost);
}
/**
* @name postAnnouncements
* @description This method is provided for you to facilitate the Super Badge
**/
public static void PostAnnouncements(List<ConnectApi.AnnouncementInput> announcements){
while ( announcements.size() > 0 ){
if ( Limits.getDMLStatements() < Limits.getLimitDMLStatements() && !test.isRunningTest()){
ConnectApi.AnnouncementInput a = announcements.remove(0);
ConnectApi.Announcements.postAnnouncement('internal', a);
} else {
AnnouncementQueueable announcementQueuable = new AnnouncementQueueable(announcements);
break;
}
}
if (announcements.size() > 0 && !test.isRunningTest()){
AnnouncementQueueable q = new AnnouncementQueueable(announcements);
System.enqueueJob(q);
//ToDo: Enqueue the above instance of announcementQueueable
}
}
}
ChartHelper
public without sharing class ChartHelper {
@AuraEnabled// Make sure annotation should be applied for this method
public static List<chartData> GetInventory(){
List<chartData> cht = new List<chartData>();
for(AggregateResult ar : [SELECT Family family, Sum(Quantity_Remaining__c) total
FROM Product2
WHERE Quantity_Remaining__c > 0 GROUP BY Family]){
cht.add(new chartData((String)ar.get('family'), Integer.valueOf(ar.get('total'))));
}
return cht;
}
public class ChartData {
public String name {get;set;}
public Decimal val {get;set;}
public ChartData(String name, Decimal val){
this.name = name;
this.val = val;
}
}
}
OrderExtension:
/**
* @name OrderExtension
* @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {
public Order orderRecord {get;set;}
public List<OrderItem> orderItemList {get;set;}
public String selectedFamily {get;set;}
public List<chartHelper.chartData> pieData {get;set;}
public Decimal total {get;set;}
public Map<Id,OrderItem> orderItemMap;
ApexPages.StandardSetController standardSetController;
public OrderExtension(ApexPages.StandardController standardController){
orderRecord = (Order)standardController.getRecord();
orderItemMap = new Map<id,OrderItem>();
if ( orderRecord.Id != null ){
orderRecord = queryOrderRecord(orderRecord.Id);
}
resetSsc();
total = 0;
for (OrderItem oi : orderRecord.OrderItems) {
orderItemMap.put(oi.Product2Id, oi);
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<ChartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
total += oi.UnitPrice * oi.Quantity;
}
}
PopulateOrderItems();
}
void resetSsc() {
String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
+ ' FROM PricebookEntry WHERE IsActive = TRUE';
if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
query += ' AND Product2.Family = \'' + selectedFamily + '\'';
}
query += ' ORDER BY Name';
standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
standardSetController.setPageSize(Constants.DEFAULT_ROWS);
}
//ToDo: Implement your own method to populate orderItemList
// that you will call after pagination and/or family selection
void PopulateOrderItems() {
orderItemList = new List<OrderItem>();
for (SObject obj : standardSetController.getRecords()) {
PricebookEntry pbe = (PricebookEntry)obj;
if (orderItemMap.containsKey(pbe.Product2Id)) {
orderItemList.add(orderItemMap.get(pbe.Product2Id));
} else {
orderItemList.add(new OrderItem(
PricebookEntryId=pbe.Id,
Product2Id=pbe.Product2Id,
UnitPrice=pbe.UnitPrice,
Quantity=0,
Product2=pbe.Product2
));
}
}
}
/**
* @name OnFieldChange
* @description
**/
public void OnFieldChange(){
//ToDo: Implement logic to store the values changed on the page
for (OrderItem oi : orderItemList) {
orderItemMap.put(oi.Product2Id, oi);
}
// and populate pieData
pieData = null;
total = 0;
for (OrderItem oi : orderItemMap.values()) {
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<chartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
// and populate total
total += oi.UnitPrice * oi.Quantity;
}
}
}
/**
* @name SelectFamily
* @description
**/
public void SelectFamily(){
//ToDo: Implement logic to filter based on the selected product family
resetSsc();
PopulateOrderItems();
}
/**
* @name Save
* @description
**/
public void Save(){
//ToDo: Implement logic to save the Order and populated OrderItems
System.Savepoint sp = Database.setSavepoint();
try {
if (null == orderRecord.Pricebook2Id) {
orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
}
upsert orderRecord;
List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
List<OrderItem> orderItemsToDelete = new List<OrderItem>();
for (OrderItem oi : orderItemList) {
if (oi.Quantity > 0) {
if (null == oi.OrderId) {
oi.OrderId = orderRecord.Id;
}
orderItemsToUpsert.add(oi);
} else if (oi.Id != null) {
orderItemsToDelete.add(oi);
}
}
upsert orderItemsToUpsert;
delete orderItemsToDelete;
} catch (Exception e) {
Database.rollback(sp);
apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
}
}
/**
* @name First
* @description
**/
public void First(){
standardSetController.first();
PopulateOrderItems();
}
/**
* @name Next
* @description
**/
public void Next(){
standardSetController.next();
PopulateOrderItems();
}
/**
* @name Previous
* @description
**/
public void Previous(){
standardSetController.previous();
PopulateOrderItems();
}
/**
* @name Last
* @description
**/
public void Last(){
standardSetController.last();
PopulateOrderItems();
}
/**
* @name GetHasPrevious
* @description
**/
public Boolean GetHasPrevious(){
return standardSetController.getHasPrevious();
}
/**
* @name GetHasNext
* @description
**/
public Boolean GetHasNext(){
return standardSetController.getHasNext();
}
/**
* @name GetTotalPages
* @description
**/
public Integer GetTotalPages(){
return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
}
/**
* @name GetPageNumber
* @description
**/
public Integer GetPageNumber(){
return standardSetController.getPageNumber();
}
/**
* @name GetFamilyOptions
* @description
**/
public List<SelectOption> GetFamilyOptions() {
List<SelectOption> options = new List<SelectOption>{
new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
};
for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
options.add(new SelectOption(ple.getValue(), ple.getLabel()));
}
return options;
}
/**
* @name QueryOrderRecord
* @description
**/
public static Order QueryOrderRecord(Id orderId){
return [
SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
(
SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
FROM OrderItems
)
FROM Order
WHERE Id = :orderId
];
}
}
OrderHelper :
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for (Integer i = 0; i < newList.size(); i++) {
if(newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS) {
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity FROM OrderItem WHERE OrderId In :activatedOrderIds];
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
for(OrderItem oi : items) {
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN:productIds]);
AggregateResult[] aggregatedResults = [SELECT Product2Id, SUM(Quantity) aggregatedQuantity FROM OrderItem WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : aggregatedResults) {
productMap.get((String)ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('aggregatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap != null && productMap.size() > 0) {
update productMap.values();
}
}
}
OrderTests:
@isTest(SeeAllData=true)
public class OrderTests {
public static Map<String, List<Object>> testData;
@isTest static void OrderUpdate_UnitTest (){
// TestDataFactory.InsertTestData(5);
// List<Account> accts=new List<Account>();
Account a=new Account();
a.Name='Account';
a.Rating='Hot';
insert a;
List<Order> orders=new List<Order>();
// Integer k=0;
//Contract c=new Contract(AccountId=accts.get(k).Id,Status='Draft',StartDate =date.today(),ContractTerm =12);
Order o=new Order();
o.AccountId=a.Id;
o.EffectiveDate=date.today();
//o.Pricebook2Id='01s6A0000031LaYQAU';
//o.ContractId=c.Id ;
o.Status='Draft';
// k++;
insert o;
List<Product2> pros=new List<Product2>();
Integer picklistSize=Constants.PRODUCT_FAMILY.size();
Integer j=0;
for(Integer s=0;s<5;s++){
Product2 p=new Product2();
p.Name='Side';
p.IsActive=true;
p.Initial_Inventory__c =10;
p.Family=Constants.PRODUCT_FAMILY[j].getValue();
p.Quantity_Ordered__c=10;
if(j==picklistSize-1){
j=0;
}else{
j++;
}
pros.add(p);
}
insert pros;
Order rec = [select id, Status from Order limit 1];
Product2 prod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 where name ='Side' limit 1];
system.debug('product2Controller => '+prod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c => '+prod.Quantity_Remaining__c);
rec.status = constants.ACTIVATED_ORDER_STATUS;
Update rec;
Product2 updatedprod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 Where name ='Side' limit 1];
system.debug('itial_Inventory__c =>'+updatedprod.Initial_Inventory__c);
system.debug('Quantity_Ordered__c =>'+updatedprod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c =>'+updatedprod.Quantity_Remaining__c);
TestDataFactory.VerifyQuantityOrdered(prod,updatedprod,constants.DEFAULT_ROWS);
//upsert updatedprod;
}
@isTest(SeeAllData=true) static void OrderExtension_UnitTest(){
Order rec = [select id, Status from Order limit 1];
PageReference pageRef = Page.OrderEdit;
Test.setCurrentPage(pageRef);
pageRef.getParameters().put('id',rec.id);
ApexPages.StandardController sc = new ApexPages.standardController(rec);
OrderExtension cc = new OrderExtension(sc);
cc.SelectFamily();
cc.OnFieldChange();
cc.Save();
cc.First();
cc.Next();
cc.Previous();
cc.Last();
cc.GetHasPrevious();
cc.GetHasNext();
cc.GetTotalPages();
cc.GetFamilyOptions();
ChartHelper.GetInventory();
//Constants.getStdPriceBook();
}
//@testSetup static void SetupTestData (){
//}
}
Thanks,
BHaskar
i am gettingbelow error while trying to verify this.
Challenge Not yet complete... here's what's wrong:
Ensure that product2Controller is still working as specified in the earlier challenge.
Someone please help me to get it through.i am stuck on this for last couple of days.
Below are my classes :
Constants :
public class Constants {
public static final Integer DEFAULT_ROWS = 5;
public static final String SELECT_ONE = Label.Select_One;
public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low;
public static final List<Schema.PicklistEntry> PRODUCT_FAMILY = Product2.Family.getDescribe().getPicklistValues();
public static final String DRAFT_ORDER_STATUS = 'Draft';
public static final String ACTIVATED_ORDER_STATUS = 'Activated';
public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements';
public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.';
public static final Id STANDARD_PRICEBOOK_ID = '01s6A0000031LaYQAU'; //Test.isRunningTest() ? Test.getStandardPricebookId() : [SELECT Id FROM PriceBook2 WHERE isStandard = true LIMIT 1].Id;
}
AnnouncementQueueable
/**
* @name AnnouncementQueueable
* @description This class posts Chatter Announcements
**/
public class AnnouncementQueueable implements system.Queueable{
public List<ConnectApi.AnnouncementInput> toPost;
public AnnouncementQueueable(List<ConnectApi.AnnouncementInput> toPost){
this.toPost = toPost;
}
public void execute(QueueableContext context){
PostAnnouncements(toPost);
}
/**
* @name postAnnouncements
* @description This method is provided for you to facilitate the Super Badge
**/
public static void PostAnnouncements(List<ConnectApi.AnnouncementInput> announcements){
while ( announcements.size() > 0 ){
if ( Limits.getDMLStatements() < Limits.getLimitDMLStatements() && !test.isRunningTest()){
ConnectApi.AnnouncementInput a = announcements.remove(0);
ConnectApi.Announcements.postAnnouncement('internal', a);
} else {
AnnouncementQueueable announcementQueuable = new AnnouncementQueueable(announcements);
break;
}
}
if (announcements.size() > 0 && !test.isRunningTest()){
AnnouncementQueueable q = new AnnouncementQueueable(announcements);
System.enqueueJob(q);
//ToDo: Enqueue the above instance of announcementQueueable
}
}
}
ChartHelper
public without sharing class ChartHelper {
@AuraEnabled// Make sure annotation should be applied for this method
public static List<chartData> GetInventory(){
List<chartData> cht = new List<chartData>();
for(AggregateResult ar : [SELECT Family family, Sum(Quantity_Remaining__c) total
FROM Product2
WHERE Quantity_Remaining__c > 0 GROUP BY Family]){
cht.add(new chartData((String)ar.get('family'), Integer.valueOf(ar.get('total'))));
}
return cht;
}
public class ChartData {
public String name {get;set;}
public Decimal val {get;set;}
public ChartData(String name, Decimal val){
this.name = name;
this.val = val;
}
}
}
OrderExtension:
/**
* @name OrderExtension
* @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {
public Order orderRecord {get;set;}
public List<OrderItem> orderItemList {get;set;}
public String selectedFamily {get;set;}
public List<chartHelper.chartData> pieData {get;set;}
public Decimal total {get;set;}
public Map<Id,OrderItem> orderItemMap;
ApexPages.StandardSetController standardSetController;
public OrderExtension(ApexPages.StandardController standardController){
orderRecord = (Order)standardController.getRecord();
orderItemMap = new Map<id,OrderItem>();
if ( orderRecord.Id != null ){
orderRecord = queryOrderRecord(orderRecord.Id);
}
resetSsc();
total = 0;
for (OrderItem oi : orderRecord.OrderItems) {
orderItemMap.put(oi.Product2Id, oi);
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<ChartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
total += oi.UnitPrice * oi.Quantity;
}
}
PopulateOrderItems();
}
void resetSsc() {
String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
+ ' FROM PricebookEntry WHERE IsActive = TRUE';
if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
query += ' AND Product2.Family = \'' + selectedFamily + '\'';
}
query += ' ORDER BY Name';
standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
standardSetController.setPageSize(Constants.DEFAULT_ROWS);
}
//ToDo: Implement your own method to populate orderItemList
// that you will call after pagination and/or family selection
void PopulateOrderItems() {
orderItemList = new List<OrderItem>();
for (SObject obj : standardSetController.getRecords()) {
PricebookEntry pbe = (PricebookEntry)obj;
if (orderItemMap.containsKey(pbe.Product2Id)) {
orderItemList.add(orderItemMap.get(pbe.Product2Id));
} else {
orderItemList.add(new OrderItem(
PricebookEntryId=pbe.Id,
Product2Id=pbe.Product2Id,
UnitPrice=pbe.UnitPrice,
Quantity=0,
Product2=pbe.Product2
));
}
}
}
/**
* @name OnFieldChange
* @description
**/
public void OnFieldChange(){
//ToDo: Implement logic to store the values changed on the page
for (OrderItem oi : orderItemList) {
orderItemMap.put(oi.Product2Id, oi);
}
// and populate pieData
pieData = null;
total = 0;
for (OrderItem oi : orderItemMap.values()) {
if (oi.Quantity > 0) {
if (null == pieData) {
pieData = new List<chartHelper.ChartData>();
}
pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
// and populate total
total += oi.UnitPrice * oi.Quantity;
}
}
}
/**
* @name SelectFamily
* @description
**/
public void SelectFamily(){
//ToDo: Implement logic to filter based on the selected product family
resetSsc();
PopulateOrderItems();
}
/**
* @name Save
* @description
**/
public void Save(){
//ToDo: Implement logic to save the Order and populated OrderItems
System.Savepoint sp = Database.setSavepoint();
try {
if (null == orderRecord.Pricebook2Id) {
orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
}
upsert orderRecord;
List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
List<OrderItem> orderItemsToDelete = new List<OrderItem>();
for (OrderItem oi : orderItemList) {
if (oi.Quantity > 0) {
if (null == oi.OrderId) {
oi.OrderId = orderRecord.Id;
}
orderItemsToUpsert.add(oi);
} else if (oi.Id != null) {
orderItemsToDelete.add(oi);
}
}
upsert orderItemsToUpsert;
delete orderItemsToDelete;
} catch (Exception e) {
Database.rollback(sp);
apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
}
}
/**
* @name First
* @description
**/
public void First(){
standardSetController.first();
PopulateOrderItems();
}
/**
* @name Next
* @description
**/
public void Next(){
standardSetController.next();
PopulateOrderItems();
}
/**
* @name Previous
* @description
**/
public void Previous(){
standardSetController.previous();
PopulateOrderItems();
}
/**
* @name Last
* @description
**/
public void Last(){
standardSetController.last();
PopulateOrderItems();
}
/**
* @name GetHasPrevious
* @description
**/
public Boolean GetHasPrevious(){
return standardSetController.getHasPrevious();
}
/**
* @name GetHasNext
* @description
**/
public Boolean GetHasNext(){
return standardSetController.getHasNext();
}
/**
* @name GetTotalPages
* @description
**/
public Integer GetTotalPages(){
return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
}
/**
* @name GetPageNumber
* @description
**/
public Integer GetPageNumber(){
return standardSetController.getPageNumber();
}
/**
* @name GetFamilyOptions
* @description
**/
public List<SelectOption> GetFamilyOptions() {
List<SelectOption> options = new List<SelectOption>{
new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
};
for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
options.add(new SelectOption(ple.getValue(), ple.getLabel()));
}
return options;
}
/**
* @name QueryOrderRecord
* @description
**/
public static Order QueryOrderRecord(Id orderId){
return [
SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
(
SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
FROM OrderItems
)
FROM Order
WHERE Id = :orderId
];
}
}
OrderHelper :
public class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> activatedOrderIds = new Set<Id>();
//Create list of OrderIds
for (Integer i = 0; i < newList.size(); i++) {
if(newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS) {
activatedOrderIds.add(newList[i].Id);
}
}
RollUpOrderItems(activatedOrderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
Map<Id, Product2> productMap = new Map<Id, Product2>();
Set<Id> productIds = new Set<Id>();
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
List<OrderItem> items = [SELECT Id, Product2Id, Quantity FROM OrderItem WHERE OrderId In :activatedOrderIds];
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
for(OrderItem oi : items) {
productIds.add(oi.Product2Id);
}
productMap = new Map<Id, Product2>([SELECT Id, Quantity_Ordered__c FROM Product2 WHERE Id IN:productIds]);
AggregateResult[] aggregatedResults = [SELECT Product2Id, SUM(Quantity) aggregatedQuantity FROM OrderItem WHERE Product2Id In :productMap.keySet() GROUP BY Product2Id];
for (AggregateResult ar : aggregatedResults) {
productMap.get((String)ar.get('Product2Id')).Quantity_Ordered__c = Integer.valueOf(ar.get('aggregatedQuantity'));
}
//ToDo: Perform an update on the records in the productMap
if(productMap != null && productMap.size() > 0) {
update productMap.values();
}
}
}
OrderTests:
@isTest(SeeAllData=true)
public class OrderTests {
public static Map<String, List<Object>> testData;
@isTest static void OrderUpdate_UnitTest (){
// TestDataFactory.InsertTestData(5);
// List<Account> accts=new List<Account>();
Account a=new Account();
a.Name='Account';
a.Rating='Hot';
insert a;
List<Order> orders=new List<Order>();
// Integer k=0;
//Contract c=new Contract(AccountId=accts.get(k).Id,Status='Draft',StartDate =date.today(),ContractTerm =12);
Order o=new Order();
o.AccountId=a.Id;
o.EffectiveDate=date.today();
//o.Pricebook2Id='01s6A0000031LaYQAU';
//o.ContractId=c.Id ;
o.Status='Draft';
// k++;
insert o;
List<Product2> pros=new List<Product2>();
Integer picklistSize=Constants.PRODUCT_FAMILY.size();
Integer j=0;
for(Integer s=0;s<5;s++){
Product2 p=new Product2();
p.Name='Side';
p.IsActive=true;
p.Initial_Inventory__c =10;
p.Family=Constants.PRODUCT_FAMILY[j].getValue();
p.Quantity_Ordered__c=10;
if(j==picklistSize-1){
j=0;
}else{
j++;
}
pros.add(p);
}
insert pros;
Order rec = [select id, Status from Order limit 1];
Product2 prod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 where name ='Side' limit 1];
system.debug('product2Controller => '+prod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c => '+prod.Quantity_Remaining__c);
rec.status = constants.ACTIVATED_ORDER_STATUS;
Update rec;
Product2 updatedprod = [SELECT Initial_Inventory__c,Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 Where name ='Side' limit 1];
system.debug('itial_Inventory__c =>'+updatedprod.Initial_Inventory__c);
system.debug('Quantity_Ordered__c =>'+updatedprod.Quantity_Ordered__c);
system.debug('Quantity_Remaining__c =>'+updatedprod.Quantity_Remaining__c);
TestDataFactory.VerifyQuantityOrdered(prod,updatedprod,constants.DEFAULT_ROWS);
//upsert updatedprod;
}
@isTest(SeeAllData=true) static void OrderExtension_UnitTest(){
Order rec = [select id, Status from Order limit 1];
PageReference pageRef = Page.OrderEdit;
Test.setCurrentPage(pageRef);
pageRef.getParameters().put('id',rec.id);
ApexPages.StandardController sc = new ApexPages.standardController(rec);
OrderExtension cc = new OrderExtension(sc);
cc.SelectFamily();
cc.OnFieldChange();
cc.Save();
cc.First();
cc.Next();
cc.Previous();
cc.Last();
cc.GetHasPrevious();
cc.GetHasNext();
cc.GetTotalPages();
cc.GetFamilyOptions();
ChartHelper.GetInventory();
//Constants.getStdPriceBook();
}
//@testSetup static void SetupTestData (){
//}
}
Thanks,
BHaskar
- BHASKAR GANGULY
- October 25, 2018
- Like
- 0
Superbadge:Advance Apex Specialist step 8 Error
Hello,
While solving challenge 8 I am getting an error:-
Challenge Not yet complete... here's what's wrong:
Ensure that orderTrigger and orderHelper are still working as specified in the earlier challenge.
Please let me know what I am doing wrong else paste the correct code here.
My code goes as follows-:
CLASS- OrderTests
@isTest
public class OrderTests {
@testSetup
public static void SetupTestData() {
TestDataFactory.InsertTestData(3);
}
@isTest
public static void OrderUpdate_UnitTest (){
Test.startTest();
List<Product2> originalProduct=[Select Quantity_Ordered__c from Product2 where Name like 'ProductConstruction%'];
List<Order> ord=new List<Order>();
List<Order> testOrders=[Select status from Order where status='Draft'];
System.debug('originalPro '+originalProduct);
System.debug('Ordertest orders '+testOrders);
for(Order o:testOrders){
o.Status=Constants.ACTIVATED_ORDER_STATUS;
ord.add(o);
}
System.debug('OrderTests 21 '+ord);
update ord;
List<Product2> updatedProduct=OrderHelper.pr;
//System.debug(updatedProduct.get(0)+' '+originalProduct.get(0));
TestDataFactory.VerifyQuantityOrdered(originalProduct.get(0), updatedProduct.get(0), (Integer)OrderHelper.temp.get(0));
Test.stopTest();
}
@isTest
public static void OrderExtension_UnitTest (){
Test.startTest();
Account ac=new Account();
ac.Name='Test1';
insert ac;
Contract ct=new Contract();
ct.AccountId=ac.Id;
ct.StartDate =date.today();
ct.Status='Draft';
ct.ContractTerm=4;
insert ct;
Order obj=new Order();
obj.AccountId=ac.Id;
obj.EffectiveDate=date.today();
obj.ContractId=ct.Id;
obj.Status='Draft';
obj.Name='OrderName';
insert obj;
ApexPages.StandardController sc = new ApexPages.StandardController(obj);
OrderExtension cc=new OrderExtension(sc);
cc.SelectFamily();
cc.OnFieldChange();
cc.Save();
cc.First();
cc.Next();
cc.Previous();
cc.Last();
cc.GetHasPrevious();
cc.GetHasNext();
cc.GetTotalPages();
cc.GetFamilyOptions();
Test.stopTest();
}
}
CLASS- prouct2Tests
@isTest (seeAllData=true)
private class Product2Tests {
/**
* @name product2Extension_UnitTest
* @description UnitTest for product2Extension
**/
static TestMethod void Product2Extension_UnitTest(){
Test.startTest();
PageReference pageRef = Page.Product2New;
Test.setCurrentPage(pageRef);
ApexPages.StandardController controller =new Apexpages.StandardController(new Product2());
Product2Extension ext = new Product2Extension(controller);
ext.addRows();
ext.save();
System.assertEquals(Product2Extension.productsToInsert.size(), Constants.DEFAULT_ROWS);
//if(addValue.equals('Add'))
//System.assertEquals(Product2Extension.productsToInsert.size(), 2*Constants.DEFAULT_ROWS);
Integer i=0;
for(Product2Extension.ProductWrapper pr: Product2Extension.productsToInsert){
if (String.isBlank(pr.productRecord.Name) || pr.productRecord.Name==null){
pr.productRecord.Name='Product'+i;
}
if(String.isBlank(pr.productRecord.Family) || pr.productRecord.Family==null ){
pr.productRecord.Family='Side';
}
if(pr.productRecord.IsActive==false){
pr.productRecord.IsActive=true;
}
if(pr.productRecord.Initial_Inventory__c==null){
pr.productRecord.Initial_Inventory__c=15;
}
i++;
}
PageReference p=ext.save();
List<Product2> queryResults=[Select Name,IsActive,Initial_Inventory__c from Product2 where Initial_Inventory__c=15 and IsActive= true and Family='Side'];
Test.stopTest();
System.assertEquals(queryResults.size(), 5);
System.debug(Product2Extension.productsToInsert.size());
}
static void Product2Trigger_UnitTest(){
Test.startTest();
Product2 p=new Product2();
p.Name='TestProduct';
p.Family='Side';
p.IsActive=true;
p.Quantity_Ordered__c =100;
p.Initial_Inventory__c =10;
insert p;
p.Quantity_Ordered__c=200;
update p;
Test.stopTest();
}
}
CLASS - OrderHelper
public without sharing class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static List<Product2> pr=new List<Product2>();
public static List<Decimal> temp;
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> orderIds = new Set<Id>();
for ( Integer i=0; i<newList.size(); i++ ){
if ( newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS ){
orderIds.add(newList[i].Id);
}
}
System.debug('New Order '+newList);
System.debug('Old Order '+oldList);
System.debug('OrderIDS '+orderIds);
OrderHelper.RollUpOrderItems(orderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
List<OrderItem> oi=[Select Id, Product2Id ,AvailableQuantity from OrderItem where OrderId IN:activatedOrderIds];
Map<Id,Product2> productMap=new Map<Id,Product2>();
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
for(OrderItem ord:oi){
Product2 p=[Select Id,Name, Quantity_Ordered__c , Quantity_Remaining__c from Product2 where Id=: ord.Product2Id ];
productMap.put(ord.Product2Id, p);
}
AggregateResult[] groupedResults =[Select Product2Id,SUM(Quantity) from OrderItem where Product2Id IN : productMap.keySet() group by Product2Id];
for(AggregateResult ag:groupedResults){
Product2 p= productmap.get((Id)ag.get('Product2Id'));
p.Quantity_Ordered__c =(Double)ag.get('expr0');
temp.add(p.Quantity_Ordered__c);
pr.add(p);
}
System.debug('orderHelper'+pr+' '+activatedOrderIds+' '+groupedResults);
update pr;
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
//ToDo: Loop through a query that aggregates the OrderItems related to the Products in the ProductMap keyset
//ToDo: Perform an update on the records in the productMap
}
}
Thanks in advance
Shubham Nandwana
While solving challenge 8 I am getting an error:-
Challenge Not yet complete... here's what's wrong:
Ensure that orderTrigger and orderHelper are still working as specified in the earlier challenge.
Please let me know what I am doing wrong else paste the correct code here.
My code goes as follows-:
CLASS- OrderTests
@isTest
public class OrderTests {
@testSetup
public static void SetupTestData() {
TestDataFactory.InsertTestData(3);
}
@isTest
public static void OrderUpdate_UnitTest (){
Test.startTest();
List<Product2> originalProduct=[Select Quantity_Ordered__c from Product2 where Name like 'ProductConstruction%'];
List<Order> ord=new List<Order>();
List<Order> testOrders=[Select status from Order where status='Draft'];
System.debug('originalPro '+originalProduct);
System.debug('Ordertest orders '+testOrders);
for(Order o:testOrders){
o.Status=Constants.ACTIVATED_ORDER_STATUS;
ord.add(o);
}
System.debug('OrderTests 21 '+ord);
update ord;
List<Product2> updatedProduct=OrderHelper.pr;
//System.debug(updatedProduct.get(0)+' '+originalProduct.get(0));
TestDataFactory.VerifyQuantityOrdered(originalProduct.get(0), updatedProduct.get(0), (Integer)OrderHelper.temp.get(0));
Test.stopTest();
}
@isTest
public static void OrderExtension_UnitTest (){
Test.startTest();
Account ac=new Account();
ac.Name='Test1';
insert ac;
Contract ct=new Contract();
ct.AccountId=ac.Id;
ct.StartDate =date.today();
ct.Status='Draft';
ct.ContractTerm=4;
insert ct;
Order obj=new Order();
obj.AccountId=ac.Id;
obj.EffectiveDate=date.today();
obj.ContractId=ct.Id;
obj.Status='Draft';
obj.Name='OrderName';
insert obj;
ApexPages.StandardController sc = new ApexPages.StandardController(obj);
OrderExtension cc=new OrderExtension(sc);
cc.SelectFamily();
cc.OnFieldChange();
cc.Save();
cc.First();
cc.Next();
cc.Previous();
cc.Last();
cc.GetHasPrevious();
cc.GetHasNext();
cc.GetTotalPages();
cc.GetFamilyOptions();
Test.stopTest();
}
}
CLASS- prouct2Tests
@isTest (seeAllData=true)
private class Product2Tests {
/**
* @name product2Extension_UnitTest
* @description UnitTest for product2Extension
**/
static TestMethod void Product2Extension_UnitTest(){
Test.startTest();
PageReference pageRef = Page.Product2New;
Test.setCurrentPage(pageRef);
ApexPages.StandardController controller =new Apexpages.StandardController(new Product2());
Product2Extension ext = new Product2Extension(controller);
ext.addRows();
ext.save();
System.assertEquals(Product2Extension.productsToInsert.size(), Constants.DEFAULT_ROWS);
//if(addValue.equals('Add'))
//System.assertEquals(Product2Extension.productsToInsert.size(), 2*Constants.DEFAULT_ROWS);
Integer i=0;
for(Product2Extension.ProductWrapper pr: Product2Extension.productsToInsert){
if (String.isBlank(pr.productRecord.Name) || pr.productRecord.Name==null){
pr.productRecord.Name='Product'+i;
}
if(String.isBlank(pr.productRecord.Family) || pr.productRecord.Family==null ){
pr.productRecord.Family='Side';
}
if(pr.productRecord.IsActive==false){
pr.productRecord.IsActive=true;
}
if(pr.productRecord.Initial_Inventory__c==null){
pr.productRecord.Initial_Inventory__c=15;
}
i++;
}
PageReference p=ext.save();
List<Product2> queryResults=[Select Name,IsActive,Initial_Inventory__c from Product2 where Initial_Inventory__c=15 and IsActive= true and Family='Side'];
Test.stopTest();
System.assertEquals(queryResults.size(), 5);
System.debug(Product2Extension.productsToInsert.size());
}
static void Product2Trigger_UnitTest(){
Test.startTest();
Product2 p=new Product2();
p.Name='TestProduct';
p.Family='Side';
p.IsActive=true;
p.Quantity_Ordered__c =100;
p.Initial_Inventory__c =10;
insert p;
p.Quantity_Ordered__c=200;
update p;
Test.stopTest();
}
}
CLASS - OrderHelper
public without sharing class OrderHelper {
/**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
public static List<Product2> pr=new List<Product2>();
public static List<Decimal> temp;
public static void AfterUpdate(List<Order> newList, List<Order> oldList){
Set<Id> orderIds = new Set<Id>();
for ( Integer i=0; i<newList.size(); i++ ){
if ( newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS ){
orderIds.add(newList[i].Id);
}
}
System.debug('New Order '+newList);
System.debug('Old Order '+oldList);
System.debug('OrderIDS '+orderIds);
OrderHelper.RollUpOrderItems(orderIds);
}
/**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
public static void RollUpOrderItems(Set<Id> activatedOrderIds){
List<OrderItem> oi=[Select Id, Product2Id ,AvailableQuantity from OrderItem where OrderId IN:activatedOrderIds];
Map<Id,Product2> productMap=new Map<Id,Product2>();
//ToDo: Declare a Map named "productMap" of Ids to Product2 records
//ToDo: Loop through a query of OrderItems related to the activatedOrderIds
for(OrderItem ord:oi){
Product2 p=[Select Id,Name, Quantity_Ordered__c , Quantity_Remaining__c from Product2 where Id=: ord.Product2Id ];
productMap.put(ord.Product2Id, p);
}
AggregateResult[] groupedResults =[Select Product2Id,SUM(Quantity) from OrderItem where Product2Id IN : productMap.keySet() group by Product2Id];
for(AggregateResult ag:groupedResults){
Product2 p= productmap.get((Id)ag.get('Product2Id'));
p.Quantity_Ordered__c =(Double)ag.get('expr0');
temp.add(p.Quantity_Ordered__c);
pr.add(p);
}
System.debug('orderHelper'+pr+' '+activatedOrderIds+' '+groupedResults);
update pr;
//ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
//ToDo: Loop through a query that aggregates the OrderItems related to the Products in the ProductMap keyset
//ToDo: Perform an update on the records in the productMap
}
}
Thanks in advance
Shubham Nandwana
- Shubham Nandwana
- December 29, 2017
- Like
- 0
Apex PageReference clarification
HI,
I am new to Apex Programing.
I am trying to create a simple program using Visualforce where i am inserting Account data.I want to nevigate to the newly created Account Record by click on Save Button.But its not working.
Can some bosy help me here.
My VisualForce code :
<apex:page controller="TDname" sidebar="false">
<apex:form >
<apex:outputLabel >Account Name :</apex:outputLabel>
<apex:inputText value="{!Accname}"/>
<apex:commandButton value="Save" action="{!AccSave}"/>
</apex:form>
</apex:page>
My Apex Class :
public class TDname {
public string Accname{Set;Get;}
public void AccSave()
{
Account a = new Account();
a.name = Accname;
Insert a;
}
Public PageReference save()
{
PageReference acctPage = new ApexPages.StandardController(account).view();
acctPage.setRedirect(true);
return acctPage;
}
}
I am new to Apex Programing.
I am trying to create a simple program using Visualforce where i am inserting Account data.I want to nevigate to the newly created Account Record by click on Save Button.But its not working.
Can some bosy help me here.
My VisualForce code :
<apex:page controller="TDname" sidebar="false">
<apex:form >
<apex:outputLabel >Account Name :</apex:outputLabel>
<apex:inputText value="{!Accname}"/>
<apex:commandButton value="Save" action="{!AccSave}"/>
</apex:form>
</apex:page>
My Apex Class :
public class TDname {
public string Accname{Set;Get;}
public void AccSave()
{
Account a = new Account();
a.name = Accname;
Insert a;
}
Public PageReference save()
{
PageReference acctPage = new ApexPages.StandardController(account).view();
acctPage.setRedirect(true);
return acctPage;
}
}
- BHASKAR GANGULY
- August 29, 2017
- Like
- 0