• Glyn Anderson (Slalom)
  • NEWBIE
  • 495 Points
  • Member since 2017
  • Solution Principal
  • Slalom


  • Chatter
    Feed
  • 15
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 153
    Replies
Hello Everyone,
I am having a field called Discount Percent at quotelineitem. 
If a quotelineitem is of a specific Product Category and there are many quotelineitems of the same product category, when discount % is applied to one lineitem of that product category in an onchange event automatically the discount percent should be applied to all lineitems of the same product category. 
Could anyone suggest how to do that? 
Thanks
 
I have a custom setting called BindValues__c which has a single field say value__c
It contains values as : A1  1   , A2  2   , A3  3  ,  A4  4 , A5  5 , A6  6 , A7 7 , A8  8 , A9  9 , A10  10 , A11  11

I have worked on a code which binds the values into a picklist as shown below , also I attached a screen shot to show my requirement.

custom setting
values

data
public class CodeGeneratorController {
    public List<SelectOption> Values { get; set; }
    
    public CodeGeneratorController() {
        getValues();
    }
    
    public void getValues() {
        Values = new List<SelectOption>();
        
        List<BindVaues__c> allValues = new List<BindVaues__c>();

        allValues=[SELECT  Name FROM BindVaues__c];
        
        for( BindVaues__c val : allValues) {
          Values.add( new SelectOption( val.Id, val.Name) );
        }
    }
}
<apex:page controller="CodeGeneratorController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:outputLabel value="Values :"/>
                  
                <apex:selectList size="1">
                    <apex:selectOptions value="{!Values}"/>
                </apex:selectList>
             </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
My requirement is I need to access values from 1 to 5 , then do some processing , then values from 6 to 11 then do some other logic.

so I need to split the custom setting values into 2 parts i. 1 to  5 and   6  to 11.
I hope I am clear.
Please let me know how I can proceed further.

Thanks
sheila
 
Hi Guys,

We have an appex trigger that creates a "new" opportunity in a custom tab (AE Opps), which works perfectly. Now, I'm trying to create a custom tab, called AE Tasks, which will take the tasks from the AE Opps tab, and populate them in the new custom tab (AE Tasks). Is there a way to do this or will I need a new apex trigger?

Many thanks
Hey everyone, trying to get my APEX skills up. Can't seem to figure out how to debug this error. Any advice? 

Thanks, 
 
public class ContactSearch{
    public static Contact searchForContacts(String lastName, String zip){
        List<Contact> conts =[SELECT Id, Name FROM Contact WHERE LastName=:lastName AND MailingPostalCode=:zip ]; 
        
        return  conts;
    }
	
}

 
Hello,
I am a salesforce admin and new to apex. We have reached cross object references in our org and would like to create a trigger. 
I have to pull the  First name and Last name of the user in Manager lookup field on Account using a trigger. Can anyone help me creating a trigger? 
The Property has field "Available". The Property “Available” field should be set to "True" by default. If the property has
prospective Client the “Available” field must be changed to “False” automatically. Need i do it with Triggers?
Hi everyone,
How to filter a SOQL query by two or more fields (key fields)? For example let's say I have an object with three fields: Person (String), Year (String) and Income (Number). Person and Year are key fields. And there are four records in the object:

Person                    Year                       Income
'Jhon'                      '2016'                      1000
'Jhon'                      '2017'                      950
'Mike'                      '2016'                       1100
'Mike'                      '2017'                       900

Then I want to retrieve data about Jhon's income in 2016 and Mike's income in 2017
In some SQL implementations I can do it in such way:
Select Person, Year, Income From MyObject Where (Person, Year) In (('Jhon', '2016'), ('Mike', '2017'))
What about SOQL? I was told that it won't accept such a query. Is there any means? Or I have to use "And" filter separately for every field and then use a loop?

Im having an error with my code. Not really familiar with reverse method. Need help with checking this and creating a simple test class.

this is the code that I got so far:

public class Example {
    public static void reverseWordInMyString(String str){
        List<String> str = new List<String>{''};
            List<String> reversedString = new List<String>();
        if(!str.isEmpty()){
            for (String s : str){
                reversedString.add(s.reverse());
            }
        }
        System.debug(str);
        System.debug(reversedString);        
    }    
}

Thanks in advance

Hi all. can you simplify the above to something similar to SOQL's "IN" operator? Do not want to duplicate field name for every potential value check 
Hi,

I've created a email field (bcc) in lead.I want to populate bcc mail id here using email service class.How can i acheive this?

Thanks
Devmen
  • August 05, 2018
  • Like
  • 0
xx__c obj = [select xxnumber from xx__c];
in obj i will get the xxnumber's with comma seperated values (xxnumber = 12345,6789,09876). Here i need to split the comma's and add only the numbers to the list. 
I need to deactivate a  user and portal user by clicking checkbox in contact page. 
trigger activeuser on Contact (after update) {
    ID contactId = [Select contactid from User where id =:UserInfo.getUserId()].contactId; 
   
  for(Contact c : Trigger.new){
    if(c.isactive__c == true) 
            {             
        User u = [SELECT Id,ContactId,IsActive,IsPortalEnabled FROM User  WHERE contactId =:contactId ];
                
                 
                     u.CompanyName ='test';
                    u.IsActive=false;
                    u.IsPortalEnabled=false;
           Update u;

                }
            }
}

am getting error 
System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)


any help..
I need to write a schedulable apex class that will update a custom field in the OpportunityLineItem object everyday.

I have this so far:

global class UpdateOLI Implements Schedulable {

    global void execute(SchedulableContext sc) {
        updateOLI();
    }

    public void updateOLI() {

        List<OpportunityLineItem> affected = [SELECT Id, Name 
                                     FROM OpportunityLineItem
                                     WHERE position_status__c <> Closed];

       // either do your logic actually here with a Message.SingleEmailMessage here, or just fire an update
       for(OpportunityLineItem thisOLI : affected) {
           // Some dummy field to trigger the workflow (gross huh!)
           thisOLI.Apex_Schedule__c = thisOLI.Apex_Schedule__c +1;
       }

      update affected;
    }
}

But have received this error: 
Apex script unhandled exception by user/organization: 

Scheduled job 'Update OLI' threw unhandled exception.

caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: OpportunityLineItem.Apex_Schedule__c

Class.UpdateOLI.updateOLI: line 15, column 1
Class.UpdateOLI.execute: line 4, column 1
 
Pretty new to writing test classes, was looking for help for this trigger:

trigger SumPositions on Investor__c (before insert, before update, before delete) {
    for (Investor__c record : Trigger.new) {
        record.Sum_of_Positions__c = null;
    }
    for(AggregateResult result: [SELECT SEI_Investor_Id__c, SUM(Position__c.Balance__c)
                                 FROM Position__c WHERE SEI_Investor_Id__c
                                 IN :Trigger.newMap.keyset() GROUP BY SEI_Investor_Id__c]) {
         Trigger.newMap.get(result.get('SEI_Investor_Id__c')).Sum_of_Positions__c = (Decimal)result.get('expr0');
     }
 }
Hi, I'm very new to creating triggers so I apologize if this question is somewhat basic. I am trying to create a trigger on an attachment that, when an attachment with a specific file name is uploaded to an account, will update a custom Datetime field on that account. When the attachment with the specific file name is deleted from the account, the value in the Datetime account field should be erased. Using this thread: https://developer.salesforce.com/forums/?id=9060G000000I8UmQAK#!/feedtype=SINGLE_QUESTION_SEARCH_RESULT&id=906F0000000Ayf8IAC  I was able to create a simple trigger, but I am missing the logic portion to limit the trigger to attachments containing the string "Admissions Packet" in the file name. Here is what I have so far: 
trigger AdmissionsPacketUploaded on Attachment (before insert, before delete)
{
if(trigger.isinsert){
List<Account> co = [select id from Account where id =: Trigger.New[0].ParentId];
If(co.size()>0 && Attachment.Name.contains('Admissions Packet'))
{            
    co[0].Date_Admissions_Packet_Uploaded__c = Date.Today();            
update co;        
}
}


if(trigger.isdelete){

List<Account> co = [select id from Account where id =: Trigger.old[0].ParentId];        
If(co.size()>0 && Attachment.Name.contains('Admissions Packet'))        
{            
    co[0].Date_Admissions_Packet_Uploaded__c = NULL;            
update co;        
}
}
}
My two error messages (for both isinsert and isdelete) read "Method does not exist or incorrect signature: void contains(String) from the type Schema.SObjectField." 

Any assistance would be greatly appreciated!

Hello,
I am getting this error: Too many Email Invocations: 11

Is there any way around this? I tried to run a batch with a scope of 1 but its looks like I need to keep it at 200 otherwise I get this error: 

No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

Below is my code:

Batch Class:
 

global class BatchRenewal implements Database.Batchable<sObject>{
    
    public String query = 'SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL';
    
    global Database.queryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator(query); // you can modify the query as per your requirement.
    }
    
    global void execute (Database.BatchableContext BC, List<Account> acct)
    {
            
            Messaging.SingleEmailMessage AlertOver = new Messaging.SingleEmailMessage(); //Alert when greater than or equal to 2500
            Messaging.SingleEmailMessage AlertUnder = new Messaging.SingleEmailMessage(); //Alert  when less than 2500
            
            String[] toAdd1 = new String[] 
            {
               test@test.com
            };
            
            String[] toAdd2 =  new String[] 
            {
                test1@test.com
            };
            
            //Account[] acct = [SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL];
            
            for(Account a: acct)
            {
                String sURL = URL.getSalesforceBaseUrl().toExternalForm()+ '/'+a.Id;
                Date tod = System.today();
                System.debug('%%%%%%%%% '+tod);
                Date contEnd = a.Contract_End_Date__c;
                System.debug('&&&&& '+contEnd);
                Integer dayDiff = contEnd.daysBetween(tod);
                System.debug('******* '+dayDiff);
                
                
                if(dayDiff == 60)
                {    
                    Integer days = 60;
                    
                    if(a.Contract_Amount__c >= 2500)
                    {
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertOver.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertOver.setToAddresses(toAdd1);
                        AlertOver.setSaveAsActivity(False);
                        AlertOver.setHtmlBody(bod);
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertOver
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                    
                    }
                    else
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertUnder.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertUnder.setToAddresses(toAdd2);
                        AlertUnder.setSaveAsActivity(False);
                        AlertUnder.setHtmlBody(bod);
                        
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertUnder
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                        
                    }
                }
                
                if(dayDiff == 30)
                {
                    Integer days = 30;
                    
                    if(a.Contract_Amount__c >= 2500)
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertOver.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertOver.setToAddresses(toAdd1);
                        AlertOver.setSaveAsActivity(False);
                        AlertOver.setHtmlBody(bod);
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertOver
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                        
                    }
                    else
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertUnder.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertUnder.setToAddresses(toAdd2);
                        AlertUnder.setSaveAsActivity(False);
                        AlertUnder.setHtmlBody(bod);
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertUnder
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                        
                    }    
                }
            }
            
        }
        
       
   
    
    global void finish(Database.BatchableContext BC){      
        
    }
}


Schedule Class:

global class ScheduleBatchRenewal implements Schedulable {
   global void execute(SchedulableContext sc) {
      BatchRenewal b = new BatchRenewal(); 
      database.executebatch(b, 1);
   }
}


Test Class:​

@isTest
private class BatchRenewalTest
{
    @testSetup
    static void setup() 
    {
        List<Account> acct = new List<Account>();
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Apple'+i;
            Integer am = 250 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,6,10),Contract_Amount__c=am));
        }
        
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Orange'+i;
            Integer am = 5000 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,6,10),Contract_Amount__c=am));
        }
        
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Banana'+i;
            Integer am = 250 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,7,10),Contract_Amount__c=am));
        }
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Grape'+i;
            Integer am = 5000 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,7,10),Contract_Amount__c=am));
        }
        
        insert acct;
        System.debug(Acct);
        
    }
    
    static testmethod void test() 
    { 
    	Test.startTest();
        BatchRenewal uca = new BatchRenewal();
        uca.query='SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL';
        Id batchId = Database.executeBatch(uca, 200);
        
        ScheduleBatchRenewal sch = new ScheduleBatchRenewal();
        sch.execute(null);
        
        Test.stopTest();
    }
}

Any help would be greatly appreciated!

 
i am trying to create one to  one relation between campaign and campaign member like one campaign member for one campaign.
below is  my code:
trigger CampaignmemberControl on CampaignMember (before insert) {
    If(trigger.isInsert && trigger.isbefore){
        Set<String> CampaignMember_parentid=new Set<String>();
        for (CampaignMember cc:trigger.new){
            If(cc.Email !=null){
                CampaignMember_parentid.add(cc.CampaignId);
            }
            List <CampaignMember> listCampaign= [SELECT Id, Name,(SELECT Id FROM CampaignMembers) FROM Campaign WHERE Id IN:CampaignMember_parentid];
            for(CampaignMember cnew:trigger.new){
                if(listCampaign.size()>0)
                {
                    cnew.addError('Not Allowed');
                }
                
            }update listCampaign;
        }
    }

}

However i am facing error:  Illegal assignment from List<Campaign> to List<CampaignMember>

Please help me with this
  • August 09, 2018
  • Like
  • 0
Hi All,

I am trying to encrypt an object and pass it as query string from an external site(in C#) to a salesforce Apex controller and decrypt it in constructor.
This is the code I am using.

C#:
private string Encrypt256<T>(T dataObject)
        {            
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider
            {
                KeySize = 256,
                Key = Convert.FromBase64String("****"),
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7,
                IV = IV
            };

            // Convert string to byte array
            byte[] src = Encoding.Unicode.GetBytes(SerializeToString(dataObject));

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key,IV))
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return Convert.ToBase64String(dest);
            }
        }
        private static string SerializeToString(object obj)
        {
            string output;
            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);

                output = writer.ToString();
            }
            return output;
        }

APEX Controller:
String queryString = ApexPages.currentPage().getParameters().get('token');
Blob key = Blob.valueOf('***');
String encodedString = EncodingUtil.urlEncode(queryString ,'UTF-8');
 Blob source = Blob.valueOf(encodedString);
Blob decrypted = Crypto.decryptWithManagedIv('AES256', key, source );
jsonString = decrypted.toString();

I keep getting the error 
"|DEBUG|ERROR:System.SecurityException: Input length must be multiple of 16 when decrypting with padded cipher"

I am new to APEX. What am I missing here. 
Hello Everyone,
I am having a field called Discount Percent at quotelineitem. 
If a quotelineitem is of a specific Product Category and there are many quotelineitems of the same product category, when discount % is applied to one lineitem of that product category in an onchange event automatically the discount percent should be applied to all lineitems of the same product category. 
Could anyone suggest how to do that? 
Thanks
 
Hi guys,

I want to get all the dates of current month with its current day.
 
DateTime startDate = System.Date.today().toStartOfMonth(); 
        DateTime endDate = startDate.addMonths(1).addDays(-1);
        
        system.debug('Start Date '+ startDate);
        system.debug('End Date '+ endDate);
        
        for(DateTime d = startDate; d < = endDate ; d.addDays(1))
        {
            system.debug('Current date in loop is  '+ d.day());
            String dayofWeek = d.format('EEEE');
            system.debug('Weekeday is '+ dayofWeek);
        }

I am using above code but it is throwing CPU time limit exceded inside loop 
  • August 08, 2018
  • Like
  • 0
Can someone help me with a query to get the following:

- OwnerId
- Event ID
- ActivityDate
- Subject
- Opportunity ID
- Contact ID (invitees/participants)
 
Hi folks,
Can anyone tell me how to get the dependent picklist values based on the Controlling picklist value in Apex?
I need a Optimise code for that..

Thanks,

I already have this code and it is working fine, bu i need optimise code.

public static Map<String,List<String>> GetDependentOptions(String pObjName, String pControllingFieldName, String pDependentFieldName){
        Map<String,List<String>> objResults = new Map<String,List<String>>();
        //get the string to sobject global map
        Map<String,Schema.SObjectType> objGlobalMap = Schema.getGlobalDescribe();
        if (!objGlobalMap.containsKey(pObjName))
            return objResults;
        //get the type being dealt with
        Schema.SObjectType pType = objGlobalMap.get(pObjName);
        Map<String, Schema.SObjectField> objFieldMap = pType.getDescribe().fields.getMap();
        //verify field names 
        if (!objFieldMap.containsKey(pControllingFieldName) || !objFieldMap.containsKey(pDependentFieldName))
            return objResults;     
        //get the control values   
        List<Schema.PicklistEntry> ctrl_ple = objFieldMap.get(pControllingFieldName).getDescribe().getPicklistValues();
        //get the dependent values
        List<Schema.PicklistEntry> dep_ple = objFieldMap.get(pDependentFieldName).getDescribe().getPicklistValues();
        //iterate through the values and get the ones valid for the controlling field name
        TStringUtils.Bitset objBitSet = new TStringUtils.Bitset();
        //set up the results
        for(Integer pControllingIndex=0; pControllingIndex<ctrl_ple.size(); pControllingIndex++){            
            //get the pointer to the entry
            Schema.PicklistEntry ctrl_entry = ctrl_ple[pControllingIndex];
            //get the label
            String pControllingLabel = ctrl_entry.getLabel();
            //create the entry with the label
            objResults.put(pControllingLabel,new List<String>());
        }
        //cater for null and empty
         objResults.put('',new List<String>());
         objResults.put(null,new List<String>());
        //check the dependent values
        for(Integer pDependentIndex=0; pDependentIndex<dep_ple.size(); pDependentIndex++){            
            //get the pointer to the dependent index
               Schema.PicklistEntry dep_entry = dep_ple[pDependentIndex];
               //get the valid for
            String pEntryStructure = JSON.serialize(dep_entry);                
            TStringUtils.TPicklistEntry objDepPLE = (TStringUtils.TPicklistEntry)JSON.deserialize(pEntryStructure, TStringUtils.TPicklistEntry.class);
            //if valid for is empty, skip
            if (objDepPLE.validFor==null || objDepPLE.validFor==''){
                continue;
            }
            //iterate through the controlling values
            for(Integer pControllingIndex=0; pControllingIndex<ctrl_ple.size(); pControllingIndex++){    
                if (objBitSet.testBit(objDepPLE.validFor,pControllingIndex)){                    
                    //get the label
                    String pControllingLabel = ctrl_ple[pControllingIndex].getLabel();
                    objResults.get(pControllingLabel).add(objDepPLE.label);
                }
            }
        } 
        return objResults;
    }
Hi i have a 5 dependent picklist values say as Ford, toyota, honda, benz, audi.

Ford has 30 picklist values.
toyota has 60 picklist values.
Honda has 100 picklist values
benz has 250 picklist values.
audi has 80 picklist values.

Suppose 1st value of  Ford  picklist value is selected  , i will get the revelant picklist values of Toyota. 
After that Depends up on Ford, Toyota values , another picklist has been selected from Benz. 

i will summarize this, if i select picklist of Ford, Honda values will come, after that benz values will come , after that depends of ford,toyota,honda,benz --the last values audi is automatically choosen..


Can anyone please tell me how to write this one on Lighing component ...and apex code as well.....please ping me i have around 1000 fields to pick automatically from one another
 
  • January 29, 2017
  • Like
  • 0
Hi, 

How to get sObject's dependent picklist in lightning component.
I have tried through <force:inputfield> but no luck.

Thanks,
Anupama


 
I was frustrated with the various answers I had found as to how to get a complete mapping of dependent picklist values, so I combined a few different posts into a solution that works, is efficient, and does not require a web service call. This only works for single level dependencies,

I created a class called Utilities that holds the method GetDependentOptions for getting dependent picklist values. There is also a method called GetPickListValues to retrieve values for a simple picklist. The method FirstControllingValueFor is used to do a reverse lookup given a child value to find the first controlling value that the child is valid for.

public class Utilities {
    public static List<String> GetPickListValues(String object_name, String field_name, String first_val) {
        SObjectType objectType = Schema.getGlobalDescribe().get(object_name);
        List<String> options = new List<String>(); //new list for holding all of the picklist options
        if (first_val != null) { //if there is a first value being provided
            options.add(first_val); //add the first option
        }
        List<String> classes = new List<String>();
        classes.add(object_name);
        List<Schema.DescribeSObjectResult> results = Schema.describeSObjects(classes);
        Schema.DescribeSObjectResult sobject_describe = results[0];
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        if (null != field_map) {
            Schema.SObjectField fs = field_map.get(field_name);
            Schema.DescribeFieldResult dsr = fs.getDescribe();
            if (null != dsr) {
                List<Schema.PicklistEntry> pick_list_values = dsr.getPickListValues(); //grab the list of picklist values for the passed field on the sobject
                if (null != pick_list_values) {
                    for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list            
                        options.add(a.getValue());
                    }
                }
            }
        }
        return options; //return the List
    }
    
    private static Map<String, Integer> base64Vals = null;
    
    private static List<Integer> ConvertB64ToInts(string b64Str) {
        if (base64Vals == null) {
            base64Vals = new Map<String, Integer> {
                'A'=>00,'B'=>01,'C'=>02,'D'=>03,'E'=>04,'F'=>05,'G'=>06,'H'=>07,'I'=>08,'J'=>09,
                'K'=>10,'L'=>11,'M'=>12,'N'=>13,'O'=>14,'P'=>15,'Q'=>16,'R'=>17,'S'=>18,'T'=>19,
                'U'=>20,'V'=>21,'W'=>22,'X'=>23,'Y'=>24,'Z'=>25,'a'=>26,'b'=>27,'c'=>28,'d'=>29,
                'e'=>30,'f'=>31,'g'=>32,'h'=>33,'i'=>34,'j'=>35,'k'=>36,'l'=>37,'m'=>38,'n'=>39,
                'o'=>40,'p'=>41,'q'=>42,'r'=>43,'s'=>44,'t'=>45,'u'=>46,'v'=>47,'w'=>48,'x'=>49,
                'y'=>50,'z'=>51,'0'=>52,'1'=>53,'2'=>54,'3'=>55,'4'=>56,'5'=>57,'6'=>58,'7'=>59,
                '8'=>60,'9'=>61,'+'=>62,'/'=>63
            };
        }
        List<Integer> ints = new List<Integer>();
        for (Integer idx = 0; idx< b64Str.length(); ++idx) {
            String c = String.fromCharArray(new List<Integer> { b64Str.charAt(idx)});
            ints.add(base64Vals.get(c));
        }
        return ints;
    }

    private class TPicklistEntry{
        public string active {get;set;}
        public string defaultValue {get;set;}
        public string label {get;set;}
        public string value {get;set;}
        public string validFor {get;set;}
        public TPicklistEntry(){}
    }

    public static Map<String,List<String>> GetDependentOptions(String pObjName, String pControllingFieldName, String pDependentFieldName) {
        Map<String,List<String>> mapResults = new Map<String,List<String>>();

        //verify/get object schema
        Schema.SObjectType pType = Schema.getGlobalDescribe().get(pObjName);
        if ( pType == null ) return mapResults;
        Map<String, Schema.SObjectField> objFieldMap = pType.getDescribe().fields.getMap();

        //verify field names
        if (!objFieldMap.containsKey(pControllingFieldName) || !objFieldMap.containsKey(pDependentFieldName)) return mapResults;

        //get the control & dependent values
        List<Schema.PicklistEntry> ctrl_ple = objFieldMap.get(pControllingFieldName).getDescribe().getPicklistValues();
        List<Schema.PicklistEntry> dep_ple = objFieldMap.get(pDependentFieldName).getDescribe().getPicklistValues();

        //initialize results mapping
        for(Integer pControllingIndex=0; pControllingIndex < ctrl_ple.size(); pControllingIndex++) {
            mapResults.put( ctrl_ple[pControllingIndex].getLabel(), new List<String>());
        }

        //serialize dep entries
        List<TPicklistEntry> objDS_Entries = new List<TPicklistEntry>();
        objDS_Entries = (List<TPicklistEntry>)JSON.deserialize(JSON.serialize(dep_ple), List<TPicklistEntry>.class);

        for (TPicklistEntry objDepPLE : objDS_Entries){
            List<Integer> bitValues = ConvertB64ToInts(objDepPLE.validFor);

            Integer bitMask = 32; // Ignore highest 2 bits
            Integer intIndex = 0;
            Integer bitIdx = 0;
            for (Integer numBits = bitValues.size() * 6; numBits > 0; --numBits) {
                Integer bits = bitValues[intIndex];
                if ((bits & bitMask) == bitMask) {
                    mapResults.get( ctrl_ple[bitIdx].getLabel() ).add( objDepPLE.label );
                }
                bitMask = bitMask >>> 1;
                ++bitIdx;

                if (bitMask == 0) {
                    bitMask = 32;
                    intIndex = intIndex + 1;
                }
            }
        }
        return mapResults;
    }//GetDependentOptions
   
    public static String FirstControllingValueFor(String pObjName, String pControllingFieldName, String pDependentFieldName, String childValue) {
        Map<String,List<String>> mappedItems = GetDependentOptions(pObjName, pControllingFieldName, pDependentFieldName);
        for (String key : mappedItems.keySet()) {
            List<String> items = mappedItems.get(key);
            Set<String> itemSet = new Set<String>(items);
            if (itemSet.contains(childValue)) {
                return key;
            }
        }
        return null;
    }
}
Hi all,

I am struck where i am not able to show my dependent picklist values using apex. Can anyone suggest how to proceed further ?

the reason i am running  behind apex is VF Page does not allow to show more than 10 dependent standard picklist values even though all these fields are stored in API...

controller
-------------
 public List<SelectOption> getSalesBu()
    {
      List<SelectOption> options = new List<SelectOption>();
      options.add(new SelectOption('--None--','--None--'));
 
      Schema.DescribeFieldResult SBU = Opportunity.Sales_BU2__c.getDescribe();
      List<Schema.PicklistEntry> ple = SBU.getPicklistValues();
        for( Schema.PicklistEntry f : ple)
            {
                options.add(new SelectOption(f.getLabel(), f.getValue()));
            }
       return options;

    }
    

     public List<SelectOption> getProductTypeSalesBu()
    {
      List<SelectOption> options = new List<SelectOption>();
      system.debug('------------SelectedValue-------------'+selectedSalesBu); 
      if(selectedSalesBu != NULL)
      { 
            options.add(new SelectOption('--None--','--None--'));

      for (Opportunity proSales : [select Id,Name,Product_Type_Sales_BU__c from Opportunity Where Sales_BU2__c = :selectedSalesBu])
            {
            
                    options.add(new SelectOption(proSales.id,proSales.name));
             }
       

       }return options;
    } 

i need to show Product_Type_Sales_BU__c  values based on selected Sales BU Selection. I am seeing selected SalesBU Value passed to Query but how to show Product_Type_Sales_BU__c  values..

if i change from

                    options.add(new SelectOption(proSales.id,proSales.name));

to 
                    options.add(new SelectOption(proSales.id,proSales.Product_Type_Sales_BU__c));

i get an error..
The solution all over the web, http://titancronus.com/blog/2014/05/01/salesforce-acquiring-dependent-picklists-in-apex/ does not work in all cases it seems.

Is there an official solution yet, or maybe an alternative? That code above is the only one that seems to be floating around on different sites.

Hi,

I want to retrieved dependent picklist value.I am able to do it by javascript. but i need to use in trigger. In trigger you know we can not excute javascript.
If any one have sample code to get depenedent picklist(either Schema or MetaData Api) values please let me know.It is urgent.

Thanks