• Doug Traster 4
  • NEWBIE
  • 15 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 6
    Replies
Hi all;

I have 3 accounts (name territory update, accounts for territories, and a junction account).  when you update name and terrtiory it posts to the junction.  what I want to have is a trigger that then updates the accounts based on info (state, org code, territorynameid) update the junciton.  Here is what I have so far, please help!

trigger addAcctsToJunc on Territory_Account_Junction__c (after insert, after update) {
    
   Set<string> accountIds = new Set<string>();
    for(Territory_Account_Junction__c taj : trigger.new)
        if(taj.TerritoryNameId__c !=Null)
        accountIds.add(taj.TerritoryNameId__c);
        System.debug('get all of the states ' + accountIds);
        
    
    Map<String,Accts_for_Territories__c> acountMap = new Map<String, Accts_for_Territories__c>([Select Name__c, accountID__c
                                                      FROM Accts_for_Territories__c where TerritoryNameId__c in :accountIds]);
    system.debug('all accounts '  + acountMap);
    
    Account thisAccount;
    
    
    List<Territory_Account_Junction__c> acctTerrRep = new List<Territory_Account_Junction__c>();
    
    //system.debug('get info from list ' + acctTerrRep);
    for(Territory_Account_Junction__c taj : trigger.new)
        
       
    {
        if(taj.Billing_State__c !=NULL)
        {
            
            thisAccount = acctTerrRep.get(taj.TerritoryNameID__c);
            //thisAccount = acctTerrRep.get(taj.)
            
            system.debug('info in This Account ' +thisAccount);
            If(thisAccount != NULL){
                
                if(thisAccount.Name !=Null)
                    acctTerrRep.add(thisAccount.Name);
                
                taj.Account__c = String.join(acctTerrRep, ',');
            }
        }
    }
Hi All;

I have created a trigger that pulls Product names and puts them on the Opportunity so that I can see them in a related list on Account.  

I have a test case that gets me 82%, but want to push it higher in case data or something else changes.

Here is my trigger:
trigger ShowOppProd on Opportunity (before update,before insert) {
 Map<Id,Set<String>> prodToOpp = new Map<Id,Set<String>> ();
    for (Opportunity opp : [SELECT Id, Opportunity_Prod__c, (SELECT Id, OpportunityId, Product2.name
                                                           FROM OpportunityLineItems)FROM Opportunity 
                            WHERE Opportunity.Id IN: Trigger.new] ) {
         
         Set<String> productsInOpp = new Set<String>();
         for (OpportunityLineItem oli : opp.opportunityLineItems)
             productsInOpp.add(oli.Product2.name);
         
                                if(prodToOpp.containsKey(opp.Id)){
                                 Set<String> uniqueProdset = prodToOpp.get(opp.Id);
                                    uniqueProdset.addAll(productsInOpp);
                                    prodToOpp.put(opp.Id,uniqueProdset);
                                }
                                else
                                  prodToOpp.put(opp.Id,productsInOpp);
                                
                            }
    for (Opportunity o: Trigger.new){
        if(prodToOpp.containsKey(o.Id)){
            String concatProd = '';
            for (String p : prodToOpp.get(o.Id))
                concatProd = concatProd + (concatProd.length() == 0 ? '' : '; ')+ p;
            o.Opportunity_Prod__c = concatProd;
        }
    
}
}

Here is my test case:
@isTest
public class OppProdTest {
    static testMethod void TestOppProd() {
        
        Account a = new Account (
             Name = 'The High School',
             Organization_Type__c = 'High School'
        );
        
        Insert a;
        
        
        Product2 prod = new Product2(Name = 'Bronze',
                                     Family = 'test'
                                    );
        Insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry (
             Pricebook2Id = pricebookId, 
             Product2Id = prod.Id,
             UnitPrice = 500, 
             IsActive = true
        );
        
        Insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(
             Name = 'Custom Pricebook',
             isActive = true
        );
        
        Insert customPB;
        
        
        PriceBookEntry customPrice = new PricebookEntry(
             Pricebook2Id = customPB.Id,
             Product2Id = prod.Id,
             UnitPrice = 350,
             IsActive = true
    
        );
        
        Insert customPrice;
        
     
        Opportunity opp = new Opportunity(
             Account = a,
             Opportunity_Prod__c = prod.Name,
             Name = 'Test Opp',
             StageName = 'Proposal',
             CloseDate = System.today()
        );
        
        Insert opp;     
        
        
        OpportunityLineItem OLI = new OpportunityLineItem(
             PricebookEntryId = standardPrice.Id,
             OpportunityId = opp.Id,
             Quantity = 1,
             TotalPrice = standardPrice.UnitPrice 
         );
        
        Insert OLI;
               
        
       System.assertEquals('Bronze', opp.Opportunity_Prod__c);
                             
                
         }                                   
}

Running the issues I am getting that these lines are not under coverage. I am at a loss on how to add this to the test.  I know I probably need to add another assert somewhere, but cant figure it out.  

                          Set<String> uniqueProdset = prodToOpp.get(opp.Id);
                                    uniqueProdset.addAll(productsInOpp);
                                    prodToOpp.put(opp.Id,uniqueProdset);

Any help would be most appreciated!

Thanks!
Hello

I have a requirement that asks me to show child opportunities and child tasks(activities) on the parent account.  I have created Parent/Child Hierarchy for the accounts.  What they want is anytime a sales person creates an opportunity or a task on a child, they see it in a related list on the parent.

I created 2 lookup fields.  One on Opportunity and one on activity custom fields.  

I then went to Process Builder and used the following:

For Opportunity -- 

Choose Object and Specify When to Start the Process
Object * Opportunity
Start Process* When record is created or edited

Define Criteria for this Action Group
*No criteria- just execute the actions

TRUE >Immediate Actions>Add actions>

Select and Define Action
Action type*Update Records

Record type > Select a record to update* Select the Opportunity record that started your process

Criteria for Updating Records* No criteria- just execute the actions

Set new field values for the records you update***
Field* Parent Account Lookup 
Type* Reference
Value* Account.ParentId

and for TASK --

Choose Object and Specify When to Start the Process
Object * Task
Start Process* When record is created or edited

Define Criteria for this Action Group
*No criteria- just execute the actions

TRUE >Immediate Actions>Add actions>

Select and Define Action
Action type*Update Records

Record type > Select a record to update* Select the Task record that started your process

Criteria for Updating Records* No criteria- just execute the actions

Set new field values for the records you update***
Field* Parent Account Lookup 
Type* Reference
Value* Account.ParentId 

What I am running into is that it works fine for the Opportunity.  They can create an opportunity on a child or the parent account with no problem.   It is when I use the Task it errors.  They cannot create a task on the parent account????  I get a Flow error.

Error element myRule_1_A1 (FlowRecordUpdate).
This error occurred when the flow tried to update records: The flow failed to access the value for myVariable_current.Account.ParentId because it hasn't been set or assigned.. For details, see API Exceptions.

Any ideas why or how I can fix this?

Thanks!!!!

 
Hi

I am trying to get only tasks/activities by children in a Parent/Child hierarchy.  I have created a visual force page to show both open and closed tasks, but I am getting other child accounts not related to the parent.  So If I have Parent account "A", and "B" and "C", which are children to "A" I only want to see B & C.  Right now I am seeing "D", "E" and "F", which related to other Parent Accounts.

Here is query I have in my constructor showing the open tasks:

tasksLimited= [Select id,whoid,whatid,subject,type, Medium_of_Activity__c, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
                   Where Account.ParentID != null And status !='completed' ORDER BY activitydate LIMIT 10];
   system.debug('taskslimited: '+taskslimited);

Any help, I have tried the WhatID, but it gives me an error, not sure how to filter this down!

 
I am having problems getting code coverage increased on my test case.  I see that my extension is account, but I am having issues figuring how to get task included into account.

Here is my class

public class childTaskOnParentCont {
    
    public Account acc {get;set;}
    public List<Task> tasks {get;set;}
    public List<Task> closedTasks {get;set;}
    public List<Task> tasksLimited {get;set;}
    public List<Task> closedTasksLimited {get;set;}
    
    public List<Contact> cons {get;set;}
    
    
    //constructor
    public childTaskOnParentCont(apexpages.StandardController con){
        acc = (Account) con.getRecord();
        cons=[SELECT id from Contact WHERE AccountID=: acc.Id];
         
        
    tasksLimited= [Select whoid,whatid,subject,type, Medium_of_Activity__c, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
                   Where Account.ParentID != null And status !='completed' ORDER BY activitydate LIMIT 10];
   system.debug('taskslimited: '+taskslimited);
        
    closedTasksLimited= [Select whoid,subject,type, Medium_of_Activity__c, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
                   Where Account.ParentID != null And status =:'completed' ORDER BY activitydate LIMIT 10];  
    system.debug('closedTasksLimited: '+closedTasksLimited);   
        
        
    }
    
    //Get the Account Information
public Account getAccount() {
    return [SELECT id,ParentId, name FROM Account WHERE Id=: acc.Id];
}
                
    //Get Open Tasks for Child Tasks
public List<Task> getTasks() {

    tasks= [Select whoid,subject,type, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
            Where Account.ParentID != null And status !='completed' ORDER BY activitydate];
    return tasks;
}

//Get Closed Tasks for Child Tasks
public List<Task> getClosedTasks() {

    closedTasks= [Select whoid,subject,type, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
            Where Account.ParentID != null And status =:'completed' ORDER BY activitydate];
    return closedTasks;
  }
}

Here is my test case

@isTest
public class thecontrollerTests {
    
    public static testMethod void testTaskController() {
       
        Account acc = new Account(Name = 'State College');
        insert acc;
        
        Task tsk = new Task(status = 'Completed');
        insert tsk;
        
        PageReference pageRef = Page.childTaskOnParent;
        Test.setCurrentPage(pageRef);
        ApexPages.StandardController sc = new ApexPages.StandardController(acc);
        childTaskOnParentCont testAccPlan = new childTaskOnParentCont(sc);
    }
}

Any help would be greatly appreciated.
I am trying to modify an existing VF page on Opportunity Line Item.  I need to have user be able to choose discount in either percentage or currency, and  I am trying to use ActionSupport and reRender, but not getting it to work correctly. 

Can someone please help.

Here is the VF
<apex:page standardController="Opportunity" extensions="opportunityPBB” action="{!priceBookCheck}" >
    <apex:sectionHeader Title="Manage {!$ObjectType.Product2.LabelPlural}" subtitle="{!opportunity.Name}"/>
    <apex:messages style="color:red"/>
    <style>
        .search{
            font-size:14pt;
            margin-right: 20px;    
        }
        .fyi{
            color:red;
            font-style:italic;
        }
        .label{
            margin-right:10px;
            font-weight:bold;
        }
    </style>
       <script type='text/javascript'>
    
               var waitTime = 1;
        
    
        var countDown = waitTime+1;
        var started = false;
        
        function resetTimer(){
        
            countDown=waitTime+1;
            
            if(started==false){
                started=true;
                runCountDown();
            }
        }
        
        function runCountDown(){
        
            countDown--;
            
            if(countDown<=0){
                fetchResults();
                started=false;
            }
            else{
                window.setTimeout(runCountDown,1000);
            }
        }
    
    </script>
   
  
    <apex:form >
    
        <apex:outputPanel id="mainBody">
        
            <apex:outputLabel styleClass="label">PriceBook: </apex:outputLabel>
            <apex:outputText value="{!theBook.Name}"/>&nbsp;
            <apex:commandLink action="{!changePricebook}" value="change" immediate="true"/>
            <br/>
 
            <apex:outputPanel rendered="{!multipleCurrencies}">
                <apex:outputLabel styleClass="label">Currency: </apex:outputLabel>
                <apex:outputText value="{!chosenCurrency}"/>
                <br/>
            </apex:outputPanel>
            <br/>

<!-- HERE IS WHERE I AM DOING THE OUTPUT PANEL TO DO THE GREY OUT—>
            
            <apex:outputPanel id="thePanel"> 
                <apex:inputField value="{!s.Discount_Choice__c}"> 
                <apex:actionSupport event="onchange" action="{!doDisable}" rerender="thePanel"/> 
                </apex:inputField> 
                <apex:inputField value="{!s.Discount_Percent__c.}" rendered="{!shouldRender}"/> 
                </apex:outputPanel> 
            



            <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected">
                       
                <apex:pageblockTable value="{!shoppingCart}" var="s">
                
                    <apex:column >
                        <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">

                            <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                        </apex:commandLink>
                    </apex:column>
                    
                    <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>
                    
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                        <apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                    
                   <!-- This should be greyed out if you choose ‘Currency’ above—>
                     <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Discount_Percent__c.Label}">                      
                         <apex:inputField value="{!s.Discount_Percent__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                          </apex:column>

                    <!-- This should be greyed out if you choose ‘Percentage’ above—>
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Discount_Currency__c.Label}">                      
                        <apex:inputField value="{!s.Discount_Currency__c}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                     </apex:column>  
                    
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                        <apex:inputField value="{!s.UnitPrice}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                    </apex:column>
                    
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Description.Label}">
                        <apex:inputField value="{!s.Description}" required="false"/>
                    </apex:column>
                    
                </apex:pageblockTable>
            
            
                <apex:pageBlockButtons >
                    <apex:commandButton action="{!onSave}" value="Save"/>
                    <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
                </apex:pageBlockButtons>
            
            </apex:pageBlock>
            
    
            <apex:pageBlock >
            
                <apex:outputPanel styleClass="search">
                    Search for {!$ObjectType.Product2.LabelPlural}:
                </apex:outputPanel>

                <apex:actionRegion renderRegionOnly="false" immediate="true">
                
                    <apex:actionFunction name="fetchResults" action="{!updateAvailableList}" reRender="searchResults" status="searchStatus"/>
                    
                 
                    <apex:inputText value="{!searchString}" onkeydown="if(event.keyCode==13){this.blur();}else{resetTimer();}" style="width:300px"/>
                    &nbsp;&nbsp;
                    <i>
                    
                        <apex:actionStatus id="searchStatus" startText="searching..." stopText=" "/>
                    </i>
                    
                </apex:actionRegion>
            
                <br/>
                <br/>
            
                <apex:outputPanel id="searchResults">
                
                    <apex:pageBlockTable value="{!AvailableProducts}" var="a">
                    
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Name.Label}" value="{!a.Product2.Name}" />
                        
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Family.Label}" value="{!a.Product2.Family}"/>
                        
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Description.Label}" value="{!a.Product2.Description}"/>
                        
                        <apex:column >
                       
                            <apex:commandButton value="Select" action="{!addToShoppingCart}" reRender="selected,searchResults" immediate="true">
       
                                <apex:param value="{!a.Id}" assignTo="{!toSelect}" name="toSelect"/>
                            </apex:commandButton>
                        </apex:column>
                        
                    </apex:pageBlockTable>
                    
                 
                    <apex:outputPanel styleClass="fyi" rendered="{!overLimit}">
                        <br/>
                        Your search returned over 100 results, use a more specific search string if you do not see the desired {!$ObjectType.Product2.Label}.
                        <br/>
                    </apex:outputPanel>
                    
                </apex:outputPanel>
            
            </apex:pageBlock>
            
        </apex:outputPanel>

    </apex:form>

</apex:page>

Here is class/controller

public with sharing class opportunityProductEntryExtension {

    public Opportunity theOpp {get;set;}
    public String searchString {get;set;}
    public opportunityLineItem[] shoppingCart {get;set;}
    public priceBookEntry[] AvailableProducts {get;set;}
    public Pricebook2 theBook {get;set;}   
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}
    
    public Boolean overLimit {get;set;}
    public Boolean multipleCurrencies {get; set;}
    
    private Boolean forcePricebookSelection = false;
    
    private opportunityLineItem[] forDeletion = new opportunityLineItem[]{};


    public opportunityProductEntryExtension(ApexPages.StandardController controller) {

     
        multipleCurrencies = UserInfo.isMultiCurrencyOrganization();

        
        if(multipleCurrencies)
            theOpp = database.query('select Id, Pricebook2Id, Pricebook2.Name, CurrencyIsoCode from Opportunity where Id = \'' + controller.getRecord().Id + '\' limit 1');
        else
            theOpp = [select Id, Pricebook2Id, PriceBook2.Name from Opportunity where Id = :controller.getRecord().Id limit 1];
        
       
        shoppingCart = [select Id, Quantity, TotalPrice, UnitPrice, Discount_Choice__c, Discount_Percent__c, Discount_Currency__c, Description, PriceBookEntryId, PriceBookEntry.Name, PriceBookEntry.IsActive, PriceBookEntry.Product2Id, PriceBookEntry.Product2.Name, PriceBookEntry.PriceBook2Id from opportunityLineItem 
                        where OpportunityId=:theOpp.Id];

       
        if(theOpp.Pricebook2Id == null){
            Pricebook2[] activepbs = [select Id, Name from Pricebook2 where isActive = true limit 2];
            if(activepbs.size() == 2){
                forcePricebookSelection = true;
                theBook = new Pricebook2();
            }
            else{
                theBook = activepbs[0];
            }
        }
        else{
            theBook = theOpp.Pricebook2;
        }
        
        if(!forcePricebookSelection)
            updateAvailableList();
    }
    
   
    public PageReference priceBookCheck(){
    
      
        if(forcePricebookSelection){        
            return changePricebook();
        }
        else{
        
           
            if(theOpp.pricebook2Id != theBook.Id){
                try{
                    theOpp.Pricebook2Id = theBook.Id;
                    update(theOpp);
                }
                catch(Exception e){
                    ApexPages.addMessages(e);
                }
            }
            
            return null;
        }
    }
       
    public String getChosenCurrency(){
    
        if(multipleCurrencies)
            return (String)theOpp.get('CurrencyIsoCode');
        else
            return '';
    }

    public void updateAvailableList() {
    
       
        String qString = 'select Id, Pricebook2Id, IsActive, Product2.Name, Product2.Family, Product2.IsActive, Product2.Description, UnitPrice from PricebookEntry where IsActive=true and Pricebook2Id = \'' + theBook.Id + '\'';
        if(multipleCurrencies)
            qstring += ' and CurrencyIsoCode = \'' + theOpp.get('currencyIsoCode') + '\'';
        
     
        if(searchString!=null){
            qString+= ' and (Product2.Name like \'%' + searchString + '%\' or Product2.Description like \'%' + searchString + '%\')';
        }
        
        Set<Id> selectedEntries = new Set<Id>();
        for(opportunityLineItem d:shoppingCart){
            selectedEntries.add(d.PricebookEntryId);
        }
        
        if(selectedEntries.size()>0){
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
            
            qString+= extraFilter;
        }
        
        qString+= ' order by Product2.Name';
        qString+= ' limit 101';
        
        system.debug('qString:' +qString);        
        AvailableProducts = database.query(qString);
        
      
        if(AvailableProducts.size()==101){
            AvailableProducts.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
    }
    
    public void addToShoppingCart(){
    
 
    
        for(PricebookEntry d : AvailableProducts){
            if((String)d.Id==toSelect){
                shoppingCart.add(new opportunityLineItem(OpportunityId=theOpp.Id, PriceBookEntry=d, PriceBookEntryId=d.Id, UnitPrice=d.UnitPrice));
                break;
            }
        }
        
        updateAvailableList();  
    }
    

    public PageReference removeFromShoppingCart(){
    
   
    
        Integer count = 0;
    
        for(opportunityLineItem d : shoppingCart){
            if((String)d.PriceBookEntryId==toUnselect){
            
                if(d.Id!=null)
                    forDeletion.add(d);
            
                shoppingCart.remove(count);
                break;
            }
            count++;
        }
        
        updateAvailableList();
        
        return null;
    }
    
  //HERE IS MY ACTION TO GET IT TO WORK
    public void doDisable() {
        
        if(OportunityLineItem.Discount_Choice__c =='Currency')
        {
            shouldRender=false; 
        }
        
        else{
            shouldRender =true;
             }
   }
    
    public PageReference onSave(){
    
       
        if(forDeletion.size()>0)
            delete(forDeletion);
    
   
        try{
            if(shoppingCart.size()>0)
                upsert(shoppingCart);
        }
        catch(Exception e){
            ApexPages.addMessages(e);
            return null;
        }  
           
       
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
    
    public PageReference onCancel(){
 
         
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
    
    public PageReference changePricebook(){
    
    
        PageReference ref = new PageReference('/oppitm/choosepricebook.jsp');
        ref.getParameters().put('id',theOpp.Id);
        ref.getParameters().put('retURL','/apex/opportunityProductEntry?id=' + theOpp.Id);
        
        return ref;
    }
    
}
Hi All;

I have created a trigger that pulls Product names and puts them on the Opportunity so that I can see them in a related list on Account.  

I have a test case that gets me 82%, but want to push it higher in case data or something else changes.

Here is my trigger:
trigger ShowOppProd on Opportunity (before update,before insert) {
 Map<Id,Set<String>> prodToOpp = new Map<Id,Set<String>> ();
    for (Opportunity opp : [SELECT Id, Opportunity_Prod__c, (SELECT Id, OpportunityId, Product2.name
                                                           FROM OpportunityLineItems)FROM Opportunity 
                            WHERE Opportunity.Id IN: Trigger.new] ) {
         
         Set<String> productsInOpp = new Set<String>();
         for (OpportunityLineItem oli : opp.opportunityLineItems)
             productsInOpp.add(oli.Product2.name);
         
                                if(prodToOpp.containsKey(opp.Id)){
                                 Set<String> uniqueProdset = prodToOpp.get(opp.Id);
                                    uniqueProdset.addAll(productsInOpp);
                                    prodToOpp.put(opp.Id,uniqueProdset);
                                }
                                else
                                  prodToOpp.put(opp.Id,productsInOpp);
                                
                            }
    for (Opportunity o: Trigger.new){
        if(prodToOpp.containsKey(o.Id)){
            String concatProd = '';
            for (String p : prodToOpp.get(o.Id))
                concatProd = concatProd + (concatProd.length() == 0 ? '' : '; ')+ p;
            o.Opportunity_Prod__c = concatProd;
        }
    
}
}

Here is my test case:
@isTest
public class OppProdTest {
    static testMethod void TestOppProd() {
        
        Account a = new Account (
             Name = 'The High School',
             Organization_Type__c = 'High School'
        );
        
        Insert a;
        
        
        Product2 prod = new Product2(Name = 'Bronze',
                                     Family = 'test'
                                    );
        Insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();
        
        PricebookEntry standardPrice = new PricebookEntry (
             Pricebook2Id = pricebookId, 
             Product2Id = prod.Id,
             UnitPrice = 500, 
             IsActive = true
        );
        
        Insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(
             Name = 'Custom Pricebook',
             isActive = true
        );
        
        Insert customPB;
        
        
        PriceBookEntry customPrice = new PricebookEntry(
             Pricebook2Id = customPB.Id,
             Product2Id = prod.Id,
             UnitPrice = 350,
             IsActive = true
    
        );
        
        Insert customPrice;
        
     
        Opportunity opp = new Opportunity(
             Account = a,
             Opportunity_Prod__c = prod.Name,
             Name = 'Test Opp',
             StageName = 'Proposal',
             CloseDate = System.today()
        );
        
        Insert opp;     
        
        
        OpportunityLineItem OLI = new OpportunityLineItem(
             PricebookEntryId = standardPrice.Id,
             OpportunityId = opp.Id,
             Quantity = 1,
             TotalPrice = standardPrice.UnitPrice 
         );
        
        Insert OLI;
               
        
       System.assertEquals('Bronze', opp.Opportunity_Prod__c);
                             
                
         }                                   
}

Running the issues I am getting that these lines are not under coverage. I am at a loss on how to add this to the test.  I know I probably need to add another assert somewhere, but cant figure it out.  

                          Set<String> uniqueProdset = prodToOpp.get(opp.Id);
                                    uniqueProdset.addAll(productsInOpp);
                                    prodToOpp.put(opp.Id,uniqueProdset);

Any help would be most appreciated!

Thanks!
Hello

I have a requirement that asks me to show child opportunities and child tasks(activities) on the parent account.  I have created Parent/Child Hierarchy for the accounts.  What they want is anytime a sales person creates an opportunity or a task on a child, they see it in a related list on the parent.

I created 2 lookup fields.  One on Opportunity and one on activity custom fields.  

I then went to Process Builder and used the following:

For Opportunity -- 

Choose Object and Specify When to Start the Process
Object * Opportunity
Start Process* When record is created or edited

Define Criteria for this Action Group
*No criteria- just execute the actions

TRUE >Immediate Actions>Add actions>

Select and Define Action
Action type*Update Records

Record type > Select a record to update* Select the Opportunity record that started your process

Criteria for Updating Records* No criteria- just execute the actions

Set new field values for the records you update***
Field* Parent Account Lookup 
Type* Reference
Value* Account.ParentId

and for TASK --

Choose Object and Specify When to Start the Process
Object * Task
Start Process* When record is created or edited

Define Criteria for this Action Group
*No criteria- just execute the actions

TRUE >Immediate Actions>Add actions>

Select and Define Action
Action type*Update Records

Record type > Select a record to update* Select the Task record that started your process

Criteria for Updating Records* No criteria- just execute the actions

Set new field values for the records you update***
Field* Parent Account Lookup 
Type* Reference
Value* Account.ParentId 

What I am running into is that it works fine for the Opportunity.  They can create an opportunity on a child or the parent account with no problem.   It is when I use the Task it errors.  They cannot create a task on the parent account????  I get a Flow error.

Error element myRule_1_A1 (FlowRecordUpdate).
This error occurred when the flow tried to update records: The flow failed to access the value for myVariable_current.Account.ParentId because it hasn't been set or assigned.. For details, see API Exceptions.

Any ideas why or how I can fix this?

Thanks!!!!

 
Hi

I am trying to get only tasks/activities by children in a Parent/Child hierarchy.  I have created a visual force page to show both open and closed tasks, but I am getting other child accounts not related to the parent.  So If I have Parent account "A", and "B" and "C", which are children to "A" I only want to see B & C.  Right now I am seeing "D", "E" and "F", which related to other Parent Accounts.

Here is query I have in my constructor showing the open tasks:

tasksLimited= [Select id,whoid,whatid,subject,type, Medium_of_Activity__c, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
                   Where Account.ParentID != null And status !='completed' ORDER BY activitydate LIMIT 10];
   system.debug('taskslimited: '+taskslimited);

Any help, I have tried the WhatID, but it gives me an error, not sure how to filter this down!

 
I am having problems getting code coverage increased on my test case.  I see that my extension is account, but I am having issues figuring how to get task included into account.

Here is my class

public class childTaskOnParentCont {
    
    public Account acc {get;set;}
    public List<Task> tasks {get;set;}
    public List<Task> closedTasks {get;set;}
    public List<Task> tasksLimited {get;set;}
    public List<Task> closedTasksLimited {get;set;}
    
    public List<Contact> cons {get;set;}
    
    
    //constructor
    public childTaskOnParentCont(apexpages.StandardController con){
        acc = (Account) con.getRecord();
        cons=[SELECT id from Contact WHERE AccountID=: acc.Id];
         
        
    tasksLimited= [Select whoid,whatid,subject,type, Medium_of_Activity__c, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
                   Where Account.ParentID != null And status !='completed' ORDER BY activitydate LIMIT 10];
   system.debug('taskslimited: '+taskslimited);
        
    closedTasksLimited= [Select whoid,subject,type, Medium_of_Activity__c, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
                   Where Account.ParentID != null And status =:'completed' ORDER BY activitydate LIMIT 10];  
    system.debug('closedTasksLimited: '+closedTasksLimited);   
        
        
    }
    
    //Get the Account Information
public Account getAccount() {
    return [SELECT id,ParentId, name FROM Account WHERE Id=: acc.Id];
}
                
    //Get Open Tasks for Child Tasks
public List<Task> getTasks() {

    tasks= [Select whoid,subject,type, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
            Where Account.ParentID != null And status !='completed' ORDER BY activitydate];
    return tasks;
}

//Get Closed Tasks for Child Tasks
public List<Task> getClosedTasks() {

    closedTasks= [Select whoid,subject,type, activitydate, lastmodifieddate,Account.Name, 
                   ownerid, status, priority from Task 
            Where Account.ParentID != null And status =:'completed' ORDER BY activitydate];
    return closedTasks;
  }
}

Here is my test case

@isTest
public class thecontrollerTests {
    
    public static testMethod void testTaskController() {
       
        Account acc = new Account(Name = 'State College');
        insert acc;
        
        Task tsk = new Task(status = 'Completed');
        insert tsk;
        
        PageReference pageRef = Page.childTaskOnParent;
        Test.setCurrentPage(pageRef);
        ApexPages.StandardController sc = new ApexPages.StandardController(acc);
        childTaskOnParentCont testAccPlan = new childTaskOnParentCont(sc);
    }
}

Any help would be greatly appreciated.