• Kon Dele
  • NEWBIE
  • 130 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 17
    Replies
I am trying to insert Account/Contact/Customer records into SFDC using Rest API. i have written the following class. I am able to create the Accounts and Contacts, but I'm having issues creating Customer records. In my setup, Customer is  a child of Contacts, and Contacts a child of Accounts. How should I rewrite my class and JSON to insert Customer records along with Contacts and Accounts in a single call?
Apex Class:
@RestResource(urlMapping='/test/*')
global with sharing class OrderWebServices{

@HttpPost
   global static void createSomething(Wrapper1 test){
		  
		 Account obj = new Account();
		 obj.Name = test.name;
		 obj.AccountNumber = test.accountnumber;
		 obj.External_Id__c = test.externalid;
		 insert obj;
		 List<Contact> conList = new List<Contact>();
		 
		 for(Wrapper2 con : test.Wrapper2){
				  Contact obj2 = new Contact();
				  obj2.LastName = con.lastname;
				  obj2.Email = con.email;
				  obj2.AccountId = obj.Id;
				  conList.add(obj2);
		 }
		 insert conList;
		//Below doesn't insert related Customer
		List<Customer__c> csList = new List<Customer__c>();
		for(Wrapper3 cs : test.Wrapper2){
				  Customer__c obj3 = new Customer__c();
				  obj3.LastName__c = cs.lastname;
				  obj3.Email__c = cs.email;
				  obj3.AccoountId = obj.Id;
				  csList.add(obj2);
		 }
		 insert csList;		 
	}
	global with sharing class Wrapper1{
	  public String name{get;set;}
	  public String accountnumber{get;set;}
	  public List<Wrapper2> Wrapper2{get;set;}
	}
	global with sharing class Wrapper2{
	 public String lastname{get;set;}
	 public String email{get;set;}
	public List<Wrapper3> Wrapper3{get;set;}//Add this for Customer object?
	}
	global with sharing class Wrapper3{
	 public String lastname{get;set;}
	 public String email{get;set;}
	}

}
Here's the JSON payload:
{
	"test": {
		"name": "Test Acc",
		"accountnumber": "12345",
		"externalid": "12345",
		"Wrapper2": [{
			"lastnmame": "last",
			"email": "test123@test.com",			
			"Wrapper3": [{
				"lastname": "customer",
				"email": "customer123@test.com"
			}]			
		},
		{
			"lastnmame": "last2",
			"email": "test456@test.com",			
			"Wrapper3": [{
				"lastname": "customer2",
				"email": "customer123@test.com"
			}]			
		}]
	}
}
The Account record and Contact records are inserted, but the associated Customer__c records are not inserted. I have an external id field 'External_Id__c' which ties all three records, even though Contact is a child of Accounts, and Customer__c is a child of Contacts.

How can I revise the class to be able to insert multiple contacts and multiple Customer__c records?

Thank you!

 
How can I via apex automatically @mention the case owner or case contact on the case feed in chatter? 
Using the code example in the developer's guide, here's my class:
public with sharing class AtMentionsUtility {  

    public static void mentionedUser(){           
        
        Case c = new Case();
        ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
        ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
        ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
        ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

        messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

        mentionSegmentInput.id = c.OwnerId;
        messageBodyInput.messageSegments.add(mentionSegmentInput);

        textSegmentInput.text = '';
        messageBodyInput.messageSegments.add(textSegmentInput);

        feedItemInput.body = messageBodyInput;
        feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
        feedItemInput.subjectId = c.Id;

        ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput, null);
    }
}

 
I have a class and trigger that copies selected values but is there a way to dynamically select all values in a multi-select picklist when an All Offices checkbox is checked?
User-added image
Here's my code:
public class OfficeUpdateClass {
    public static void UpdateOffices (ContentVersion[] ContentVersion1){
        for(ContentVersion cv: ContentVersion1){        
            String pickValuesStr;
            if(!String.isBlank(cv.Office__c)){
                List<String> pickValues = cv.Office__c.split(';');
                for(String str : pickValues){
                    if(String.isBlank(pickValuesStr)){
                        pickValuesStr = str;
                    }else{
                        pickValuesStr = pickValuesStr + '\n' + str;
                    }
                }
            }
            cv.Content_Offices__c = pickValuesStr;  
        }
    }
and the trigger:
trigger OfficeUpdateTrigger on ContentVersion (before insert, before update) {
    ContentVersion[] ContentVersion1 = Trigger.new;
        OfficeUpdateClass.UpdateOffices(ContentVersion1);
}



 
I am trying to copy multi-select picklist values into a Long Text Area field. The issue I am running into is I'm able to copy over a single value, but when multiple values are selected it throws an error.
User-added image
How can I split the String value so that the selection is copied into the Long Text Area with line breaks as follows:
Germany
Kentucky

Here's my code:
public class updateMultiSelectPicklistField {
    public static void updateMSelectPickField (ContentVersion[] ContentVersion1){
        for(ContentVersion c: ContentVersion1){        
            c.Main_Offices__c = c.Office__c;  
        }
    }
}
and trigger:
trigger updatefields on ContentVersion (before insert, before update) {
    ContentVersion[] ContentVersion1 = Trigger.new;
    updateMultiSelectPicklistField.updateMSelectPickField(ContentVersion1);
}


 
Hely yall,
We have a custom VF QuoteLineItem page that automatically calculates Total price based on Discount and Unit Price entered. Is there a way to lock down the UnitPrice  field so that it's only editable by certain profiles? It's an editable apex:inputField. I've tried using an outputField, which displays the UnitPrice but can no longer calculate the Total price. Here's a screenshot and code snippet.User-added image
<apex:inputField value="{!item.Item.UnitPrice}" rendered="{!IF(($Profile.Name =='System Administrator'), true , false)}"/>


 
Hey Yall,
How could I adjust the trigger code below and move the SOQL Query from inside the FOR loop?
trigger OLISyncQLIFields on OpportunityLineItem (before insert,before update) {

    date vServiceEnd;
    date vServiceStart;
    string vQuoteId;
    string vPricebookEntryId;
    string vOpportunity;
 
    for(OpportunityLineItem oppLine : Trigger.new){
           
        vQuoteId = oppLine.QuoteId__c;
        vPricebookEntryId = oppLine.PricebookEntryId;
        
        for(QuoteLineItem quoteLine : [select Id, Service_Start__c, Service_End__c from QuoteLineItem where (QuoteId = :vQuoteId and PricebookEntryId = :vPricebookEntryId)]){
            
            vServiceEnd = quoteline.Service_End__c;
            VServiceStart = quoteline.Service_Start__c;
         
        }
        
        oppLine.ServiceEndDate__c = vServiceEnd;
        oppLine.ServiceStartDate__c = vServiceStart;
        
    }
}

 
How can I remove logic from the following trigger into an apex class?
trigger AssignAccNumber on Opportunity(before insert,before update){
    
    List<Id> accIds = new List<Id>();
    
    for(Opportunity opp:trigger.new){
        
        if(opp.AccountId!=null){
            
            accIds.add(opp.AccountId);
        }
    }
    
    Map<Id,Account> accMap = new Map<Id,Account>([SELECT id,Area__c,AccountNumber,Type FROM Account WHERE id in:accIds]);
    Account a = [SELECT AccountNumber FROM Account WHERE AccountNumber != null AND Type='Prospect' AND Area__c='East' ORDER BY AccountNumber DESC LIMIT 1];
    
    for(Opportunity opp :Trigger.new){
     Account accs = accMap.get(opp.AccountId);       
        
	if(!accMap.IsEmpty()){
            
            if(opp.Probability == 95 && accs.AccountNumber == null){
                
                if(accs.LC_Market__c == 'Americas' && accs.Type == 'Prospect'){
                    
                    accs.AccountNumber = String.valueOf(Integer.valueOf(a.AccountNumber)+1);
                }            
            }
            update accMap.values();
        }
    }            
}

 
I'm trying to write a trigger that would populate a custom field on the OppLineItem when the parent Opportunity stage is updated.

The field would be populated with a value from the Product.

What adjustments do i need to make to my code to get it to function?
trigger OppProductNetValue on Opportunity(before insert,before update){

   Set<Id> pbeIds=new Set<Id>();
  
  for(Opportunity opps:Trigger.new){
   for(OpportunityLineItem oli:opps.OpportunityLineItems){
     if(oli.PricebookEntryId != null){
      pbeIds.add(oli.PricebookEntryId);
      }
    
   Map<Id,Opportunity> oppMap=new Map<Id,Opportunity>(
     
     [SELECT StageName,Order__c from Opportunity where id in :pbeIds]); 
   Map<id,PriceBookEntry> pbeMap = new Map<id, PriceBookEntry>(
             [SELECT id, Product2.id, Product2.True_Price__c
                     FROM PriceBookEntry WHERE id in :pbeIds]);
                     oppMap.putall([select Id, StageName, Order__c from Opportunity where Id in:oppMap.keyset()]);
  for(Opportunity opptys:Trigger.new){ 
   for(OpportunityLineItem ol:opptys.OpportunityLineItems){
     if((pbeMap.containsKey(oli.PriceBookEntryId))&& (oppMap.get(oli.OpportunityId).Order__c == 'Sales Unit')&&  (oppMap.get(oli.OpportunityId).StageName == 'Won')){
                   oli.Net_Price__c = pbeMap.get(oli.PriceBookEntryId).Product2.True_Price__c*oli.Quantity;      
                     }else{
              oli.Net_Price__c = (1-oli.Discount*.01)*(oli.Quantity)*(oli.UnitPrice);
          }  
    }
 }
 }
 }
 }

 
I've written a trigger that updates some fields on the Opportunity Product object with Product values when the Opportunity reaches 95% probability.
The trigger works when I edit and save the OpportunityLineItem but does not update if I just change the Opportunity stage to 95%.
What adjustments do i need to make so that the fields are updated as soon as the Opportunity reaches 95%?
trigger OppProductNetValue on OpportunityLineItem (before insert, before update) {
 
  Map<Id,Opportunity> parentopps = new Map<Id, Opportunity>();

  Set<Id> pbeIds = new Set<Id>();
  
     for(OpportunityLineItem oli : trigger.new) {
        if(oli.PriceBookEntryId != null){
            pbeIds.add(oli.PriceBookEntryId);
            parentopps.put(oli.OpportunityId,null);
       }
    }
    Map<id, PriceBookEntry> pbeMap = new Map<id, PriceBookEntry>(
          [SELECT id, Product2.id, Product2.True_Price__c
         FROM PriceBookEntry WHERE id in :pbeIds]);
    parentopps.putall([select Id, Probability, Order__c from Opportunity where Id in :parentopps.keyset()]);
    
     for(OpportunityLineItem oli : trigger.new) {
        if((pbeMap.containsKey(oli.PriceBookEntryId))&&(parentopps.get(oli.OpportunityId).Order__c == 'Sales Line')&&(parentopps.get(oli.OpportunityId).Probability == 95)){
           oli.Net_Value__c = pbeMap.get(oli.PriceBookEntryId).Product2.True_Price__c*oli.Quantity;      
      }else{
           oli.Net_Value__c = (1-oli.Discount*.01)*(oli.Quantity)*(oli.UnitPrice);
   }  
  }
}

 
I'm trying to add an article search feature to a custom portal page. I have a Search Component, a Controller, and a VF page for this functionality.

The issue is when I enter an InputText in the search component, the text is not passed on to the controller and VF page, and no results are returned.

If I enter text directly in the search box on the VF page, there's success. But the requirement is for the search to be on the component so that it can be iterated on various VF pages. I've posted the code below:

The Component:
<apex:component controller="vfKeywordSearchController">
  <apex:attribute name="theSearchResults" type="String" description="Id of the section rerender."     assignTo="{!searchstring}"/>
    <apex:form >
     <apex:inputText value="{!searchstring}" id="theSearchstring" maxlength="100" size="70"/> &nbsp;
    <apex:commandButton value="Go" id="submitButton" style="width:30" reRender="" action="{!onClick}"/>
   </apex:form>
    </apex:component>
The Controller:

public with sharing class vfKeywordSearchController {

    //Page Size
     private Static Final Integer PAGE_NUMBER = 10;

     //Search String used in ArticleList tag
       public String searchstring { get; set; }

          public PageReference onClick(){
           return new PageReference('/apex/Global_Search_Test?searchParameter='+searchstring);
      }

      public vfKeywordSearchController() {
   String qryString = 'SELECT Id, title, UrlName, LastPublishedDate,LastModifiedById FROM     KnowledgeArticleVersion WHERE (PublishStatus = \'online\' and Language = \'en_US\')';
       List<KnowledgeArticleVersion> articleList= Database.query(qryString);
     maxSize = articleList.size() ;
     }

  //Keeps track of current page & max size of article list
   Integer currentPage = 1;
    Integer maxSize = 1;

   // Returns whether we need to see previous button or not
      public boolean getPrevRequired() {
    return currentPage > 1;
      }

      // Returns whether we need to see next button or not
      public boolean getNextRequired() {
      return currentPage * PAGE_NUMBER < maxSize;
     }

     //Returns current page number 
    public Decimal getCurrentPageNumber() {
     return this.currentPage;
      }

     //action for next click
      public PageReference next() {
      if(maxSize > this.currentPage * PAGE_NUMBER) {
       this.currentPage = this.currentPage + 1;
        }
      return null;
     }    

      //action for previous click
      public PageReference previous() {        
       if(this.currentPage > 1)
        this.currentPage = this.currentPage - 1;
       return null;
       }
       }
The VF Page:

<apex:page id="mypage" controller="vfKeywordSearchController">
         <apex:composition template="LATemplate">
          <c:LASearchComponent theSearchResults="Global_Search_Test:theSearchResults"/>
              <apex:define name="body">
             <apex:form >
             <apex:inputText value="{!searchstring}" id="theSearchstring" maxlength="100" size="70"/> &nbsp;
                 <apex:commandButton value="Go" id="submitButton" style="width:30" reRender=""  action="{!onClick}"/>
                 <apex:panelGroup id="theSearchResults" >
               <apex:panelGrid width="100%">
                 <table width="99%">
           <tr>
             <th width="33%">Title</th>
            <th width="33%">Article Type</th>
            <th width="33%">Summary</th>
            </tr>
            </table>
         <knowledge:articleList articleVar="article" pageNumber="{!currentPageNumber}" Keyword=" {!searchstring}" hasMoreVar="false" pageSize="10">
             <table  width="99%">
             <tr>
             <td width="33%">
              <apex:outputLink target="_blank" value="{!URLFOR($Action.KnowledgeArticle.View, article.id,['popup' = 'true'])}">{!article.title}</apex:outputLink>
                 </td>
              <td width="33%"><apex:outputText >{!article.articleTypeLabel}</apex:outputText></td>
              <td width="33%"><apex:outputText >{!article.abstract}</apex:outputText></td>
                </tr>
           </table>
            </knowledge:articleList>
            </apex:panelGrid> 
          <apex:panelGrid columns="2">
          <apex:commandLink action="{!previous}" value="Previous" style="{!IF(prevRequired = true,'display:block','display:none')}" reRender="theSearchResults"/> 
             <apex:commandLink action="{!next}" value="Next"  style="{!IF(nextRequired = true,'display:block','display:none')}" reRender="theSearchResults"/>  
             </apex:panelGrid>
             </apex:panelGroup>
        </apex:form>
           </apex:define>
    </apex:composition>
        </apex:page>
I appreciate any pointers.


I have a custom field Sales Request that has 2 look up fields to Quote and Opportunity objects.

I'm trying to write a trigger that populates the Opportunity field when a Sales Request is created, but haven't been successful.

Any ideas on how to tweak my trigger below? Thanks!
trigger SalesRequestPopulateOpp on Sales_Request__c(Before Insert,Before Update) { 
    
    List<Id> qIds = new List<Id>();
    
      for(Sales_Request__c sr:trigger.new){

        if(sr.Quote__r.Id!=null){

            qIds.add(sr.Quote__r.Id);
           }
       }
    
  Map<Id,Quote> qMap = new Map<Id,Quote>([select id,Opportunity.Name
                                                     from Quote where id in:qIds]);
        
     for(Sales_Request__c srq :Trigger.new){
        
         if(!qMap.IsEmpty()){
    
                srq.Opportunity__c=qMap.get(srq.Quote__r.Id).Opportunity.Name;
      }            
    }
}


I am trying to create a custom button on the Quote page that creates a Sales Request record when clicked.
The Sales Request is a child object and has a lookup to Quote & Opportunity fields.
I keep getting this error: 'Cannot set property 'Id' of undefined'
Any direction would be appreciated. Here's what I have so far:

 
{!REQUIRESCRIPT('/soap/ajax/30.0/connection.js')}

var srq = new sforce.SObject("Sales_Request__c");
  srq.Id = "{!Sales_Request__c.Id}";
  srq.Quote__r.Id = "{!Quote.Id}";
  srq.Quote__r.OpportunityId = "{!Opportunity.Id}";
  srq.Status_c = "New";
  srq.Type__c = "New";
 
  var result = sforce.connection.create([srq]);
    
   if(result[0].getBoolean("success")){
   window.location = "/" + result[0].id + "/e";
    }else{
    alert('Could not create record '+result);
}


I'm getting the following error in a knowledge article controller that i'm working on:
Article__kav article1 = new Article__kav();
article1 = [select  URLName, id, Title,Partners__c,Cisco_Account__c, Article_Text__c,(select DataCategoryGroupName, DataCategoryName From DataCategorySelections) from Article__kav where publishstatus='Online' and Language = 'en_US' limit 1];
 system.debug(article1+'aaaaa+');
Any ideas on how I could edit this?
I'm trying to write a test class for the following trigger, but I'm only covering 28% of the lines. How can I edit it to cover the 4 if/else conditions?

My Trigger:
 
trigger AccountNumberIndex on Opportunity(before insert,before update){
    
    List<Id> accIds = new List<Id>();
    
    for(Opportunity opp:trigger.new){

        if(opp.AccountId!=null){

            accIds.add(opp.AccountId);
           }
       }
    
       Map<Id,Account> accMap = new Map<Id,Account>([select id,LC_Region__c,AccountNumber,Type 
                                                     from Account where id in:accIds]);
        
       Counterr__c value = new Counterr__c();
                    
       for(Counterr__c record:[SELECT Id,Ones__c,Threes__c,Eights__c,Nines__c FROM Counterr__c FOR UPDATE]) {
                      
       value = record;

     for(Opportunity opp :trigger.new){
        
         if(!accMap.IsEmpty()){
    
            if((opp.Probability == 90) && (accMap.get(opp.AccountId).AccountNumber == null)){
            
              if((accMap.get(opp.AccountId).LC_Region__c == 'North America')&&(accMap.get(opp.AccountId).Type != 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Ones__c);
      
                value.Ones__c+= 1;
                }
               else if ((accMap.get(opp.AccountId).LC_Region__c == 'North America')&&(accMap.get(opp.AccountId).Type == 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Threes__c);

               value.Threes__c+= 1;
                }
               else if ((accMap.get(opp.AccountId).LC_Region__c == 'International')&&(accMap.get(opp.AccountId).Type != 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Eights__c);
    
               value.Eights__c+= 1;
               }
               else if ((accMap.get(opp.AccountId).LC_Region__c == 'International')&&(accMap.get(opp.AccountId).Type == 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Nines__c);
  
                value.Nines__c+= 1;
                }
            update value;
           }
         update accMap.values();
        }
      }            
    }
}

And the test class so far...(The trigger is designed to assign an AccountNumber stored in a custom Counter setting)
@isTest
  Private Class UnitTest_AccountNumberIndex{

static testMethod void LCUnitTest(){

      /*Create Counter*/
      Counter__c Count= new Counter__c();
      Count.Name='Counter'; 
      Count.Ones__c=101000;

      /*Create User/America/Account*/
      Account a1 = new Account();
      a1.name='Test Account1';
      a1.Type= 'Customer-Direct';
      a1.LC_Region__c='North America';
      a1.AccountNumber=null;
      insert a1;
      
      /*Create Opp1*/      
      Opportunity o1=new Opportunity();
      o1.Name='Test Opp1';
      o1.AccountId=a1.Id;
      o1.closeDate=date.today();
      o1.StageName='Perception Analysis';
      o1.Probability=70;
      insert o1;

      o1.StageName='Negotiation/Review';
      o1.Probability=90;
      update o1;

      a1.AccountNumber=String.valueOf(Count.Ones__c);
      update a1;
      System.assertEquals(String.valueOf(Count.Ones__c),a1.AccountNumber);
   
    }
}

Thanks!
Greetings,
I'm new to apex and have been trying to design a trigger that would populate the Account Number field with a value starting at 10000, when the Opportunity Probability moves to 85%. Before I added my 'if' statements, it worked fine, but after that nothing. I even tried writing the trigger on Opportunity and Account objects. 

I created a custom object accNumber__c and custom field Ones__c, where the generated number would be stored. 

Please, please, i need some help on this one. Here is what I have so far:
trigger AccountNumberUpdate on Opportunity(before insert, before update) {
  
                accNumber__c value = new accNumber__c(Name='1',Ones__c=0);
                    for(accNumber__c record:[SELECT Id,Name,Ones__c FROM accNumber__c WHERE Name='1' FOR UPDATE]) {
                      value = record;
  }
  
                 for(Opportunity opps:Trigger.new) {
                        if((opps.Probability>=85)&&(opps.Account.Region__c=='Americas')&&(opps.AccountNumber==null)) {
      opps.Account.AccountNumber ='0'.repeat(math.max(0,0-String.valueOf(value.Ones__c).length()))+String.valueOf(value.Ones__c);
      value.Ones__c+=1;
    }
  }
  update value;
}
The Account object is a lookup on the Opportunity object. Is there another way I can approach this problem? Any help is appreciated.

I have an urgent requirement as follows:

--Whenever the Opportunity Probability is moved to 80%, an Integer should be added to the AccountNumber field on the Account object. There is a lookup relationship between the Opportunity(child) and Account(parent) object.

--The Account number will never be changed by the Trigger; only set once if the AccountNumber field is NULL when the Opportunity Probability gets to 80%.

--The trigger will find the highest number in the appropriate number range and assign a number one higher.

--The number assigned by the trigger will depend on the type of Account(Partner or User) & the region of the Account (Americas or Offshore). as follows:

       If Account = Partner & Region = Americas assign a number between 3000-3999
       If Account = Partner & Region = Offshore assign a number between 9000-9999
       If Account = User & Region = Americas assign a number between 1000-1999
       If Account = User & Region = Offshore assign a number between 8000-8999

Here is what I have so far but i'm stuck with the logic:

trigger AssignAccountNumber on Opportunity (after insert, after update){
   list<opportunity> oppsToUpdate = new list<opportunity>();
   for (Opportunity p:Trigger.new){
     if ((p.Probability >= 80)&&(p.accountnumber==null)){
  //your processing for pre-defined range, and update p
  oppsToUpdate.add(p);
     }
   }
   if(oppsToUpdate.size()>0)update oppsToUpdate;
}

Any direction will be appreciated
I'm working on a requirement as follows: Whenever an Opportunity is created or edited, its custom region picklists (Region__c) should be overwritten with the Account region picklists (Region__c).

Trying to develop a trigger that would satisfy this requirement.

Whenever an Opportunity is created or edited, check to see if any of the custom Region__c picklists are NULL. If any are NULL, overwrite all picklist fields with corresponding data from the Account object.

Here is what I have so far:

trigger UpdateOpptyPicklists on Opportunity(Before Insert, Before Update) {
    for(Opportunity o: Trigger.new){
     Account a = [select id,Region__c,Area__c, Division__c from Account where Id=:o.AccountId];
      
        if(o.Region__c == NULL || o.Area__c == NULL || o.Division__c == NULL){
        
          o.Region__c=a.Region__c;
          o.Area__c = a.Area__c;
          o.Division__c=a.Division__c;
       }
  }
}

One major flaw with my trigger is that I have SOQL running inside a loop. How can I bulkify this trigger?

Trying to get at least 75% coverage on this trigger. Here's what i have so far

My trigger:

trigger UpdateOpptyPicklists on Opportunity(Before Insert, Before Update) {
    for(Opportunity o: Trigger.new){
     Account a = [select id,LC_Region__c,LC_Area__c, LC_Division__c from Account where Id=:o.AccountId];
       
        if(o.LC_Region__c == NULL || o.LC_Area__c == NULL || o.LC_Division__c == NULL){
         
          o.LC_Region__c=a.LC_Region__c;
          o.LC_Area__c = a.LC_Area__c;
          o.LC_Division__c=a.LC_Division__c;
       }
  }
 }
  
The test class:

@isTest
private class UnitTests_UpdateOpptyPicklists {

    static testMethod void myUnitTest() {
      Account a = new Account();
      a.Name='TEST ACCOUNT';
      a.Type='Competitor';
      a.LC_Region__c='Americas';
      a.LC_Area__c='West';
      a.LC_Division__c='MA';
      insert a;
     
      Opportunity o=new Opportunity();
      o.Name='TEST';
      o.AccountId=a.Id;
      o.Type='New Customer';
      o.closeDate=date.today();
      o.StageName='Prospecting';
      o.Amount=10000;
      o.LC_Region__c='Americas';
      o.LC_Area__c='East';
      o.LC_Division__c='SE';
      insert o;
     
      RecordType rt=new RecordType();
      try{
       rt=[SELECT Id from RecordType where sObjectType='Opportunity' and isActive=true limit 1];
      }
      catch(Exception e){
       rt=null;
      } 

      if(o.LC_Region__c == NULL || o.LC_Area__c == NULL || o.LC_Division__c == NULL){
      o.LC_Region__c=a.LC_Region__c;
      o.LC_Area__c=a.LC_Region__c;
      o.LC_Division__c=a.LC_Region__c;
      update o;
      }
}    
}

Could someone enlighten me why I'm I getting only 50% coverage
Hi,
How can I write a trigger that would assign a value from a predefined range to the Account number field when: (1) the Opportunity stage moves to 80% (2) the Account Number field is NULL. The trigger should find the highest number in the predefined number range and assign a number +1. So far this is what i have:

trigger AssignAccountNumber on Opportunity (after update){
   for (Opportunity p:Trigger.old){
     if (p.Probability == 80){
    //Should I insert code here that specifies Account number field == 'NULL'
   }
}
}

Need some ideas on how I would start this off. Thanks
Hello,
I'm new to coding and have been presented with the following task.
Create a trigger that runs each time an account is created or edited that updates a custom account picklist (Cold,Warm,Hot)as follows:
  1) If there are 3 or fewer contacts update to Cold
  2) if there are 4 to 9 contacts update to Warm
  3) if there are 10 or more contacts Hot
I need help with designing the trigger syntax. Thanks
How can I via apex automatically @mention the case owner or case contact on the case feed in chatter? 
Using the code example in the developer's guide, here's my class:
public with sharing class AtMentionsUtility {  

    public static void mentionedUser(){           
        
        Case c = new Case();
        ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
        ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
        ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
        ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();

        messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();

        mentionSegmentInput.id = c.OwnerId;
        messageBodyInput.messageSegments.add(mentionSegmentInput);

        textSegmentInput.text = '';
        messageBodyInput.messageSegments.add(textSegmentInput);

        feedItemInput.body = messageBodyInput;
        feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
        feedItemInput.subjectId = c.Id;

        ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput, null);
    }
}

 
I am trying to copy multi-select picklist values into a Long Text Area field. The issue I am running into is I'm able to copy over a single value, but when multiple values are selected it throws an error.
User-added image
How can I split the String value so that the selection is copied into the Long Text Area with line breaks as follows:
Germany
Kentucky

Here's my code:
public class updateMultiSelectPicklistField {
    public static void updateMSelectPickField (ContentVersion[] ContentVersion1){
        for(ContentVersion c: ContentVersion1){        
            c.Main_Offices__c = c.Office__c;  
        }
    }
}
and trigger:
trigger updatefields on ContentVersion (before insert, before update) {
    ContentVersion[] ContentVersion1 = Trigger.new;
    updateMultiSelectPicklistField.updateMSelectPickField(ContentVersion1);
}


 
Hely yall,
We have a custom VF QuoteLineItem page that automatically calculates Total price based on Discount and Unit Price entered. Is there a way to lock down the UnitPrice  field so that it's only editable by certain profiles? It's an editable apex:inputField. I've tried using an outputField, which displays the UnitPrice but can no longer calculate the Total price. Here's a screenshot and code snippet.User-added image
<apex:inputField value="{!item.Item.UnitPrice}" rendered="{!IF(($Profile.Name =='System Administrator'), true , false)}"/>


 
I've written a trigger that updates some fields on the Opportunity Product object with Product values when the Opportunity reaches 95% probability.
The trigger works when I edit and save the OpportunityLineItem but does not update if I just change the Opportunity stage to 95%.
What adjustments do i need to make so that the fields are updated as soon as the Opportunity reaches 95%?
trigger OppProductNetValue on OpportunityLineItem (before insert, before update) {
 
  Map<Id,Opportunity> parentopps = new Map<Id, Opportunity>();

  Set<Id> pbeIds = new Set<Id>();
  
     for(OpportunityLineItem oli : trigger.new) {
        if(oli.PriceBookEntryId != null){
            pbeIds.add(oli.PriceBookEntryId);
            parentopps.put(oli.OpportunityId,null);
       }
    }
    Map<id, PriceBookEntry> pbeMap = new Map<id, PriceBookEntry>(
          [SELECT id, Product2.id, Product2.True_Price__c
         FROM PriceBookEntry WHERE id in :pbeIds]);
    parentopps.putall([select Id, Probability, Order__c from Opportunity where Id in :parentopps.keyset()]);
    
     for(OpportunityLineItem oli : trigger.new) {
        if((pbeMap.containsKey(oli.PriceBookEntryId))&&(parentopps.get(oli.OpportunityId).Order__c == 'Sales Line')&&(parentopps.get(oli.OpportunityId).Probability == 95)){
           oli.Net_Value__c = pbeMap.get(oli.PriceBookEntryId).Product2.True_Price__c*oli.Quantity;      
      }else{
           oli.Net_Value__c = (1-oli.Discount*.01)*(oli.Quantity)*(oli.UnitPrice);
   }  
  }
}

 
I am trying to create a custom button on the Quote page that creates a Sales Request record when clicked.
The Sales Request is a child object and has a lookup to Quote & Opportunity fields.
I keep getting this error: 'Cannot set property 'Id' of undefined'
Any direction would be appreciated. Here's what I have so far:

 
{!REQUIRESCRIPT('/soap/ajax/30.0/connection.js')}

var srq = new sforce.SObject("Sales_Request__c");
  srq.Id = "{!Sales_Request__c.Id}";
  srq.Quote__r.Id = "{!Quote.Id}";
  srq.Quote__r.OpportunityId = "{!Opportunity.Id}";
  srq.Status_c = "New";
  srq.Type__c = "New";
 
  var result = sforce.connection.create([srq]);
    
   if(result[0].getBoolean("success")){
   window.location = "/" + result[0].id + "/e";
    }else{
    alert('Could not create record '+result);
}


I'm trying to write a test class for the following trigger, but I'm only covering 28% of the lines. How can I edit it to cover the 4 if/else conditions?

My Trigger:
 
trigger AccountNumberIndex on Opportunity(before insert,before update){
    
    List<Id> accIds = new List<Id>();
    
    for(Opportunity opp:trigger.new){

        if(opp.AccountId!=null){

            accIds.add(opp.AccountId);
           }
       }
    
       Map<Id,Account> accMap = new Map<Id,Account>([select id,LC_Region__c,AccountNumber,Type 
                                                     from Account where id in:accIds]);
        
       Counterr__c value = new Counterr__c();
                    
       for(Counterr__c record:[SELECT Id,Ones__c,Threes__c,Eights__c,Nines__c FROM Counterr__c FOR UPDATE]) {
                      
       value = record;

     for(Opportunity opp :trigger.new){
        
         if(!accMap.IsEmpty()){
    
            if((opp.Probability == 90) && (accMap.get(opp.AccountId).AccountNumber == null)){
            
              if((accMap.get(opp.AccountId).LC_Region__c == 'North America')&&(accMap.get(opp.AccountId).Type != 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Ones__c);
      
                value.Ones__c+= 1;
                }
               else if ((accMap.get(opp.AccountId).LC_Region__c == 'North America')&&(accMap.get(opp.AccountId).Type == 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Threes__c);

               value.Threes__c+= 1;
                }
               else if ((accMap.get(opp.AccountId).LC_Region__c == 'International')&&(accMap.get(opp.AccountId).Type != 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Eights__c);
    
               value.Eights__c+= 1;
               }
               else if ((accMap.get(opp.AccountId).LC_Region__c == 'International')&&(accMap.get(opp.AccountId).Type == 'Prospect')){

                accMap.get(opp.AccountId).AccountNumber = String.valueOf(value.Nines__c);
  
                value.Nines__c+= 1;
                }
            update value;
           }
         update accMap.values();
        }
      }            
    }
}

And the test class so far...(The trigger is designed to assign an AccountNumber stored in a custom Counter setting)
@isTest
  Private Class UnitTest_AccountNumberIndex{

static testMethod void LCUnitTest(){

      /*Create Counter*/
      Counter__c Count= new Counter__c();
      Count.Name='Counter'; 
      Count.Ones__c=101000;

      /*Create User/America/Account*/
      Account a1 = new Account();
      a1.name='Test Account1';
      a1.Type= 'Customer-Direct';
      a1.LC_Region__c='North America';
      a1.AccountNumber=null;
      insert a1;
      
      /*Create Opp1*/      
      Opportunity o1=new Opportunity();
      o1.Name='Test Opp1';
      o1.AccountId=a1.Id;
      o1.closeDate=date.today();
      o1.StageName='Perception Analysis';
      o1.Probability=70;
      insert o1;

      o1.StageName='Negotiation/Review';
      o1.Probability=90;
      update o1;

      a1.AccountNumber=String.valueOf(Count.Ones__c);
      update a1;
      System.assertEquals(String.valueOf(Count.Ones__c),a1.AccountNumber);
   
    }
}

Thanks!
Greetings,
I'm new to apex and have been trying to design a trigger that would populate the Account Number field with a value starting at 10000, when the Opportunity Probability moves to 85%. Before I added my 'if' statements, it worked fine, but after that nothing. I even tried writing the trigger on Opportunity and Account objects. 

I created a custom object accNumber__c and custom field Ones__c, where the generated number would be stored. 

Please, please, i need some help on this one. Here is what I have so far:
trigger AccountNumberUpdate on Opportunity(before insert, before update) {
  
                accNumber__c value = new accNumber__c(Name='1',Ones__c=0);
                    for(accNumber__c record:[SELECT Id,Name,Ones__c FROM accNumber__c WHERE Name='1' FOR UPDATE]) {
                      value = record;
  }
  
                 for(Opportunity opps:Trigger.new) {
                        if((opps.Probability>=85)&&(opps.Account.Region__c=='Americas')&&(opps.AccountNumber==null)) {
      opps.Account.AccountNumber ='0'.repeat(math.max(0,0-String.valueOf(value.Ones__c).length()))+String.valueOf(value.Ones__c);
      value.Ones__c+=1;
    }
  }
  update value;
}
The Account object is a lookup on the Opportunity object. Is there another way I can approach this problem? Any help is appreciated.

I'm working on a requirement as follows: Whenever an Opportunity is created or edited, its custom region picklists (Region__c) should be overwritten with the Account region picklists (Region__c).

Trying to develop a trigger that would satisfy this requirement.

Whenever an Opportunity is created or edited, check to see if any of the custom Region__c picklists are NULL. If any are NULL, overwrite all picklist fields with corresponding data from the Account object.

Here is what I have so far:

trigger UpdateOpptyPicklists on Opportunity(Before Insert, Before Update) {
    for(Opportunity o: Trigger.new){
     Account a = [select id,Region__c,Area__c, Division__c from Account where Id=:o.AccountId];
      
        if(o.Region__c == NULL || o.Area__c == NULL || o.Division__c == NULL){
        
          o.Region__c=a.Region__c;
          o.Area__c = a.Area__c;
          o.Division__c=a.Division__c;
       }
  }
}

One major flaw with my trigger is that I have SOQL running inside a loop. How can I bulkify this trigger?

Trying to get at least 75% coverage on this trigger. Here's what i have so far

My trigger:

trigger UpdateOpptyPicklists on Opportunity(Before Insert, Before Update) {
    for(Opportunity o: Trigger.new){
     Account a = [select id,LC_Region__c,LC_Area__c, LC_Division__c from Account where Id=:o.AccountId];
       
        if(o.LC_Region__c == NULL || o.LC_Area__c == NULL || o.LC_Division__c == NULL){
         
          o.LC_Region__c=a.LC_Region__c;
          o.LC_Area__c = a.LC_Area__c;
          o.LC_Division__c=a.LC_Division__c;
       }
  }
 }
  
The test class:

@isTest
private class UnitTests_UpdateOpptyPicklists {

    static testMethod void myUnitTest() {
      Account a = new Account();
      a.Name='TEST ACCOUNT';
      a.Type='Competitor';
      a.LC_Region__c='Americas';
      a.LC_Area__c='West';
      a.LC_Division__c='MA';
      insert a;
     
      Opportunity o=new Opportunity();
      o.Name='TEST';
      o.AccountId=a.Id;
      o.Type='New Customer';
      o.closeDate=date.today();
      o.StageName='Prospecting';
      o.Amount=10000;
      o.LC_Region__c='Americas';
      o.LC_Area__c='East';
      o.LC_Division__c='SE';
      insert o;
     
      RecordType rt=new RecordType();
      try{
       rt=[SELECT Id from RecordType where sObjectType='Opportunity' and isActive=true limit 1];
      }
      catch(Exception e){
       rt=null;
      } 

      if(o.LC_Region__c == NULL || o.LC_Area__c == NULL || o.LC_Division__c == NULL){
      o.LC_Region__c=a.LC_Region__c;
      o.LC_Area__c=a.LC_Region__c;
      o.LC_Division__c=a.LC_Region__c;
      update o;
      }
}    
}

Could someone enlighten me why I'm I getting only 50% coverage
Hi,
How can I write a trigger that would assign a value from a predefined range to the Account number field when: (1) the Opportunity stage moves to 80% (2) the Account Number field is NULL. The trigger should find the highest number in the predefined number range and assign a number +1. So far this is what i have:

trigger AssignAccountNumber on Opportunity (after update){
   for (Opportunity p:Trigger.old){
     if (p.Probability == 80){
    //Should I insert code here that specifies Account number field == 'NULL'
   }
}
}

Need some ideas on how I would start this off. Thanks