• Amit Chaudhary 8
  • ALL STAR
  • 41852 Points
  • Member since 2014
  • Salesforce CRM Consultant


  • Chatter
    Feed
  • 1223
    Best Answers
  • 1
    Likes Received
  • 32
    Likes Given
  • 3
    Questions
  • 5910
    Replies
I am getting the annoying "Attempt to de-reference a null obect" error when trying to deploy a VF page and Class/Test Class. I have 100% code coverage on my test class and it functions perfectly in sandbox. I cannot seem to figure out where/why I am getting the error. Below is the code for both the class and test class. I am getting an error at line 64, 96, and 127 in the class. 
public class ctrl_qliEstimatedSellFor {
    
    public list< QuoteLineItems__c > qli_List	{get;set;}
    public List < SystemsOrOptions__c > soo_List {get;set;}
    private final Quotes__c qte_sObj;
    decimal pem {get;set;}
    decimal pf {get;set;}
    decimal se {get;set;}
    decimal GMNC {get;set;}
    decimal CostTotal {get;set;}
    decimal TravelCost {get;set;}
    decimal TravelCostTest {get;set;}
    decimal CommissionPercentage {get;set;}
    decimal SellForWoCommission {get;set;}
    decimal CommissionAmount {get;set;}
    decimal EstimatedSellForTotal {get;set;}
    
    public ctrl_qliEstimatedSellFor( ApexPages.StandardController stdController ){
        
        this.qte_sObj = ( Quotes__c )stdController.getRecord();
        
        qli_List = new list< QuoteLineItems__c >();
        soo_List = new List <SystemsOrOptions__c > ();
        TravelCost = 0;
        TravelCostTest = 0;
        EstimatedSellForTotal = 0;
        
        for( QuoteLineItems__c q : [SELECT Id,Name, RelatedQuote__r.CommissionPercentageForCalculations__c, RelatedQuote__r.FinalCommissionAmount__c, Qty__c, FlowItemNumber__c, RelatedQuote__r.SellForPricewoCommission__c, RelatedQuote__c, 
                                    Description2__c, ContributionCode__c, TotalCost__c, TaxCost__c, CustomerFacingPrice__c, SellForEstimated__c, RelatedQuote__r.GMNC__c, RelatedQuote__r.Name, SystemsOrOptions__r.CostOfTravel__c, 
                                    PercentageOfCost__c, RelatedQuote__r.BaseOptionsEquipmentTotalCost__c, AdHocCost__c, AdHocSegments__c, Type__c, ProductType__c, SystemsOrOptions__r.MechanicalInstallationCost__c, 
                                    SystemsOrOptions__r.ElectricalInstallationCost__c, SystemsOrOptions__r.StartupServicesCost__c, AdhocTotalCost__c
                                    FROM QuoteLineItems__c
                                    WHERE RelatedQuote__c = : qte_sObj.Id
                                    ORDER By Name ASC] ){
                                        qli_List.add( q );
                                    }
        
        for (SystemsOrOptions__c s : [SELECT Id, Name, CostOfTravel__c FROM SystemsOrOptions__c
                                      WHERE Quote__c = : qte_sObj.Id]){
                                          soo_List.add(s);
                                          IF(s.CostofTravel__c != null){
                                              TravelCostTest = (TravelCostTest + s.CostOfTravel__c);
                                              system.debug('TravelCostTest************************' + TravelCostTest);
                                          }
                                          else{
                                              system.debug('Null Value in s.CostOfTravel ' + s.Id);
                                          }
                                      }
        Integer counter = [SELECT count() FROM QuoteLineItems__c WHERE RelatedQuote__c = : qte_sObj.Id];
        
        for( QuoteLineItems__c qli : qli_List ){
            if( qli.ContributionCode__c == '500M1' && qli.TotalCost__c != null){
                TravelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pem = 0.065 * (qli.TotalCost__c+ (0.047* qli.TotalCost__c));
                pf = 0.047 * qli.TotalCost__c;
                se = 0.132 * qli.TotalCost__c;
                qli.TaxCost__c = pem + pf + se;
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                
                //Quotes Gross Margin Net of Commission
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal;
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            }
        }
        for( QuoteLineItems__c qli : qli_List ){
            if(qli.ContributionCode__c == 'OEM1' && qli.TotalCost__c != null){
                travelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pf = 0.047 * qli.TotalCost__c/2;
                pem = 0.065 * (qli.TotalCost__c + pf);
                se = 0.132 * qli.TotalCost__c;
                qli.TaxCost__c = (pem + pf + se);
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                system.debug('Commission Percentage' + CommissionPercentage);
                
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal;
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            } 
        }
        for( QuoteLineItems__c qli : qli_List ){
            if(qli.ContributionCode__c == 'CTM1' && qli.TotalCost__c != null){
                TravelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pf = 0.047 * qli.TotalCost__c/2;
                pem = 0.065 * (pf);
                qli.TaxCost__c = pem + pf;
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                
                //Quotes Gross Margin Net of Commission
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal; 
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            }
        }
    }
}
 
@IsTest
public class ctrl_qliEstimatedSellFor_test {
    static testMethod void Test1(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'System Custom';
        qli.Type__c = 'Custom';
        qli.ProductType__c = 'Ad-Hoc';
        
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
    
    static testMethod void Test2(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'OEM';
        qli.Type__c = 'Custom';
        qli.ProductType__c = 'Ad-Hoc';
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
    
        static testMethod void Test3(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'Controls';
        qli.Type__c = 'Controls';
        qli.ProductType__c = 'Ad-Hoc';
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
}

How can I test this for 100% coverage?
@HttpGet
global static List<Box__c> getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');
    if(boxId == null)
    {
        return [SELECT Id, Title__c
                FROM Box__c
                LIMIT 1000];
    }
    else
    {
        List<Box__c> boxList;
        boxList = [SELECT Id, Title__c 
                   FROM Box__c
                   WHERE Id =: boxId
                   LIMIT 1000];
        return boxList;
    }
}
My test It works, but only 80%:
@isTest
static void testBox() {
    Id recordId = idd();
    RestRequest request = new RestRequest();
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Box__c/' + recordId;            
    request.httpMethod = 'GET';
    RestContext.request = request;

    List<Box__c> b = OurClass.getBox();

    for(Box__c pneBox : b){
        System.assertEquals(pneBox.Id, recordId);
    }
}

static Id idd() {
    Box__c bb = new Box__c(
        Title__c = 'Title',
    );
    insert bb;
    return bb.Id;
}
Hello,
I'm trying to pass the account Id to the new Contact role but I'm getting this error: Compile Error: Variable does not exist: currentAccoun​t.Id
public class AccountWithContactRolesExtension{	
	Account currentAccount {get; set;}
	
	public AccountWithContactRolesExtension(ApexPages.StandardController stdCtrl){
		std=stdCtrl;
		lstInner = new List<innerClass>();
		addMore();
		selectedRowIndex = '0';
		currentAccount = (Account) std.getRecord();
		System.Debug('#######current Account Id:' + currentAccount.Id); 
	}

    public void Add()
    {   
        count = count+1;
       // AccountId = getAccount().id;
        addMore();      
    }
    
    /*Begin addMore*/
    public void addMore()
    {
        //call to the iner class constructor
        innerClass objInnerClass = new innerClass(count);
        
        //add the record to the inner class list
        lstInner.add(objInnerClass);    
        system.debug('lstInner---->'+lstInner);            
    }/* end addMore*/
        
    public class innerClass {     

        public String recCount
        {get;set;}
		
        /*Inner Class Constructor*/
        public innerClass(Integer intCount) {
            recCount = String.valueOf(intCount);        
            
            /*create a new AccountContactRole*/
            if(intCount>0 && contactRole == null && currentRecord != null){
               AccountContactRole   contactRole = new AccountContactRole(AccountId=currentAccount.Id);
            }    
        }/*End Inner class Constructor*/    
    }/*End inner Class*/
}
Thank you for your help.
 
Here's my code, page, extension & test.  No coverage for the entire list of attachments.
Extension:
public class CaseListController {
    
    private final Case cas; 
    private String sortOrder = 'CreatedDate'; 
    public Case cCas;
    public Case pCas; 
    public Id theParent;
    
    public CaseListController(ApexPages.StandardController stdController) {
        this.cas = (Case)stdController.getRecord();
        cCas=[SELECT id, parentid, casenumber FROM case WHERE id=:cas.id];
        pCas=[SELECT id FROM case WHERE id=:cCas.ParentId]; 
        theParent=pCas.id;
        System.debug('The Parent Record is: ' + theParent); 
    }
    
    public List<Attachment> getAttachments() {
        List<Attachment> results; 
        If(theParent != null){
            results = Database.query(
                'SELECT Id, parentid, parent.name, name, CreatedDate, ContentType, ownerid ' + 
                'FROM Attachment ' + 
                ' WHERE parentid =:theParent ' + 
                'ORDER BY ' + sortOrder + ' DESC ' + 
                'LIMIT 10'
            ); 
        } 
        return results;
    }
}
Page: 
<apex:page standardcontroller="Case" extensions="CaseListController" sidebar="false" showHeader="false" >
    <apex:form >
        <apex:pageBlock title="Parent Attachments" id="attachments_list"> 
            <apex:pageBlockTable value="{! attachments }" var="at">
                <apex:column headervalue="File">
                    <apex:outputLink value="/servlet/servlet.FileDownload?file={! at.id}" target="_blank">{! at.Name}
                    </apex:outputLink>
                </apex:column>
                <apex:column value="{! at.contenttype }"/>
                <apex:column value="{! at.createddate }"/>
                <apex:column value="{! at.ownerid }"/>
                <apex:column value="{! at.parent.name }" headerValue="Case"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Test:  
@isTest
public class CaseListController_Test {

    public static testMethod void testMyController() {
        Account testAccount = new Account();
		testAccount.Name='Test Account'; 
        testAccount.Phone='(999) 999-9999';
        
        Case ParentCase = new Case();
        ParentCase.AccountId = testAccount.id; 
        ParentCase.RecordTypeId='012L000000073y2';
        ParentCase.Reason__c='Move User';
        ParentCase.Subject = 'Test Parent Case'; 
        ParentCase.Description = 'Test Parent Case'; 
        insert ParentCase; 
        
        Case ChildCase = new Case();
        ChildCase.AccountId = testAccount.id; 
        ChildCase.ParentId = ParentCase.id;
        ChildCase.RecordTypeId='012L000000073y2';
        ChildCase.Reason__c='Move User';
        ChildCase.Subject = 'Test Parent Case'; 
        ChildCase.Description = 'Test Parent Case'; 
        insert ChildCase; 
        
        Attachment atch = new Attachment();
        Blob bodyBlb=Blob.valueOf('test body');
        atch.Name='test attachment'; 
        atch.parentid=ParentCase.Id; 
        atch.Body=bodyBlb;
        insert atch;
        
        Test.startTest();
        PageReference pageRef = Page.ParentCaseAttachments;
        pageRef.getParameters().put('Id',ChildCase.Id);
        Test.setCurrentPage(pageRef);
        
        ApexPages.StandardController sc = new ApexPages.StandardController(ChildCase);
        CaseListController ext = new CaseListController(sc);
        Test.stopTest();
    }
}

Any direction is appreciated!
  • September 11, 2018
  • Like
  • 0
Hi,
Can you please help me with test class


Class:

global with sharing class BatchToEndCarouselAnnouncementsScheduler extends BatchScheduler implements Schedulable
{
    global BatchToEndCarouselAnnouncementsScheduler()
    {
        super(10 /*minutes between attempts */, 'End Carousel Announcements');
    }
    
    global void execute(SchedulableContext sc)
    {
        schedule(new BatchToEndCarouselAnnouncements());
    }
}


Extended Class:

public with sharing abstract class BatchScheduler implements Schedulable
{
    @TestVisible static final Integer MAX_CONCURRENT_BATCH = 5;
    @TestVisible Integer minutesBeforeReschedule;
    @TestVisible String title;
    public BatchScheduler( Integer minutes, String title )
    {
        this.minutesBeforeReschedule = minutes;
        this.title = title;
    } 
    public void schedule( IBatchHelper helper, Integer batchSize )
    {
        Integer currentlyRunningBatches = [SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex'
                                           AND (Status = 'Processing' OR Status = 'Preparing')];
        if( currentlyRunningBatches < MAX_CONCURRENT_BATCH )
        {
            BatchHandler batch = new BatchHandler( helper );
            Database.executeBatch( batch, batchSize );
        }
        else
        {
            scheduleRetry();
        }
    }

    public void schedule( IBatchHelper helper )
    {
        schedule( helper, 200 );
    }

    @TestVisible void scheduleRetry() 
    { 
        Datetime rescheduleDateTime = Datetime.now().addMinutes(minutesBeforeReschedule); 
        String timeForScheduler = rescheduleDateTime.format('s m H d M \'?\' yyyy'); 
        System.schedule(title + ' ' + timeForScheduler, timeForScheduler, this); 
    } 
}
  • September 11, 2018
  • Like
  • 0
can you please me to write test class on below code:
Apex code:

public class copycontact {
    public list<selectoption>account1{set;get;}
    public list<selectoption>account2{set;get;}
    public list<contact>contacts{set;get;}
    public String getListOfAccounts { get; set; }
    public id selectedaccountId1 {set;get;}
    public id selectedaccountId2 {set;get;}
    public list<id>selected ;
    public List<SelectOption> getListOfAccounts1()
    {
        List<Account> AccountList1 = [select id,Name from Account] ;
        System.debug('Accounts'+AccountList1.size());
        account1 = new List<SelectOption>();
        account1.add(new SelectOption( ' ' ,'---Select---'));
        for(Account acc : AccountList1 )
        {
            account1.add(new SelectOption(acc.id , acc.Name));
        }
        return account1 ;         
    }
    public List<SelectOption> getListOfAccounts2()
    {
        List<Account> AccountList2 = [select id,Name from Account] ;
        System.debug('Accounts'+AccountList2.size());
        account2 = new List<SelectOption>();
        account2.add(new SelectOption( ' ' ,'---Select---'));
        for(Account acc : AccountList2 )
        {
            account2.add(new SelectOption(acc.id , acc.Name));  
        }
        system.debug('java');
        return account2 ;  
    } 
    public  void clonecontacts(){
        system.debug('gsvdd');
        if(selectedaccountId1!=null){
            contacts=new list<contact>([select id,lastname from contact where accountid=:selectedaccountId1]);
            if(contacts.size()==0){
                system.debug('gsg'   );
               ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No contacts to display'));
            }
            else{
                system.debug('dhg');
                list<contact>clist=new list<contact>();
                for(Contact con:contacts){
                    contact c=new contact();
                    c.lastname=con.LastName;
                    c.AccountId=selectedaccountId2;
                    clist.add(c);
                }
                insert clist;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'successfully copied'));
            }
        }
    }
}
vf page:

<apex:page controller="copycontact">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection title="from Account" >
                <apex:OutputPanel >
                    <apex:selectList value="{!selectedaccountId1}" size="1" multiselect="false" >
                        <apex:selectOptions value="{!ListOfAccounts1}"  />
                    </apex:selectList>
                </apex:OutputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
            <apex:pageBlockSection title="to account">
                <apex:selectList value="{!selectedaccountId2}" size="1" multiselect="false"  >
                    <apex:selectOptions value="{!ListOfAccounts2}" />
                </apex:selectList>
            </apex:pageBlockSection> >
        </apex:pageBlock>
        <apex:commandButton value="clone" action="{!clonecontacts}"/>
        <apex:pageMessages ></apex:pageMessages>
    </apex:form>
</apex:page>
Hi All,
​         i want to create a trigger on Account to count number of opportinty and contact relateed to Account.
How to do it?
Any suggestion?
Can anyone provide test class for following VF PAGE . The requirement is to search text in account,,contact,lead.
Please Include minimum 5 Asserts and test cases for positive negative bulk scenarios.

-------------------------------------------------VF--------------------------------------------
<apex:page Controller="SOSLController">
  <apex:form >
    <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!search}" reRender="accountId,error,opportunityId,contactId" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
      <apex:facet name="start" >
      <img src="/img/loading.gif"/>                    
      </apex:facet>
    </apex:actionStatus>
  </apex:form>
    
  <apex:outputPanel title="" id="error">
    <apex:pageMessages ></apex:pageMessages>
  </apex:outputPanel>
  
  
  <apex:pageBlock title="Accounts" id="accountId">
    <apex:pageblockTable value="{!accountList }" var="accountVar">
      <apex:column value="{!accountVar.name}"/>
      <apex:column value="{!accountVar.Type}"/>
    </apex:pageblockTable>
  </apex:pageBlock>

  
 
  <apex:pageBlock title="Contacts" id="contactId">
    <apex:pageblockTable value="{!contactList}" var="contactVar">
      <apex:column value="{!contactVar.name}"/>
      <apex:column value="{!contactVar.email}"/>
    </apex:pageblockTable>
  </apex:pageBlock>
  
  
      
  
  <apex:pageBlock title="Opportunities" id="opportunityId">
    <apex:pageblockTable value="{!OpportunityList}" var="opportunityVar">
      <apex:column value="{!opportunityVar.name}"/>
      <apex:column value="{!opportunityVar.StageName}"/>
    </apex:pageblockTable>
  </apex:pageBlock>
</apex:page>
-------------------------------------------------Controller------------------------------------------

Public with sharing class SOSLController{
  Public List<Opportunity> OpportunityList {get;set;}
  Public List<contact> contactList{get;set;}
  Public List<account> accountList{get;set;}
    
  Public String searchStr{get;set;}
    Public SOSLController(){
    }
    /**
    Method:searchText 
    Description : Method use SOSL Query to search the text.
    @return : searchText or Error Message */
    Public List<List<sObject>> search(){
      OpportunityList = New List<Opportunity>();
      contactList = New List<contact>();
      accountList = New List<account>();
     
      String searchStr1 = '*'+searchStr+'*';
      String searchQuery = 'FIND \'' + searchStr1 + '\' IN Name FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
      List<List <sObject>> searchList = search.query(searchQuery);
      accountList = ((List<Account>)searchList[0]);
      contactList  = ((List<contact>)searchList[1]);
      OpportunityList = ((List<Opportunity>)searchList[2]);
      if(accountList.size() == 0 && contactList.size() == 0 && OpportunityList.size() == 0){
          apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
          
      }
    return searchList;
    }
}
  • August 17, 2018
  • Like
  • 0
Hi,
   
   Below trigger is working fine on a single transaction can we change this code to handle bulk load logic. Please suggest me
  
Trigger convertToUSD on Opportunity (before update){
     
  Try 
   {
       List<String> oppiso = new List<String>();  
       List<date> cdate = new List<date>();
      
      for(Opportunity o : trigger.new) 
        {
         oppiso.add(o.CurrencyIsoCode);
         cdate.add(o.closedate);
        }
    
        Double cts = [SELECT ConversionRate FROM DatedConversionRate 
                 where isocode IN :oppiso and 
                       startdate <= :cdate 
                 order by startdate desc limit 1].conversionRate;
                 
                  
       for(Opportunity ops : trigger.new) 
       {
        ops.CURRENCY_RATE__c = cts;
       }
    }
 
    catch (Exception e)
    {
        system.debug(e);
        for(Opportunity ops : trigger.new) 
        {
        ops.CURRENCY_RATE__c = null;
        }
    }  
}
Thanks
Sam
 
Hi There,

I've created a visualforce page based on a custom object and an extension which enables this to be opened from the account screen. 

Whenever I click "Save", I am redirected back to the account I invoked the visualforce page, however the record I created on the visualforce doesn't appear to be saving. 

 VF page:
<apex:page StandardController="Account" extensions="accountProp" sidebar="false">
    <apex:sectionHeader title="Edit AccountProperty" />
    <apex:form >
        <apex:pageBlock title="Edit AccountProperty" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Property Information" columns="1">
                    
                    <apex:pageBlockSectionItem >                       
                        <apex:outputLabel value="Property_Name__c"/>
                        <apex:outputPanel >                            
                            <apex:inputField value="{!objB.Property_Name__c}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
            </apex:actionRegion>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'Sunrise ID'}">
                <apex:inputField value="{!ObjB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.Sunrise_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="SVU Channel" columns="1"
                                   rendered="{!objB.Property_Name__c == 'SVU Site ID'}">
                <apex:inputField value="{!objB.Account__c}" required="true"/>
                <apex:inputField value="{!objB.SVU_SITE_ID__c}" required="true"/>
                <apex:inputField value="{!objB.Start_Date__c}" required="true"/>
                <apex:inputField value="{!objB.Implementation_Date__c}" required="true"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public with sharing class accountProperty {
    
    ApexPages.StandardController sc;
    public Account_Property__c objB {get; set;}
    
    public accountProperty(ApexPages.StandardController sc)
    {
        this.sc = sc;
        objB = new Account_Property__c();
    }
    
    public ApexPages.PageReference SaveBoth()
    {
        insert objB;
        return sc.Save();
    }

}
I want output or not output some tag in visualforce page.
How can use if else?
ex:
<apex:repeat value="{!MapProducts[ikey]}" var="item">
                              {!if(item.id==0)}
                               <div class="columnnull">
                                   
                                </div> 
                              {!else}
                              <div class="column">                           
                                  <div class="zoomimage"> 
                                 </div>
                              </div>

 
How to write Test Class for dependent picklist methods?
  
 @AuraEnabled
    public static List<String> getDepStates(String objectType, String parentField, String childField,String search){    
        List<String> optionStates = new List<String>();
        PicklistFieldController controller = new PicklistFieldController();
        Map<String,List<String>> valueMap = PicklistFieldController.getDependentOptionsImpl(objectType,parentField,childField);
        for(String contr : valueMap.keySet()){
           // System.debug('CONTROLLING FIELD : ' + contr);
            //System.debug('DEPENDENT VALUES ...  : ' + valueMap.get(contr));
            if(search==contr){
                optionStates=valueMap.get(contr);
            }
        }
        return optionStates;
    }
    @AuraEnabled
    public static List<String> getPickList(String field,String objectName){    
        List<String> lstPickvals=new List<String>();
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objectName);
        Sobject Object_name = targetType.newSObject();
        Schema.sObjectType sobject_type = Object_name.getSObjectType(); 
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); 
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); 
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field).getDescribe().getPickListValues(); 
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
            lstPickvals.add(a.getValue());//add the value  to our final list
        }        
        return lstPickvals;
    }
   
}
I am changing one particular  field by checking lastmodifeddate in my code.All works fine but i am struck with test class.I am chnaging multiple records from multiple objects so my batch class looks like below.
 
global class editrecords implements Database.Batchable<string>, Schedulable{
global boolean bool = false;

global Iterable<string> start(Database.BatchableContext ctx) {
    return new list<String> { 'CO__c', 'CO2__c', 'CO3__c','CO4__c'};
}
global void execute(Database.BatchableContext ctx, list<string> listObj) {
    list<sObject> editrecords = new list<sObject>();
    for(string strObjName : listObj) {
        for(sObject objsObject : database.query('Select Id from ' + strObjName + ' where LastModifiedDate < LAST_N_DAYS:36')) {
                editrecords.add(objsObject);
            else {
                b = true;
                break;
            }
        }
    }
    update editrecords;
}
global void finish(Database.BatchableContext ctx) {

}        global void execute(SchedulableContext sc){
         Database.executebatch(new editrecords ());    
    }
}

my test class is as below which get 58% of coverage.How can i get lastmodified date and cover rest of code.please help.
 
@isTest
Public class testeditrecords{

    static testMethod void testMethod1(){

        CO__c CO =new CO__c(Name='testdata');
        insert CO;
        CO2__c co2 =new 
  co2__c(Name='testdata');
        insert co2;
        Co3__c co3 =new Co3__c(Name='test2');
        insert co3;

       for(CO__c c:[Select ID from CO__c where createddate=TODAY]){
        Test.startTest();
       
        editrecords obj = new editrecords();
        Database.executeBatch(obj);
        Test.stopTest();       
        }
   } 
}

 
Hello,

The business requirement is to have a lookup relation ship between a Contract and Opportunity. A field on the opportunity must get the SUM of a custom field on the Contracts which belong to the opportunity. I use the @future annotation to increase the CPU time, however, I get an error "Attempt to de-reference a null object".

Here's the code. I got the error on line 6 where I define the Set<ID>
public class contractRollUpCLASS {
    @future
    public static void calculate() {
  
    //limit the size of list by using Sets which do not contain duplicate elements.
    Set<ID> oppIds = new Set<ID>();

    
    //when adding new or updating existing contracts.
    if(trigger.isInsert || trigger.isUpdate) {
        
        for(Contract con : (List<Contract>)trigger.new) {
        
            if(con.Is_Obsolete__c == false)
            oppIds.add(con.Renewal_Opportunity__c);
        }
    }
    
    
    //when deleting contracts.
    if(trigger.isDelete){
        
        for(Contract con : (List<Contract>)trigger.old ) {
           if(con.Is_Obsolete__c == false)
            oppIds.add(con.Renewal_Opportunity__c);
        }
    } 
    System.debug('***************NUMBER OF IDS ************** : '+ String.ValueOf(oppIds.size()));
    
    //Map will contain one Opportunity Id to one sum value.
    map<Id, Double> OpportunityMap = new Map<Id,Double>();
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    //aggregate result.
    for(AggregateResult q : [SELECT Renewal_Opportunity__c, SUM(Latest_PD_Renewal_Amount__c) sumLatest FROM Contract WHERE Renewal_Opportunity__c IN : oppIds AND Latest_PD_Renewal_Amount__c != null GROUP BY Renewal_Opportunity__c]) {
        OpportunityMap.put((Id)q.get('Renewal_Opportunity__c'),(Double)q.get('sumLatest'));
    }
    
    for(Opportunity opp : [SELECT Id, Annual_Maintenance_Value__c FROM Opportunity WHERE Id IN : oppIds]) {

        Double sumLatestPD = OpportunityMap.get(opp.Id);
        opp.Annual_Maintenance_Value__c = sumLatestPD;
        oppsToUpdate.add(opp);     
    }    
    update oppsToUpdate;   
    
}
}

Any help would be much appreciated.
Angel
 
@RestResource(urlMapping='/Merchandise/*')
global with sharing class MerchandiseResource {

private class Attach {
    String Body;
    String ContentType;
    String Name;
}
private class Merchandise {
    Merchandise__c merchandise;
    list<Attach> attachments;
} 

@HttpPost
global static String doPost() {
    //json will be taken directly from RestContext
    Merchandise container = (Merchandise)System.JSON.deserialize(
        RestContext.request.requestBody.tostring(), 
        Merchandise.class);

    Merchandise__c merch = container.merchandise;
    insert merch;

    list<attachment> attachmentToInsert = new list<attachment>();

    for (Attach att :container.attachments) {
        attachmentToInsert.add(
            new Attachment(parentId = merch.Id, name = att.name, 
                           ContentType = att.ContentType, 
                           Body = EncodingUtil.base64Decode(att.body)));
    }
    insert attachmentToInsert;

    return merch.id;
}}

Can anyone suggest me a test class for this above code.
I send the following json.
 
{
    "merchandise": {
        "Name": "Eraser"
    },
    "attachments": [{
        "Body": "d29ybGQ=",
        "ContentType": "text/plain",
        "Name": "hello.txt"
    }, {
        "Body": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY3growIAAycBLhVrvukAAAAASUVORK5CYII=",
        "ContentType": "image/png",
        "Name": "picture.png"
    }]
}


I also tried the below test class,
 
@isTest
public class TesMerchandiseResource 
 {
    
     private Static testMethod void testFunction()
     {


System.RestContext.request = new RestRequest();
        System.RestContext.response = new RestResponse();
        RestContext.request.requestBody =blob.valueof('{}');

		
		 Account accountDetails = new Account();
        accountDetails.name = 'test name';
        upsert accountDetails;
		
 Attachment attachIt = new Attachment();
        attachIt.Name = 'test_attch';
        attachIt.ParentId = accountDetails.id;
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
      attachIt.body=bodyBlob;
	  
	   RestContext.request.requestBody =blob.valueof('{     "merchandise": {         "Name": "Eraser"     },     "attachments": [{         "Body": "d29ybGQ=",         "ContentType": "text/plain",         "Name": "hello.txt"     }, {         "Body": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY3growIAAycBLhVrvukAAAAASUVORK5CYII=",         "ContentType": "image/png",         "Name": "picture.png"     }] }');
        MerchandiseResource .doPost();

}

}

Still I get error "Attempt to de-reference a null object" in the line ​"for (Attach att :container.attachments) {"

Thanks in Advance,
Leafen.
 
From child-Parent soql
----------------------------
Parent = college
child =student(lookup with parent)
relation =Students

written query as

for(Student__c s:[select Name,college__r.Name,CollegeName__c from student__c])
{
  system.debug('student Name:'+s.Name+'     college Name:'+s.college__r.Name);
}

but error as

Line: 3, Column: 18
select Name,college__r.Name,CollegeName__c from ^ ERROR at Row:1:Column:13 Didn't understand relationship 'college__r'
Hello, 

I created this trigger which set a share type for each new content document link. 
trigger ContentDocumentLinkTrigger on ContentDocumentLink (before insert) {
    
    for(ContentDocumentLink cdl: Trigger.new){
        cdl.shareType = 'I';
    } 
}
I tried to create this test class:
@isTest
public class ContentDocumentLinkTriggerTest {
    
    @isTest static void ContentDocumentLinkTriggerTest() {
        
        // Create a ContentVersion
        ContentVersion ContentDoc = new ContentVersion();
        ContentDoc.Title = 'My Doc';
        ContentDoc.ContentUrl= 'test.com';
        Insert ContentDoc;
        
        // Create a ContentDocumentLink
        ContentDocumentLink ContentDL = new ContentDocumentLink();
        ContentDL.ContentDocumentId = ContentDoc.Id;
        Insert ContentDL;
        
        // Verify the share type is = i
        System.assertEquals(ContentDL.ShareType,'I');
        
        
    }
}

But I receive this error: 
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, ContentDocument ID: id value of incorrect type: 0683E0000003EXVQA2: [ContentDocumentId]

Any idea why ? 
Hi  All,

Am getting code coverage error for my test class? Can anyone help me to get code coverage?

Trigger : 
trigger taskRestriction on task (Before insert,After update,Before Update) {
  
    list<Contact> clist =new list<Contact>();
    
    String userid=UserInfo.getUserId();
    
    String ProfileID=userinfo.getProfileId();
  
  
    
        for (Task t : Trigger.new) {
       
        if (t.WhoId !=Null  && userinfo.getProfileId()=='00e90000000O4VsAAK' )
        {
                
          clist= [select ID, ownerId ,Account_name__C, Account.Lock_record__C from Contact where 
          ID=:t.WhoId and Account.Lock_record__C!=True and  OwnerId !=:UserInfo.getUserId()]; 
                
            }
            
            IF(Clist.size()>0)
            {
            T.adderror('This contact is assigned to other user, Kindly Contact Sir/Madam to Change the Ownership');
            }
            }                   
}

Test Class:

@isTest

public class TaskBlockedTest
{
    @isTest
    public static void testLeadInsert ()
    
    {
             Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
            
            Lead objLead = new Lead (LastName='Test2Dup',E_Mail_Additional__c='test3@duptest.com', Email='test2@duptest.com',LeadSource='Click India',
       MobilePhone='7452638196',Whatsapp_Mobile__c='7452638194' ,Mobile_Additional__c='7452638193' ,Phone='7452638192',
       Phone_Additional__c='7452638191', Status='Open',Customer_Type__c='Shop',Company='Test',Date__c= Date.newInstance(2018, 03, 23));
        
            insert objLead; 
            
            Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
           insert a; 
           
           Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
    
     System.runAs(u) 
        { 
            Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             Insert testTTask;
             
             
        Test.startTest();
        testTTask= new task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
        ownerid=con.ownerid);
        Database.SaveResult result = Database.insert(testTTask, false);
           Test.stopTest();
           }
        
    }
    
    @isTest
    public static void testLeadUpdate ()
    {
        
             Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
             
            User u = new User(Alias = 'Test', Email='Test@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='shakila@gmail.com');
            
            insert u;
            
                Lead objLead = new Lead (LastName='Test2Dup',E_Mail_Additional__c='test3@duptest.com', Email='test2@duptest.com',LeadSource='Click India',
            MobilePhone='7452638196',Whatsapp_Mobile__c='7452638194' ,Mobile_Additional__c='7452638193' ,Phone='7452638192',
           Phone_Additional__c='7452638191', Status='Open',Customer_Type__c='Shop',Company='Test',Date__c= Date.newInstance(2018, 03, 23));
        
            insert objLead; 
            Account a = new Account(Name = 'ApprovalTest' ,Lock_record__C=FALSE ,ownerid=u.ID);
           insert a; 
           
           Contact con = new COntact();
            con.email='test@fmail.co';
            con.ACCOUNTID=a.ID;
            con.ownerid=a.ownerid;
            con.lastname='test' ;
            
            insert con;
         
           
           
        System.runAs(u) 
        { 
    
            Task testTTask= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             Insert testTTask;
             
               List<Account> listact=New List<Account>{[select OwnerID from Account Where ownerID=:u.ID ]};
             
         List<task> taskstoupdate = New List<task>{[select Time_New__c, Task.Account.Name from Task where  ownerId =:u.id limit 1]};
             
              Task testTTask2= new Task(Subject = 'EventTest',  Description = 'Description',WhoId= con.Id ,
             ownerid=con.ownerid);
             
             Insert testTTask2;
             
             Task tk =[select Subject from Task where ID=:testTTask2.ID];
             
             tk.Subject ='Test';
             
             
             Update tk;
               
       
              
            
   
        
        }
         
        
       
    }
}
 
Hi Everyone, 

I have writen a short apex code to be able display a couple of fields from Salesforce however, I now have to write a test class, 

So it would be great if someone could please assist me :)  

This is my short apex code that I have:
public with sharing class AccountController {
    @AuraEnabled
    public static List<Account> findAll() {
    return [SELECT id, name, Location__Latitude__s, Location__Longitude__s, Industry
            FROM Account
            WHERE Location__Latitude__s != NULL AND Location__Longitude__s != NULL
            LIMIT 50];
    }
    
}

 
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
When i am posting code "" is not printing. And Some code is removing automatically. 

Any idea . It look like some issue ?
External Lookup Relationship could now be setup between external objects and Salesforce object.
External Object - They are same as custom objects but used to map to data located outside Salesforce.
External object take data from External source and External source obviously has its own DB. 
To create external object : From Setup, click Develop | External Objects.
To create external Data source : Develop | External data source
 
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
I created a new dev org but I did not get the verification/confirmation email. Now I cannot use the email for another username. How do I move forward.
hi guys im really new to apex and salesforce i need to write a test class for this class
public without sharing class CM_Report_LTN_Controller {
    public String reportId {get;set;}
    public String reportIdStato {get;set;}
    public User userReport {get;set;}
    public String dashId {get;set;}
    public String URL {get;set;} 

    public CM_Report_LTN_Controller(ApexPages.StandardController controller) {
        dashId = [SELECT DeveloperName,Id,Name FROM Report WHERE 
                            DeveloperName = 'POD_Report'
                            LIMIT 1].Id;
        system.debug('CM_Report_LTN_Controller reportId is'+dashId);
            
        // Get the report metadata
        Reports.ReportDescribeResult describeDash = Reports.ReportManager.describeReport(dashId);
        Reports.ReportMetadata DashMd = describeDash.getReportMetadata();
        Reports.ReportResults resultsDash = Reports.ReportManager.runReport(dashId, DashMd);
        
        reportId = [SELECT DeveloperName,Id,Name FROM Report WHERE 
                            DeveloperName = 'Codice_Fiscale_Report'
                            LIMIT 1].Id;
        system.debug('CM_Report_LTN_Controller reportId is'+reportId);
            
        // Get the report metadata
        Reports.ReportDescribeResult describe = Reports.ReportManager.describeReport(reportId);
        Reports.ReportMetadata reportMd = describe.getReportMetadata();
        Reports.ReportResults results = Reports.ReportManager.runReport(reportId, reportMd);
        
        URL__C u = URL__C.getInstance();
        URL = u.urlOrg__c;
        
        }  
    
}
so far i worte this which is not correct at all 
@isTest
public class CM_Report_LTN_ControllerTest {
	@isTest
    static void test(){
        Report rp = new Report();
        ApexPages.StandardController cont = new ApexPages.StandardController(rp);
        CM_Report_LTN_Controller controller = new CM_Report_LTN_Controller(cont);
    }
}

is there anyone that can help me with this ? or give me some info about ApexPages.StandardController ?
 

Challenge Not yet complete... here's what's wrong: 
The Sales Operation dashboard isn't configured according to the requirements. 1. The Bar chart, Gauge and Donut must measure Sum of Amount and must be named correctly. 2. The filter must be named Stage value. 3. The dashboard should run as the logged in user.
I am getting the annoying "Attempt to de-reference a null obect" error when trying to deploy a VF page and Class/Test Class. I have 100% code coverage on my test class and it functions perfectly in sandbox. I cannot seem to figure out where/why I am getting the error. Below is the code for both the class and test class. I am getting an error at line 64, 96, and 127 in the class. 
public class ctrl_qliEstimatedSellFor {
    
    public list< QuoteLineItems__c > qli_List	{get;set;}
    public List < SystemsOrOptions__c > soo_List {get;set;}
    private final Quotes__c qte_sObj;
    decimal pem {get;set;}
    decimal pf {get;set;}
    decimal se {get;set;}
    decimal GMNC {get;set;}
    decimal CostTotal {get;set;}
    decimal TravelCost {get;set;}
    decimal TravelCostTest {get;set;}
    decimal CommissionPercentage {get;set;}
    decimal SellForWoCommission {get;set;}
    decimal CommissionAmount {get;set;}
    decimal EstimatedSellForTotal {get;set;}
    
    public ctrl_qliEstimatedSellFor( ApexPages.StandardController stdController ){
        
        this.qte_sObj = ( Quotes__c )stdController.getRecord();
        
        qli_List = new list< QuoteLineItems__c >();
        soo_List = new List <SystemsOrOptions__c > ();
        TravelCost = 0;
        TravelCostTest = 0;
        EstimatedSellForTotal = 0;
        
        for( QuoteLineItems__c q : [SELECT Id,Name, RelatedQuote__r.CommissionPercentageForCalculations__c, RelatedQuote__r.FinalCommissionAmount__c, Qty__c, FlowItemNumber__c, RelatedQuote__r.SellForPricewoCommission__c, RelatedQuote__c, 
                                    Description2__c, ContributionCode__c, TotalCost__c, TaxCost__c, CustomerFacingPrice__c, SellForEstimated__c, RelatedQuote__r.GMNC__c, RelatedQuote__r.Name, SystemsOrOptions__r.CostOfTravel__c, 
                                    PercentageOfCost__c, RelatedQuote__r.BaseOptionsEquipmentTotalCost__c, AdHocCost__c, AdHocSegments__c, Type__c, ProductType__c, SystemsOrOptions__r.MechanicalInstallationCost__c, 
                                    SystemsOrOptions__r.ElectricalInstallationCost__c, SystemsOrOptions__r.StartupServicesCost__c, AdhocTotalCost__c
                                    FROM QuoteLineItems__c
                                    WHERE RelatedQuote__c = : qte_sObj.Id
                                    ORDER By Name ASC] ){
                                        qli_List.add( q );
                                    }
        
        for (SystemsOrOptions__c s : [SELECT Id, Name, CostOfTravel__c FROM SystemsOrOptions__c
                                      WHERE Quote__c = : qte_sObj.Id]){
                                          soo_List.add(s);
                                          IF(s.CostofTravel__c != null){
                                              TravelCostTest = (TravelCostTest + s.CostOfTravel__c);
                                              system.debug('TravelCostTest************************' + TravelCostTest);
                                          }
                                          else{
                                              system.debug('Null Value in s.CostOfTravel ' + s.Id);
                                          }
                                      }
        Integer counter = [SELECT count() FROM QuoteLineItems__c WHERE RelatedQuote__c = : qte_sObj.Id];
        
        for( QuoteLineItems__c qli : qli_List ){
            if( qli.ContributionCode__c == '500M1' && qli.TotalCost__c != null){
                TravelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pem = 0.065 * (qli.TotalCost__c+ (0.047* qli.TotalCost__c));
                pf = 0.047 * qli.TotalCost__c;
                se = 0.132 * qli.TotalCost__c;
                qli.TaxCost__c = pem + pf + se;
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                
                //Quotes Gross Margin Net of Commission
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal;
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            }
        }
        for( QuoteLineItems__c qli : qli_List ){
            if(qli.ContributionCode__c == 'OEM1' && qli.TotalCost__c != null){
                travelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pf = 0.047 * qli.TotalCost__c/2;
                pem = 0.065 * (qli.TotalCost__c + pf);
                se = 0.132 * qli.TotalCost__c;
                qli.TaxCost__c = (pem + pf + se);
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                system.debug('Commission Percentage' + CommissionPercentage);
                
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal;
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            } 
        }
        for( QuoteLineItems__c qli : qli_List ){
            if(qli.ContributionCode__c == 'CTM1' && qli.TotalCost__c != null){
                TravelCost = 0;
                gmnc = qli.RelatedQuote__r.GMNC__c;
                pf = 0.047 * qli.TotalCost__c/2;
                pem = 0.065 * (pf);
                qli.TaxCost__c = pem + pf;
                CommissionPercentage = qli.RelatedQuote__r.FinalCommissionAmount__c / qli.RelatedQuote__r.SellForPricewoCommission__c;
                
                //Quotes Gross Margin Net of Commission
                GMNC = qli.RelatedQuote__r.GMNC__c/100;
                CostTotal = qli.TotalCost__c + qli.TaxCost__c;
                TravelCost = (TravelCostTest * (qli.PercentageofCost__c/100));
                SellForWoCommission = ((CostTotal + TravelCost) / (1-GMNC));
                CommissionAmount = ((SellForWoCommission * CommissionPercentage) / (1-GMNC));
                qli.SellForEstimated__c = SellForWoCommission + CommissionAmount;
                EstimatedSellForTotal = qli.SellForEstimated__c + EstimatedSellForTotal; 
                
                system.debug('GMNC ' + GMNC);
                system.debug('PEM ' + pem);
                system.debug('SE ' + Se);
                system.debug('PF ' + Pf);
                system.debug('Cost Total ' + CostTotal);
                system.debug('TravelCost '+ TravelCost);
                system.debug('Estimated Sell For w/o Commission ' + SellForWoCommission);
                system.debug('Commission Amount ' + (SellForWoCommission * CommissionPercentage));
                system.debug('Estimated Sell For ' + EstimatedSellForTotal);
                system.debug('QLI Percentage of Cost +' + qli.PercentageofCost__c);
                system.debug('Travel Cost Test ' + TravelCostTest);
            }
        }
    }
}
 
@IsTest
public class ctrl_qliEstimatedSellFor_test {
    static testMethod void Test1(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'System Custom';
        qli.Type__c = 'Custom';
        qli.ProductType__c = 'Ad-Hoc';
        
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
    
    static testMethod void Test2(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'OEM';
        qli.Type__c = 'Custom';
        qli.ProductType__c = 'Ad-Hoc';
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
    
        static testMethod void Test3(){
        RFQ__c rfqObj                              = new RFQ__c();
        insert rfqObj;
        
        Account a = new Account();
        a.Name = 'Name';
        insert a;
        
        Opportunity opp = new Opportunity();
        opp.StageName = 'Developing Proposal';
        opp.Name = 'test';
        opp.CloseDate = system.today();
        insert opp;
        
        Quotes__c q = new Quotes__c();
        q.RFQ__c = rfqObj.Id;
        q.Name = 'test';
        q.Opportunity__c = opp.Id;
        q.QuoteType__c = 'Budgetary';
        q.MarginPercentage__c = 0.32;
        q.SetSellForPrice__c = 2000000;
        q.CommissionCalculationType__c = 'Shick Standard';
        q.FinalCommissionAmountPB__c = 0;
        insert q;
        
        SystemsOrOptions__c soo = new SystemsOrOptions__c();
        soo.Quote__c = q.Id;
        soo.Locked__c = false;
        soo.Name		= 'Test';
        soo.MechanicalInstallationCost__c = 0;
        soo.ElectricalInstallationCost__c = 0;
        soo.StartUpServicesCost__c = 0;
        insert soo;
        
        QuoteLineItems__c qli = new QuoteLineItems__c();
        qli.RelatedQuote__c = q.Id;
        qli.SystemsOrOptions__c = soo.Id;
        qli.ClonedItem__c = false;
        qli.AdHocCost__c = 4000;
        qli.Qty__c = 100;
        qli.AdHocSegments__c = 'Controls';
        qli.Type__c = 'Controls';
        qli.ProductType__c = 'Ad-Hoc';
        
        insert qli;
               
        system.test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController( q );
        ctrl_qliEstimatedSellFor ctrl = new ctrl_qliEstimatedSellFor( sc );
        
        system.test.stopTest();

    }
}
Hi, I am working on trailhead called Picklist Administration https://trailhead.salesforce.com/en/modules/picklist_admin/units/picklist_admin_manage and I am getting the following error while trying to create a formula field:       

Challenge not yet complete... here's what's wrong: There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: MLHXOLBN

Challenge description:
Use the formula editor to set the Default Value for the Macaron Flavor picklist as follows:CASE(MONTH(TODAY()),1, "Gingerbread",2, "Strawberry",4, "Chocolate",7, "Raspberry",11, "Pumpkin",12, "Mint", "Vanilla")


Any ideas what could cause the issue?

How can I test this for 100% coverage?
@HttpGet
global static List<Box__c> getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');
    if(boxId == null)
    {
        return [SELECT Id, Title__c
                FROM Box__c
                LIMIT 1000];
    }
    else
    {
        List<Box__c> boxList;
        boxList = [SELECT Id, Title__c 
                   FROM Box__c
                   WHERE Id =: boxId
                   LIMIT 1000];
        return boxList;
    }
}
My test It works, but only 80%:
@isTest
static void testBox() {
    Id recordId = idd();
    RestRequest request = new RestRequest();
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Box__c/' + recordId;            
    request.httpMethod = 'GET';
    RestContext.request = request;

    List<Box__c> b = OurClass.getBox();

    for(Box__c pneBox : b){
        System.assertEquals(pneBox.Id, recordId);
    }
}

static Id idd() {
    Box__c bb = new Box__c(
        Title__c = 'Title',
    );
    insert bb;
    return bb.Id;
}
Rather than creating multiple Lightning components I would like to reuse my components and have the admin specify the Custom Label when they add the component to the page. I am not sure if this is possible although this article screenshots show it working https://salesforce.stackexchange.com/questions/155974/translate-designattribute

When I do the same thing it does not work; it returns the value the admin sets and not the value from the custom label.

Conversely, this article makes me think it is not possible as it says that "Label expressions in markup are supported in .cmp and .app resources only. "https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_config_for_app_builder_design_files.htm

Has anyone got this to work recently?
 
Component

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
 <aura:attribute name="Report" type="String" />
 <p>{!v.Report}</p>

<!--Tried it like this as well-->
<p>{!'$Label.c.'+ v.Report}</p>
</aura:component>


Design
<design:component label="Report">
	<design:attribute name="Report" 
                      label="Report" 
                      Description = "The custom label"
                      default="{!$Label.c.Report}"/>
</design:component>

 
Hi all,

I need to write a test class for a simple LEX component which I built, but I am struggling to understand how to write it. Can you please help me?
 
public class MyOLIController {
    
    @AuraEnabled
    public static List<OpportunityLineItem> getProduct(List<Id> opportunityIds){
        Case cs = [Select Enquiry__c from Case where Id=:opportunityIds];
        List<OpportunityLineItem> productList = [SELECT Id, Property__c, OpportunityId, Start_Date_Time__c,End_Date_Time__c,Status__c  
                                                 FROM OpportunityLineItem 
                                                 WHERE OpportunityId=:cs.Enquiry__c
                                                 AND (Status__c='confirmed' OR Status__c='pending' 
                                                                             OR Status__c='booked' 
                                                                             OR Status__c='stayed')];
        return productList;
    }
}

 
This is what my code is suppose to be doing: 
To pass this challenge, create an Apex class that inserts a new account named after an incoming parameter. If the account is successfully inserted, the method should return the account record. If a DML exception occurs, the method should return null.


public class AccountHandler {

    public static Account insertNewAccount(String accName){
        if(accName!=''){    
            try{
                Account a = new Account(Name=accName);
                insert a;    
                return a;
            } catch(Exception e){
                
                return null;
            }
        } else {
        return null;
        }
    }
}

When I test it inside of the execute anonymous window, I input "insertNewAccount('abcd');". I get an error saying "Method does not exist or incorrect signature: void insertNewAccount(String) from the type anon"
 
@RestResource(urlMapping='/Merchandise/*')
global with sharing class MerchandiseManager {

@HttpPost
global static String createMerchandise(String  firstname)
{
Merchandise__c m = new Merchandise__c( Name=firstname); 
insert m;
return m.Id;
}
)
I wants to know how this api be called by somebody from outside salesforce,i have tried workbench but that does not give me much idea.so if the json body is something like 
{
"firstname":'james"
}

How will this information be passed by calling the above method from outside salesforce.How will i call above given method.please help
 
 
// Trigger

trigger Opportunity_Misc on Opportunity (before insert, before Update) 
if(Trigger.isBefore && Trigger.isInsert){

      MyHelperClass.NewStep(Trigger.new);        
    }

// class
public with sharing class MyHelperClass  {
    public static void NewStep(List<Opportunity> newstepopps){

}


// test clas 

@isTest
    public static void testNewStep(){
   
    // create test opportunity 
        Opportunity opp = Test_Helper.CreateOpp(contact,user);
        insert(opp);

Test.startTest();

        Opportunity opp1 = opp.clone(true);
        
            List<Opportunity> newloanopps = AutoAssignCampaignHelper.NewLoan(opp1);    

        Test.stopTest();
}


 
  • September 17, 2018
  • Like
  • 0
Hello,
I'm trying to pass the account Id to the new Contact role but I'm getting this error: Compile Error: Variable does not exist: currentAccoun​t.Id
public class AccountWithContactRolesExtension{	
	Account currentAccount {get; set;}
	
	public AccountWithContactRolesExtension(ApexPages.StandardController stdCtrl){
		std=stdCtrl;
		lstInner = new List<innerClass>();
		addMore();
		selectedRowIndex = '0';
		currentAccount = (Account) std.getRecord();
		System.Debug('#######current Account Id:' + currentAccount.Id); 
	}

    public void Add()
    {   
        count = count+1;
       // AccountId = getAccount().id;
        addMore();      
    }
    
    /*Begin addMore*/
    public void addMore()
    {
        //call to the iner class constructor
        innerClass objInnerClass = new innerClass(count);
        
        //add the record to the inner class list
        lstInner.add(objInnerClass);    
        system.debug('lstInner---->'+lstInner);            
    }/* end addMore*/
        
    public class innerClass {     

        public String recCount
        {get;set;}
		
        /*Inner Class Constructor*/
        public innerClass(Integer intCount) {
            recCount = String.valueOf(intCount);        
            
            /*create a new AccountContactRole*/
            if(intCount>0 && contactRole == null && currentRecord != null){
               AccountContactRole   contactRole = new AccountContactRole(AccountId=currentAccount.Id);
            }    
        }/*End Inner class Constructor*/    
    }/*End inner Class*/
}
Thank you for your help.
 
We've found that while you can have an sObject collection attribute on a lightning component that implements the lightning:availableForFlowScreens interface and access the attribute from the flow designer,  you cannot see the attribute if the component was created in a developer org that has a package prefix.

Example: We created the following sample component in both a clean developer org, and an org that had a package prefix defined:
 
<aura:component implements="lightning:availableForFlowScreens" access="global">
    <aura:attribute name="contacts" type="Contact[]" />
    <aura:iteration items="{!v.contacts}" var="contact">
        {!contact.Name}: {!contact.Email}<br/>
    </aura:iteration>
</aura:component>

And configured the design attributes so that the flow designer would be able to "see" the component attribute:
<design:component >
    <design:attribute name="contacts" label="Contact records"/>
</design:component>



The flow designer in package org refused to display the "Contact records" attribute:
(we also published the component as part of the package and tested it in the flow designer of the target org and got the same results).

User-added image 

However if we use the same source code to create a component in a non-packaging org, the component (without a namespace prefix) works fine and we can see the component attribute in the flow screen inputs and outputs:

User-added image

Has anyone else run into this?
I was working on the Customize Your Login Process with My Domain module and I accidentally changed my domain of my Hands-On Org. Is it possible to change it back to what it was? I get an error message now when I try to launch my hands-on org. L

My former Hands On Org. URL is as follows: curious-badger-397879-dev-ed.my.salesforce.com

The domain I changed it to is: mylightsaber.dom-dev-ed.my.salesforce.com
 
NOT (ISPICKVAL( Transfer_ID__r.Transfer_Type__c , 'Store to WHS') AND (Shipping_Quantity__c > Serial_No__r.Quantity_available__c ))

I am getting ) missing in thie validation rule, Can someone help?

System.QueryException: List has more than 1 row for assignment to SObject
Class.AccountSearchUI.<init>: line 13, column 1

My VF Page

<apex:page standardController="Account" extensions="AccountSearchUI">
<head>
<title>Account Search UI</title>
<style type="text/css"> </style>
</head>

<body>
<table width="99%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
      </tr>
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
    <td bgcolor="#FFFFFF" valign="top">
        <table width="100%" border="0" align="center" cellpadding="1" cellspacing="0" class="tablemain">
            <tr><td height="1"></td></tr>
            <tr><td height="50" class="headingmain">&nbsp;Account Search UI</td></tr>
            <tr>
                <td align="center">
                  <table width="100%" border="0" cellspacing="0" cellpadding="1" class="tablemain">
                    <tr>
                      <td width="10%" height="23" class="headingsub1">Group Org Acc</td>
                      <td width="10%" height="23" class="headingsub1">Vertical</td>
                      <td width="10%" height="23" class="headingsub1">Account Name</td>
                      <td width="10%" height="23" class="headingsub1">Type</td>
                      <td width="10%" height="23" class="headingsub1">Owner Last Name</td>
                      <td width="10%" height="23" class="headingsub1">Client Rank</td>
                      <td width="10%" height="23" class="headingsub1">Account Plan</td>
                      <td width="10%" height="23" class="headingsub1">Last Modified</td>
                      <td width="10%" height="23" class="headingsub1">View Latest PDF</td>
                      <td width="10%" height="23" class="headingsub1">PDF Upload Date</td>
                    </tr>
                    <apex:repeat value="{!accPList}" var="cp">
                    <tr>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                    </tr>
                    </apex:repeat>
          </table>
        </td>
        
      </tr>
    </table></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
  </tr>
  
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>

</table>

</body>

</apex:page>

APEX Class
public with sharing class AccountSearchUI{    

    public ApexPages.StandardController stdController {get; set;}
    public Account acc {get; set;}
    public Account accPList {get; set;}
    
    public String accountName ='';
    public AccountSearchUI(ApexPages.StandardController stdController){
    this.stdController = stdController;

 accPList = [select Group_Org__c, Vertical__c, Name, Type, Client_Rank__c from Account where Top_25_Client__c = true and Client_Rank__c < 26 order by Client_Rank__c ASC limit 5];
    }
}
Can anyone help with the issue.
 
This is my code
=============
global class BatchApex implements Database.Batchable<sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id from Opportunity');
        
    }
    global void execute(Database.BatchableContext bc,List<Opportunity>scope){
        for(Opportunity o:scope){
            o.Name='sandhya';
        }
    update scope;
}
    global void finish(Database.BatchableContext bc){
            
   Messaging.SingleEmailMessage[] mail=new Messaging.SingleEmailMessage();
        String[] toAddresses=new String[] {'forcesfdcloud@gmail.com'};
            mail.setToAddresses(toAddresses);
        mail.setSubject('sending mail ');
        mail.setPlainTextBody('process completed success fully');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
      
    }
    }
I want to update my opportunities. After updating the opportunities i want to send a mail to the above mentioned address, but it shows error like" Illegal assignment from Messaging.SingleEmailMessage to List<Messaging.SingleEmailMessage>" can any one tell me how to solve this issue.
trigger CheckValidationonCaseClose on Case (after update) {     
for(Case e:Trigger.New){          
Case d=Trigger.oldMap.get(e.Id);         
if(d.Signature_Required__c==true && d.Customer_Signature_Status__c!='Completed' && e.IsClosed==true)
{  
e.adderror('Cannot Close Case');
}

its urgent
}  
Hi,

I have a rquirement to format a time which is given in HH:MM format (24-hour clock) into the user's locale. I assumed that there would be a fromat() method as the DateTime class does, but it does not exist.

Any ideas how I can do this?

Thanks
I have a Salesforce App which passed security review for the first time in the last year. This App also includes integration with external web application, due to this I also submitted a BURP scan report of the external web application. I am not sure about how Salesforce conducts periodic security review and have some queries.

As you may know, Salesforce provides periodic, point-in-time review at an interval determined by salesforce.com (typically anywhere between 6 months to 2 years).

• As per Salesforce documentation for already passed Apps, around the expiry date, Salesforce contacts partners to arrange another review. Can you guide me on how much time Salesforce gives us to prepare for Security Review?

• BURP scan and fixing the issues reported by it can take time. If I could not submit a clean BURP scan report within the time frame provided by Salesforce, Does Salesforce remove package from AppExchange?

• Salesforce charges for Security Review process for paid Apps, as one-time upfront fee, and a small subsequent annual fee. Can you guide me on how much subsequent annual fee Salesforce charges to partners? Salesforce also charges annual listing fee of $150 USD. Is that correct?

Kindly help me with this. Thanks in advance.
Hi All,

I want to disable the global search for particular users,i have disabled the chatter in chatte section,please give me suggestion how to disable the global search.
see the below screen shot where i have disabled
User-added image

see the below screen shot for what i want to disable 

User-added image

Thanks,
Surya
I'm stuck on only one unit for this module; the controlling access to fields unit:

"Two team members need to view and update Accounts, but only one should be able to see and edit the Rating field. Create one profile and one permission set with field level security to solve for this use case.The profile must be named 'Basic Account User' and result in an API name of 'Basic_Account_User'. It should use the 'Salesforce' user license type.
The permission set must be named ‘Account Rating’ and result in an API name of 'Account_Rating'."

"Challenge Not yet complete... here's what's wrong:
The 'Basic Account User' profile did not have the appropriate object and field-level security for the Account object "
  • February 02, 2016
  • Like
  • 1
Hi Jacob,

I have already completed 5 badges, but still no email for obtaining the Cloak of Adventure sweatshirt. Does it take username or email address for sending emails, as my email address and user name are different.

User-added image
Hi,

I want to send an email alert to task owner if they have any open task which due date is already passed.
I want to send it 1 day after due date and 1 week after due date.
Please suggest how I can achieve it because through workflow it is not achievable.

Regards
Emily
 view state and need a steps how can we reduce view state without help of transient
Hi,

I have executed "Run all test" to get code coverage of all apex classes. Is there way to get all apex classes code coverage with percentage copy to excel sheet. I am able to see all classes with percentage in Developer console. But not able to copy all those. Please provide some suggestion.
We are using Apex Data Loader 19.0 and cliq_process.  Using Apex Data Loader & Cliq_process, we are exporting the data into salesforce custom object. The process was working fine past 2 years and till last week. Last few days we are getting the below error.


2015-08-17 06:12:31,218 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:104) - Logging in to: https://www.salesforce.com/services/Soap/u/19.0
2015-08-17 06:12:31,233 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:989) - Beginning Partner Salesforce login ....
2015-08-17 06:12:31,249 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:998) - Salesforce login to https://www.salesforce.com/services/Soap/u/19.0/services/Soap/u/19.0 as user forceuser@<company>.com
2015-08-17 06:12:31,655 INFO  [ExportRevenue] dao.DataAccessObjectFactory getDaoInstance (DataAccessObjectFactory.java:51) - Instantiating data access object: C:\Program Files\salesforce.com\Apex Data Loader 19.0\cliq_process\ExportRevenue\write\ExportRevenue.csv of type: csvWrite
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:109) - Checking the data access object connection
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:114) - Setting field types
2015-08-17 06:12:31,766 ERROR [ExportRevenue] client.PartnerClient describeSObject (PartnerClient.java:1249) - Error while calling web service operation: describeSObject, error was: Failed to send request to https://ncst.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:840)
    ... 19 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    ... 24 more
2015-08-17 06:12:31,766 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:214) - Unable to run process ExportRevenue
java.lang.RuntimeException: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:139)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    ... 1 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
Exact replication steps:
1. Create a connected app
2. Add the callback URL to that connected app as the URL of a VF page. For Eg - 'https://c.eu2.visual.force.com/apex/mypage'.
3. Connect to another salesforce org of the same instance.Énter the login details ie username and password
4. Allow permission to the connected app create on your source org to access info about target org by clicking on Állow Button'
5. Instead of redirecting back to source org it redirects me to the target org and tries to open up the page mentioned in the callback url.
6. This issue is coming when my source and target org are on same instance. It works fine when source and target instances are different.
Hello,
I have some queries on release versioning and listing subsequent versions on AppExchange:
  1. Can I release and maintain 2 versions on AppExchange? In other words, if there a v1.0 that is listed on AppExchange, and we release a new version v1.1 that has passed Security Review and ready to be listed on AppExchange, does it automatically replace the v1.0 that was listed earlier? 
  2. Do the existing customer orgs get any notification of a new released version? If yes, does it automatically contain the install link? If not, what is the most preferred practice?
  3. If I deprecate an earlier version, do the customer orgs using this version get a notification to upgrade? Are they forced to upgrade?
  4. If a patch is created for a particular released version, do I have to manually inform all customer orgs using it? Or do they get automatic notifications of the same and can choose to apply the patch as needed?
Thanks in advance!
Hi,

I want to develop an "Open CTI Adapter", where can I find the documentation(API/Library) for the same?

Regards,
Rohan
Hi ,
  
 I'm trying to parse Account records to JSON string. But I'm getting unnecessary data like attributes(type,url) that is not required in String.

Can any one pls help me in how to parse the string to required format.
List<Account> accnts=[Select Name,Phone From Account];
String s=JSON.serialize(accnts);
The resulting output is in below fromat..
{
  "attributes" : {
    "type" : "Account",
    "url" : "/services/data/v34.0/sobjects/Account/00128000002trGGAAY"
  },
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}


My requirement is to generate resulting String as below JSON string format.
 
{
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}

So that I can minimize the data to to be sent the the client system.

Any help is really appreciated. Thanks in advance.

Regards,
Naveen.
I need to download Contacts Near By component for the trailhead - field sales app project but I am not able to find it on appexchange. Any idea where can I get it from?