• BerettaJon
  • NEWBIE
  • 25 Points
  • Member since 2011

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 18
    Questions
  • 27
    Replies

Hi SF peoples,

 

Here's what I have been challenged with.  My team has a public facing website/form that when filled out will automatically generate a lead inside my org.  I want the people filling out the site/form to enter their SF credentials (username,password,securitytoken) so that we can set up some API access.

 

Is there anyway that I can validate the given user credentials and perform a query from within my org using a trigger on the Lead or something similar?  I want to be able to get the email entered in their salesforce org for that specific set of credentials.

 

Im not really aware of any cross org stuff, another developer is the one diving into the API stuff, Im more of the Triggers and VisualForce guy... Could someone point me in the right direction or let me know if this is impossible?

 

.001 BTC reward for good info :)

Hi internet,

 

I have a pretty simple query in a User Trigger that is supposed to determine all records in a custom object that are owned by the Users being updated in the Trigger.

 

 [select CreatedByID from CustomObject__c where CreatedByID in :Trigger.newMap.keyset()]

 

CustomObject__c has over 140,000 rows.  Trigger.newMap.keyset().size = 1.

 

Interestingly I am able to manually run this query through the developer console and it returns 0 rows (rather quickly too...)

 

What is the correct way to query a large table?  

 

Note I am aware that I cannot return more than 50,000 rows in a query but I do not expect this query to return more than a couple dozen ever.

 

Full error:

Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times

 

 

EDIT

Im doing some more research and found this

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_VLSQ.htm

 

  • The following fields are indexed by default: primary keys (Id, Name and Owner fields), foreign keys (lookup or master-detail relationship fields), audit dates (such as LastModifiedDate), and custom fields marked as External ID or Unique.

The CreatedByID is the owner field of my custom object so according to SF docs my query should be fine??

I wrote a trigger on Opportunity that takes values from custom fields and makes them into the primaryContactRole for the Opporunity being created or updated.

 

This is working well but I relized that if a user went down into the OpporutnityConactRoles list view, they would be able to change the primary contact and my custom fields that drive the trigger would be left un updated.

 

If there anyway that I can monitor changes made to the OpportunityContactRole list and fire updates based off this?

 

A solution that doesnt require visualforce gets bonus points!

Thanks!

Hi folks,

 

Today I come to you looking for some help understanding how to bulkify a trigger.  I currently have this code.

 

if(Trigger.isUpdate)
{
Projection_Multi_Year__c testObj = Trigger.new[0];
List<Projection_Multi_Year__c> checkForDups = new List <Projection_Multi_Year__c>([select id from Projection_Multi_Year__c where
account__c = :testObj.account__c and ownerID = :testObj.ownerID]);
if(checkForDups.size() != 0)
{
trigger.new[0].addError('Update dupe error');
}
else
{
String profileID = UserInfo.getProfileID();
String profileName = [Select name from Profile where ID = :profileID].name;
for(Projection_Multi_Year__c obj : Trigger.New)
{

String accountName = [select name from Account where ID = :obj.Account__c].name;
User ownerObj = [select ID,name,LHH_Zone__c,Region__c,ManagerID from User where ID = :obj.ownerID];
String ownerName = [select name from User where ID = :obj.ownerID].name;
String managerName = [select name from USER where ID = :ownerObj.ManagerID].name;
System.debug('obj.CreatedBy.name = ' + old.CreatedBy.Name);
System.debug('obj.CreatedBy = ' + old.CreatedByID);
obj.Projection_Name__c = accountName + ' - ' + divisionName + ' - ' + ownerObj.name;
//this ^ field has 32,000 some chars. Need to also make a var for a 80 char field
if(accountName.length() > 80)
{
accountName = accountName.substring(0,79);
}

if(ownerName.length() > 80)
{
ownerName = ownerName.substring(0,79);
}
String truncatedName = ownerName + ' - ' + accountName + ' - ' + divisionName;
if(truncatedName.length() > 80)
{
truncatedName = truncatedName.substring(0,79);
}
obj.Name = truncatedName;
obj.Manager__c = managerName;
obj.LHH_Zone__c = ownerObj.LHH_Zone__c;
obj.Country_Region__c = ownerObj.Region__c;

}//end of For

 

So while I understand the basics of my problem I am not sure how to write the solution.  I am going to be sending a bulk upload of thousnads of records at this trigger, so I cant have queries inside of a for loop that will itereate through all the records.

 

Help would be much appriciated on the specifics.

Hi all, thanks for reading.

 

I have a before insert trigger on a custom object.  The trigger should query the User table and grab the Manager record where ID = the custom object's owner.managerID.

 

 List <User> userList = [select name from USER where ID = :ownerObj.ManagerID limit 1];
               if(userList.size() == 0 || userList == null)
               {
                   trigger.new[0].addError('No manager was found for the user attempting to own a Projection.  Please fill in the manager field for this user before   creating a Projection for them.');
               }
               String managerName = userList[0].name;

 

I thought my if statement would prevent String managerName = userList[0].name from ever blowing up but I am getting the list has no rows for assignment on that line and not seeing my error message inside the IF.

 

What gives? 0.1 BTC reward if you are interested. Thanks again.

Hi devs!

 

VF page uses 

<apex:repeat value="{!optionRows}" var="opRow">

To display info.  To be honest I am not sure what/where/how this opRow object is populated.

Nevertheless the opRow var here contains a field that is the same as a Product name.

 

I am trying to return a feild off of the Product record that is related to the opRow var by product name(as you can see in the SOQL in the apex).

 

Here are some code snippets showing how I tried to do this.  The code below is most defiantly not correct and may or may not be helpful.  Please let me know if any additonal info is required in order to help me.  

 

The person who provides an answer will be eligible for a 0.01 BTC reward if you are interested :)

 

 

<APEX CODE>

public OptionRow2 OpRow{get;set;}
    public Product2 getProductFromOpRow()
    {
        
            if(OpRow.dropdownname == null)
            {
                myProduct = [select Product_Image_URL__c from Product2 where name = :OpRow.CheckBoxName];
            }
            if(OpRow.CheckBoxName == null)
            {
                myProduct = [select Product_Image_URL__c from Product2 where name = :OpRow.dropdownname];    
            }
            return myProduct;
       
    }

</APEX CODE>

 

 

<VF CODE>

<div class="image">
<apex:repeat value="{!ProductFromOpRow}" var="opRowP">
<apex:image url="!opRowP.Product_Image_URL__c " rendered=
"{! if(opRowP.Product_Image_URL__c != null && opRow.isDropDown == false,true,false)}" /> </apex:repeat> </div>

 

 

</VF CODE>

 

 

Hi all,

 

Also posted this in Schema Development, if there is a better sub forums please let me know :)

 

I am wondering what is the best way to test how my data set will be effected by the changes I want to make.  I want to remove a custom object that is currently tied to many other objects with restrictive master-detail relationships.  I have made a sandbox to test my new code, but I am not sure how to test what changes will be made to my data set.  I dont believe a full sandbox is an option, and I am not confident in my abilities to make a good enough set of dummy data to test all possible issues.

 

Thanks!

Hi all,

 

I am wondering what is the best way to test how my data set will be effected by the changes I want to make.  I want to remove a custom object that is currently tied to many other objects with restrictive master-detail relationships.  I have made a sandbox to test my new code, but I am not sure how to test what changes will be made to my data set.  I dont believe a full sandbox is an option, and I am not confident in my abilities to make a good enough set of dummy data to test all possible issues.

 

Thanks!

trigger TimestampFields on Survey__c (before update, before insert)
{
for (Survey__c c : Trigger.new)
{
Survey__c oldSurvey = Trigger.oldMap.get(c.ID);

if (c.Field1__c != oldSurvey.Field1__c) {
String new1 = c.Field1__c;
String old1 = oldSurvey.Field1__c;

String newStuff1 = old1.difference(new1);

 

Error: Compile Error: Method does not exist or incorrect signature: [String].difference(String)

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm

I have an empty visual force page on my Account records.  This visualforce page has 

extensions="AccountRollUpController" action="{!getCounts}">

and the apex that it is calling looks like 

public void getCounts()
    {
        this.account.of_Contacts__c = getintNumberOfContacts();
        this.account.of_Open_Activities__c = getintNumberOfOpenActivities();
        this.account.of_Closed_Activities__c = getintNumberOfClosedActivities();
        update this.account;   
    }



The problem is that this code seems to be run after the Account Record is loaded. For instance, the very first time I view and account record the 3 fields above are blank, if I refresh the page the correct values appear. I also have a problem when, from the account record, a user chooses to add a contact, when they are returned to the account record the count of contacts isnt correct until the account record is refreshed.

Help? :)

I have an empty visual force page on my Account records.  This visualforce page has 

extensions="AccountRollUpController" action="{!getCounts}">

and the apex that it is calling looks like 

public void getCounts()
    {
        this.account.of_Contacts__c = getintNumberOfContacts();
        this.account.of_Open_Activities__c = getintNumberOfOpenActivities();
        this.account.of_Closed_Activities__c = getintNumberOfClosedActivities();
        update this.account;   
    }



The problem is that this code seems to be run after the Account Record is loaded. For instance, the very first time I view and account record the 3 fields above are blank, if I refresh the page the correct values appear. I also have a problem when, from the account record, a user chooses to add a contact, when they are returned to the account record the count of contacts isnt correct until the account record is refreshed.

Help? :)



Could someone point me to or write an example of a test class for a OpportunityProductLineItem?  If this was a trigger on an object like Account I would just create Account a = new account and insert a but a OpportunityProductLineItem is dependent on the Opportunity ,Pricebookentry, pricebook2, product2 and more...  I tried to create the test class by instansiating all of those objects but I was still unable to find/set every required field.

 

Trigger class

trigger OpportunityModelNameTrigger on OpportunityLineItem (after insert, after update, after delete) {

OpportunityModelNameTriggerHandler handler = new OpportunityModelNameTriggerHandler();

if(Trigger.isInsert && Trigger.isAfter) {
handler.OnAfterInsert(Trigger.new);

} else if(Trigger.isUpdate && Trigger.isAfter) {
handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.oldMap, Trigger.newMap);

}
else if (Trigger.isDelete)
{
handler.OnAfterDelete(Trigger.old,Trigger.oldMap);
}

}

 

Handler Class : 

public with sharing class OpportunityModelNameTriggerHandler {

// update the Opportunity Model field when new records are inserted from trigger
public void OnAfterInsert(List<OpportunityLineItem> newRecords){
updateOpportunity(newRecords);
}

// update the Opportunity Model when records are updated from trigger
public void OnAfterUpdate(List<OpportunityLineItem> oldRecords,
List<OpportunityLineItem> updatedRecords, Map<ID, OpportunityLineItem> oldMap,
Map<ID, OpportunityLineItem> newMap){
updateOpportunity(updatedRecords);
}
public void OnAfterDelete(List<OpportunityLineItem> oldRecords,Map<ID,OpportunityLineItem> oldMap)
{
updateOpportunityAfterDelete(oldRecords);
}
private void updateOpportunityAfterDelete(List<OpportunityLineItem> oldRecords)
{
Set<Id> CurrentOppId = new Set<Id>();
for (OpportunityLineItem OppLnItem : oldRecords){
CurrentOppId.add(OppLnItem.OpportunityId);
}
List<Opportunity> OppId =
[Select o.Id from Opportunity o
where o.Id in: CurrentOppId];

List<OpportunityLineItem> relatedOLIs =
[Select oli.Id, PricebookEntry.Product2.name, PricebookEntry.Product2.Option_Category__c from OpportunityLineItem oli
where oli.OpportunityId in: CurrentOppId];

if(relatedOLIs.size() != 0)
{
for (Opportunity opp2 : OppId){

for (OpportunityLineItem oli : relatedOLIs){
if(oli.PricebookEntry.Product2.Option_Category__c == 'Model')
{
opp2.model__c = oli.PricebookEntry.Product2.name;
}
}
}
}
else
{
for (Opportunity opp2 : OppId)
{
opp2.model__c = '';
}
}

update OppID;

}
private void updateOpportunity(List<OpportunityLineItem> newRecords)
{
Set<Id> CurrentOppId = new Set<Id>();
for (OpportunityLineItem OppLnItem : newRecords){
CurrentOppId.add(OppLnItem.OpportunityId);
}

// Create List of One Opportunity Id to Update
List<Opportunity> OppId =
[Select o.Id from Opportunity o
where o.Id in: CurrentOppId];

 

List<OpportunityLineItem> relatedOLIs =
[Select oli.Id, PricebookEntry.Product2.name, PricebookEntry.Product2.Option_Category__c from OpportunityLineItem oli
where oli.OpportunityId in: CurrentOppId];


for (Opportunity opp2 : OppId){

for (OpportunityLineItem oli : relatedOLIs){
if(oli.PricebookEntry.Product2.Option_Category__c == 'Model')
{
opp2.model__c = oli.PricebookEntry.Product2.name;
}
}
}
update OppID;

}

}

I wrote a trigger on OpportunityProductLineItem and now I am trying to write a test for it.  My understanding is that I need to instanciate an OpportunityProductLineItem that will set off the trigger.  My confusion comes when I try to make ... 

 

OpportunityProductLineItem opi = new OpportunityProductLineItem();

 

I get errors saying I do not have the required field OpportunityId.  How/Where am I supposed to get an OpporutnityID from?

private void updateOpportunity(List<OpportunityLineItem> newRecords) {

// create a new map to hold the
Map<ID,String> productNames = new Map<ID,String>();
List<Opportunity> opps;
List<Product2> prods;
Map<ID,Opportunity> opportunities = new Map<ID,Opportunity>();
Map<ID,PriceBookEntry> pbIDs = new Map<ID,PriceBookEntry>();
Map<ID,Product2> products = new Map<ID,Product2>();


for (OpportunityLineItem oli : newRecords) {
opportunities.put(oli.id,oli.Opportunity);
pbIDs.put(oli.id,oli.pricebookentry);

}
prods = [select name from Product2 where id IN :pbIDs.keyset()];
opps = [select id from Opportunity where id IN :opportunities.keyset()];

for(Product2 prod : prods)
{
// it seems like I never enter this loop
for (Opportunity opp : opps)
{
if(prod.Option_Category__c == 'Model')
{
opp.model__c = prod.name;
}
}
}

// commit the records
update opps;

}

}

I am trying to set up a trigger.  Opportunity has Opportunity Products which are just Products with a relationship to an opportunity.  When a custom field on Product is set a certain way I would like to update a custom field on the opportunity record to say the Product name.  I am having trouble figuring out where to place the trigger and how to write the handler class. 

Hi all,

 

I am trying to build a VisualForce page that would check certain fields for data validity before inserting.  I believe I want to use a validation rule for this.

 

How am I able to mimic the standard functionality of a validation error message appearing below the associated field?

 

Currently the insert statement in my apex controller throws a DML error referencing the validation rule I have set up for the first field that needs one.  This error does not go underneath the field as I told it to do in the validation rule, it redirects to a seemingly new page that is 100% comprised of the DML error.  How can I handle this properly, or rather make it behave like the standard intended functionality?

 

Thanks

I have a salesforce page that creates "Projects".  On the projects page I have included a checkbox.  I would like to have a document open up in a second window for editing if the checkbox is selected at the time of saving the new project.

 

Is this possible?  Would it be done in an Apex trigger?  I am very new to salesforce development so please excuse any missing information and jsut ask me for more details if nessesary.

 

Thanks

Hi all,

 

I am trying to build the starter "Recruting Applicaiton" and I am getting this error on my formula.

 

Incorrect parameter for function 'and()'. Expected Boolean, received Text

 

Location__r.City__c && ', ' && Location__r.State_Province__c && ' - ' && Location__r.Country__c

 

I believe I followed the instructions to a T and the mistake is not jumping out at me.  Help?

 

 

Hi SF peoples,

 

Here's what I have been challenged with.  My team has a public facing website/form that when filled out will automatically generate a lead inside my org.  I want the people filling out the site/form to enter their SF credentials (username,password,securitytoken) so that we can set up some API access.

 

Is there anyway that I can validate the given user credentials and perform a query from within my org using a trigger on the Lead or something similar?  I want to be able to get the email entered in their salesforce org for that specific set of credentials.

 

Im not really aware of any cross org stuff, another developer is the one diving into the API stuff, Im more of the Triggers and VisualForce guy... Could someone point me in the right direction or let me know if this is impossible?

 

.001 BTC reward for good info :)

Hi internet,

 

I have a pretty simple query in a User Trigger that is supposed to determine all records in a custom object that are owned by the Users being updated in the Trigger.

 

 [select CreatedByID from CustomObject__c where CreatedByID in :Trigger.newMap.keyset()]

 

CustomObject__c has over 140,000 rows.  Trigger.newMap.keyset().size = 1.

 

Interestingly I am able to manually run this query through the developer console and it returns 0 rows (rather quickly too...)

 

What is the correct way to query a large table?  

 

Note I am aware that I cannot return more than 50,000 rows in a query but I do not expect this query to return more than a couple dozen ever.

 

Full error:

Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times

 

 

EDIT

Im doing some more research and found this

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_VLSQ.htm

 

  • The following fields are indexed by default: primary keys (Id, Name and Owner fields), foreign keys (lookup or master-detail relationship fields), audit dates (such as LastModifiedDate), and custom fields marked as External ID or Unique.

The CreatedByID is the owner field of my custom object so according to SF docs my query should be fine??

Hi folks,

 

Today I come to you looking for some help understanding how to bulkify a trigger.  I currently have this code.

 

if(Trigger.isUpdate)
{
Projection_Multi_Year__c testObj = Trigger.new[0];
List<Projection_Multi_Year__c> checkForDups = new List <Projection_Multi_Year__c>([select id from Projection_Multi_Year__c where
account__c = :testObj.account__c and ownerID = :testObj.ownerID]);
if(checkForDups.size() != 0)
{
trigger.new[0].addError('Update dupe error');
}
else
{
String profileID = UserInfo.getProfileID();
String profileName = [Select name from Profile where ID = :profileID].name;
for(Projection_Multi_Year__c obj : Trigger.New)
{

String accountName = [select name from Account where ID = :obj.Account__c].name;
User ownerObj = [select ID,name,LHH_Zone__c,Region__c,ManagerID from User where ID = :obj.ownerID];
String ownerName = [select name from User where ID = :obj.ownerID].name;
String managerName = [select name from USER where ID = :ownerObj.ManagerID].name;
System.debug('obj.CreatedBy.name = ' + old.CreatedBy.Name);
System.debug('obj.CreatedBy = ' + old.CreatedByID);
obj.Projection_Name__c = accountName + ' - ' + divisionName + ' - ' + ownerObj.name;
//this ^ field has 32,000 some chars. Need to also make a var for a 80 char field
if(accountName.length() > 80)
{
accountName = accountName.substring(0,79);
}

if(ownerName.length() > 80)
{
ownerName = ownerName.substring(0,79);
}
String truncatedName = ownerName + ' - ' + accountName + ' - ' + divisionName;
if(truncatedName.length() > 80)
{
truncatedName = truncatedName.substring(0,79);
}
obj.Name = truncatedName;
obj.Manager__c = managerName;
obj.LHH_Zone__c = ownerObj.LHH_Zone__c;
obj.Country_Region__c = ownerObj.Region__c;

}//end of For

 

So while I understand the basics of my problem I am not sure how to write the solution.  I am going to be sending a bulk upload of thousnads of records at this trigger, so I cant have queries inside of a for loop that will itereate through all the records.

 

Help would be much appriciated on the specifics.

Hi all, thanks for reading.

 

I have a before insert trigger on a custom object.  The trigger should query the User table and grab the Manager record where ID = the custom object's owner.managerID.

 

 List <User> userList = [select name from USER where ID = :ownerObj.ManagerID limit 1];
               if(userList.size() == 0 || userList == null)
               {
                   trigger.new[0].addError('No manager was found for the user attempting to own a Projection.  Please fill in the manager field for this user before   creating a Projection for them.');
               }
               String managerName = userList[0].name;

 

I thought my if statement would prevent String managerName = userList[0].name from ever blowing up but I am getting the list has no rows for assignment on that line and not seeing my error message inside the IF.

 

What gives? 0.1 BTC reward if you are interested. Thanks again.

Hi devs!

 

VF page uses 

<apex:repeat value="{!optionRows}" var="opRow">

To display info.  To be honest I am not sure what/where/how this opRow object is populated.

Nevertheless the opRow var here contains a field that is the same as a Product name.

 

I am trying to return a feild off of the Product record that is related to the opRow var by product name(as you can see in the SOQL in the apex).

 

Here are some code snippets showing how I tried to do this.  The code below is most defiantly not correct and may or may not be helpful.  Please let me know if any additonal info is required in order to help me.  

 

The person who provides an answer will be eligible for a 0.01 BTC reward if you are interested :)

 

 

<APEX CODE>

public OptionRow2 OpRow{get;set;}
    public Product2 getProductFromOpRow()
    {
        
            if(OpRow.dropdownname == null)
            {
                myProduct = [select Product_Image_URL__c from Product2 where name = :OpRow.CheckBoxName];
            }
            if(OpRow.CheckBoxName == null)
            {
                myProduct = [select Product_Image_URL__c from Product2 where name = :OpRow.dropdownname];    
            }
            return myProduct;
       
    }

</APEX CODE>

 

 

<VF CODE>

<div class="image">
<apex:repeat value="{!ProductFromOpRow}" var="opRowP">
<apex:image url="!opRowP.Product_Image_URL__c " rendered=
"{! if(opRowP.Product_Image_URL__c != null && opRow.isDropDown == false,true,false)}" /> </apex:repeat> </div>

 

 

</VF CODE>

 

 

I have an empty visual force page on my Account records.  This visualforce page has 

extensions="AccountRollUpController" action="{!getCounts}">

and the apex that it is calling looks like 

public void getCounts()
    {
        this.account.of_Contacts__c = getintNumberOfContacts();
        this.account.of_Open_Activities__c = getintNumberOfOpenActivities();
        this.account.of_Closed_Activities__c = getintNumberOfClosedActivities();
        update this.account;   
    }



The problem is that this code seems to be run after the Account Record is loaded. For instance, the very first time I view and account record the 3 fields above are blank, if I refresh the page the correct values appear. I also have a problem when, from the account record, a user chooses to add a contact, when they are returned to the account record the count of contacts isnt correct until the account record is refreshed.

Help? :)

I have an empty visual force page on my Account records.  This visualforce page has 

extensions="AccountRollUpController" action="{!getCounts}">

and the apex that it is calling looks like 

public void getCounts()
    {
        this.account.of_Contacts__c = getintNumberOfContacts();
        this.account.of_Open_Activities__c = getintNumberOfOpenActivities();
        this.account.of_Closed_Activities__c = getintNumberOfClosedActivities();
        update this.account;   
    }



The problem is that this code seems to be run after the Account Record is loaded. For instance, the very first time I view and account record the 3 fields above are blank, if I refresh the page the correct values appear. I also have a problem when, from the account record, a user chooses to add a contact, when they are returned to the account record the count of contacts isnt correct until the account record is refreshed.

Help? :)



Could someone point me to or write an example of a test class for a OpportunityProductLineItem?  If this was a trigger on an object like Account I would just create Account a = new account and insert a but a OpportunityProductLineItem is dependent on the Opportunity ,Pricebookentry, pricebook2, product2 and more...  I tried to create the test class by instansiating all of those objects but I was still unable to find/set every required field.

 

Trigger class

trigger OpportunityModelNameTrigger on OpportunityLineItem (after insert, after update, after delete) {

OpportunityModelNameTriggerHandler handler = new OpportunityModelNameTriggerHandler();

if(Trigger.isInsert && Trigger.isAfter) {
handler.OnAfterInsert(Trigger.new);

} else if(Trigger.isUpdate && Trigger.isAfter) {
handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.oldMap, Trigger.newMap);

}
else if (Trigger.isDelete)
{
handler.OnAfterDelete(Trigger.old,Trigger.oldMap);
}

}

 

Handler Class : 

public with sharing class OpportunityModelNameTriggerHandler {

// update the Opportunity Model field when new records are inserted from trigger
public void OnAfterInsert(List<OpportunityLineItem> newRecords){
updateOpportunity(newRecords);
}

// update the Opportunity Model when records are updated from trigger
public void OnAfterUpdate(List<OpportunityLineItem> oldRecords,
List<OpportunityLineItem> updatedRecords, Map<ID, OpportunityLineItem> oldMap,
Map<ID, OpportunityLineItem> newMap){
updateOpportunity(updatedRecords);
}
public void OnAfterDelete(List<OpportunityLineItem> oldRecords,Map<ID,OpportunityLineItem> oldMap)
{
updateOpportunityAfterDelete(oldRecords);
}
private void updateOpportunityAfterDelete(List<OpportunityLineItem> oldRecords)
{
Set<Id> CurrentOppId = new Set<Id>();
for (OpportunityLineItem OppLnItem : oldRecords){
CurrentOppId.add(OppLnItem.OpportunityId);
}
List<Opportunity> OppId =
[Select o.Id from Opportunity o
where o.Id in: CurrentOppId];

List<OpportunityLineItem> relatedOLIs =
[Select oli.Id, PricebookEntry.Product2.name, PricebookEntry.Product2.Option_Category__c from OpportunityLineItem oli
where oli.OpportunityId in: CurrentOppId];

if(relatedOLIs.size() != 0)
{
for (Opportunity opp2 : OppId){

for (OpportunityLineItem oli : relatedOLIs){
if(oli.PricebookEntry.Product2.Option_Category__c == 'Model')
{
opp2.model__c = oli.PricebookEntry.Product2.name;
}
}
}
}
else
{
for (Opportunity opp2 : OppId)
{
opp2.model__c = '';
}
}

update OppID;

}
private void updateOpportunity(List<OpportunityLineItem> newRecords)
{
Set<Id> CurrentOppId = new Set<Id>();
for (OpportunityLineItem OppLnItem : newRecords){
CurrentOppId.add(OppLnItem.OpportunityId);
}

// Create List of One Opportunity Id to Update
List<Opportunity> OppId =
[Select o.Id from Opportunity o
where o.Id in: CurrentOppId];

 

List<OpportunityLineItem> relatedOLIs =
[Select oli.Id, PricebookEntry.Product2.name, PricebookEntry.Product2.Option_Category__c from OpportunityLineItem oli
where oli.OpportunityId in: CurrentOppId];


for (Opportunity opp2 : OppId){

for (OpportunityLineItem oli : relatedOLIs){
if(oli.PricebookEntry.Product2.Option_Category__c == 'Model')
{
opp2.model__c = oli.PricebookEntry.Product2.name;
}
}
}
update OppID;

}

}

When i write a  test class for a trigger the "if condition part of code is getting covered but not the else how to cover the else part."

 

Part of Trigger is 

 for(Patient__c p:Trigger.new)
         {
           if(p.Associate__c!=null) 
           {
               p.Address_1__c = assMap.get(p.Associate__c).Current_Address__c; 
               p.City__c = assMap.get(p.Associate__c).Current_City__c; 
               p.State__c=assMap.get(p.Associate__c).Current_State__c;
               p.Zip__c=assMap.get(p.Associate__c).Current_Zip__c;
               
           }
           else
           {
             p.Address_1__c = ''; 
             p.City__c = ''; 
             p.State__c='';
             p.Zip__c='';
            
           }     //This part is not getting covered with my test class ...please help me //


Test class

 Associate__c aa =new Associate__c(Name='TestAss' ,Associate_ID__c='ASSID', Last_Name__c='AssLName',Current_Address__c='TestAddress',Current_City__c='TestCity',Current_Zip__c='45678',Current_State__c='TX');          
  insert aa;  

 

Patient__c p=new Patient__c(Name='TestUser',Associate__c=aa.id,CID__c='ASSID',Type__c='Agent',Address_1__c='TestAddressStreet',City__c='TestCity',State__c='TX',Zip__c='75423');
         insert p;
         update p;

 

 

 

 

I wrote a trigger on OpportunityProductLineItem and now I am trying to write a test for it.  My understanding is that I need to instanciate an OpportunityProductLineItem that will set off the trigger.  My confusion comes when I try to make ... 

 

OpportunityProductLineItem opi = new OpportunityProductLineItem();

 

I get errors saying I do not have the required field OpportunityId.  How/Where am I supposed to get an OpporutnityID from?

private void updateOpportunity(List<OpportunityLineItem> newRecords) {

// create a new map to hold the
Map<ID,String> productNames = new Map<ID,String>();
List<Opportunity> opps;
List<Product2> prods;
Map<ID,Opportunity> opportunities = new Map<ID,Opportunity>();
Map<ID,PriceBookEntry> pbIDs = new Map<ID,PriceBookEntry>();
Map<ID,Product2> products = new Map<ID,Product2>();


for (OpportunityLineItem oli : newRecords) {
opportunities.put(oli.id,oli.Opportunity);
pbIDs.put(oli.id,oli.pricebookentry);

}
prods = [select name from Product2 where id IN :pbIDs.keyset()];
opps = [select id from Opportunity where id IN :opportunities.keyset()];

for(Product2 prod : prods)
{
// it seems like I never enter this loop
for (Opportunity opp : opps)
{
if(prod.Option_Category__c == 'Model')
{
opp.model__c = prod.name;
}
}
}

// commit the records
update opps;

}

}