• CB312
  • NEWBIE
  • 0 Points
  • Member since 2011

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

Hi All,

 

Has anyone ever expierenced this error when using Javascript Remoting?

 

Visualforce Remoting Exception: Method 'updateMerchantProduct' not found on controller ManageLeadsRemote. Check spelling, method exists, and/or method is RemoteAction annotated.

 

Serialzed Code:



global with sharing class ManageLeadsRemote {
   
    @RemoteAction
    global static sObject[] searchMerchants(String divisionName, string MerchantType) 
        {    
            //This Function Works 
        }
    
    
    @RemoteAction
    global static boolean updateMerchantProduct(String MerchantType, String recordID, String ProductLine) 
        {
        system.debug('------------------------DEBUG---if you can read this we got in to this function');
            boolean updateCheck = false;
            if(MerchantType=='Account')
                {
                    update new Account(Id = recordID, CurrentProduct__c = ProductLine);
                    updateCheck = true;
                }
            if(MerchantType=='Lead')
                {
                    update new lead(Id = recordID, CurrentProduct__c = ProductLine);
                    updateCheck = true;
                }
            return updateCheck;
        }

}

 Javascript Code in my VisualForce Page that enacts this method:

function updateAccount(MType, acc, newVal) 
    {
        // Javascript Remoting to update Accout record
        alert(MType);
        alert(acc);
        ManageLeadsRemote.updateMerchantProduct(MType, acc.Id, newVal, function(result, event)
            {         
               if (event.status && event.result) 
                   {       
                          alert('Good Job - this worked!');
                   } else 
                       {
                          alert(event.message);
                       }
            }, {escape:true});
    }

 

I have a feeling the error message that is being thrown is not the error that is actually occuring, the alerts are firing before the updateMerchantProduct remote function and are passing in the correct params. So I'm stuck on this....

 

Thanks!

  • September 14, 2011
  • Like
  • 0

Hi,

 

I have a custom visualforce page with some javascrpit in it and I am getting this error: Unsafe JavaScript attempt to access frame with URL

 

Can someone help me figure out why the values are being passed incorrectly.

 

<apex:page standardController="lead" showheader="false" sidebar="false" id="pgId"> 
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"/>
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"/>
<apex:includeScript value="{!URLFOR($Resource.tablesorter, 'jquery.tablesorter.js')}"/>
<apex:stylesheet value="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/trontastic/jquery-ui.css"/>


<body>
  <p id="hello">Hello World</p>
  <a href="http://www.google.com" class="name">google</a>
  <a href="http://www.yahoo.com" class="name">yahoo</a>
</body>
  <div id = "searching" title= "Searching.............">
  </div> 

<script type="text/javascript">
var j$ = jQuery.noConflict();
j$(function(){
  $j("#searching" ).dialog({ 'autoOpen': true });
});
 
</script>

</apex:page>

 this throws:

 Unsafe JavaScript attempt to access frame with URL https://c.cs7.visual.force.com/servlet/servlet.Integration?lid=XXXXXXXXXXX&ic=1 from frame with URL https://cs7.salesforce.com/XXXXXXXXXX. Domains, protocols and ports must match.

 

  • August 02, 2011
  • Like
  • 0

Hi,

 

I have an html input that I would like to pass to my apex controller. How can I have APEX access the value?


Sanitized code below, I am trying to pass the "rep2" field to my controller.

 

Sanatized code here, I'm using JQuery Autocomplete to populate the field.

VF Page:

 

$j(document).ready(function() 
    {
        $j("#rep2" ).autocomplete({
            'source': replist
        });
     });   

<apex:form >
<apex:pageBlock >

   <div class="ui-widget">
    <label for="rep2"><b>Reassign to: </b></label>
    <input id="rep2"/>
   </div>

<apex:pageBlockButtons >
        <apex:commandButton action="{!updateLeadOwner}" value="Save"   rerender="leadtoupdatetable"/>
       </apex:pageBlockButtons>
      </apex:pageBlock>

</apex:form>

 Controller:

public pagereference updateLeadOwner()
    {
        id leadid = ApexPages.currentPage().getParameters().get('id');
        string repname = Apexpages.currentPage().getParameters().get('rep2');
system.debug('-----------------DEBUG-------------');
        system.debug(repname);

 repname return null, what is the best way to access the value?

 

Thanks!

 

-Chris

  • July 29, 2011
  • Like
  • 0

Hey, I'm trying to traverse relationships in Javascript, and the dot notation is not working in Javascript. Can you please help me access the name? I have written my own Javascript Remoting class that handles the query and then returns the results.

 

//Building the SOQL query to pass to the Javascript remoting class

var queryAcct = "SELECT id, Name, Owner.Name, Division__r.Name FROM Account ";
queryAcct += "WHERE Owner.name like '%{username}%'";
queryAcct += " ORDER BY Division__c ";
queryAcct += "Limit 5000";

 

//Fucntion that is called to query the account records, this then passes the results off to the next function that builds the table

function getaccts(){
var un = document.getElementById("username").value;
alert(queryAcct.replace("{username}",un));
RemotingToolkit.query(queryAcct.replace("{username}",un),function(result,event) {
        if (event.status) {
        handleAccts(result,$j('#acctresultsDiv'));
             } else {
                    alert('Remoting call failed');
                    }
        });
    }

 //Handles the Array that is returned from the query, then using Jquery builds the table and injects the HTML in to the div.

function handleAccts(records,tableObject) {
            var tableString ='<table border="1">';
                tableString+='<th>Owner</th><th>Company</th><th>Division</th>';
                $j.each(records, function(index,record) {
                tableString += '<tr><td> ' + record.Owner.Name + '</td><td>' + record.Name+''+ '</td><td>' + record.Division__r.Name+'';
                });
                tableString += '</td></tr></table>';
                tableObject.html(tableString);
                }

 I can pass in record.Division__c and it runs, when I try to pass in record.Division__r.Name it erros out. What can I do to access the name of the related object? What is really wierd is that "record.Owner.Name" works and returns the name of the owner, not the ID, but Division__r.Name throws an error.

 

Thanks!

 

-Chris

  • July 18, 2011
  • Like
  • 0

Hey All,

 

Is there a way to remove the new line character '/n' from a Long Text Area in Apex? I am trying to pass to a google fusion obj and they don't handle the '/n' character and throw an exception. Any idea how I can take a long text area(we will call it LT__c) and have it remove the new line characters? Is this supported nativly in apex?

 

Thanks!

-Chris

  • June 01, 2011
  • Like
  • 0

Hi,

 

I've built a VF page and am having problems initiing my variables in the test class. I can't get the code to execute so I am only getting 10% coverage. Any ideas?

 

VF Page:

 

This is where the java vars are getting put in.

 

 

<apex:pageBlock title="Search (beta)" mode="edit" id="criteria">
 
      <script type="text/javascript">
        function doSearch() {
        setTimeout(1550);
        searchServer(
        document.getElementById("account").value, document.getElementById("categories").options[document.getElementById("categories").selectedIndex].value,
Then there is a table that has this code:
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="account" onkeyup="doSearch();"/>
        </td>
      </tr>
Apex Code:
public PageReference runSearch() {
String account = Apexpages.currentPage().getParameters().get('account');
if (!account.equals(''))
      soql += ' AND Custom_Obj__r.Account_Name__r.name LIKE \''+String.escapeSingleQuotes(account)+'%\'';
runQuery();
return null; 
public void runQuery() {
 
    try {
      Deals = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 50');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }
 
  }
Apex Test Code:
string theacctname= 'test acct';
PageReference pageRef = Page.SearchPage;
                       Test.setCurrentPage(pageRef); 
                       pageRef.getParameters().put('account', theacctname);
  
      SearchController con = new SearchController();
                       con = new SearchController();
                       con.runquery();
                       con.runsearch();

 

help?
Thanks,
Chris

 

  • May 16, 2011
  • Like
  • 0

Hi,

 

I just read through most of the boards including this recent post: http://forums.sforce.com/t5/Apex-Code-Development/Test-Methods-for-Extensions/td-p/260353

 

and I still am confused with the process for setting up my test method.  (I've already registered for the March 30th class but any help between now and then would be much appreciated)

 

Here is my class:

 

 

public class POSystem {
    Public Purchase_Order__c po {get; set;}
    public POSystem(ApexPages.StandardController controller) {po = (Purchase_Order__c)controller.getRecord();}  
    public List<Lead> getRelevantLeads() { 
    List<Lead>Listofleads = [select id, company, Category__c, Subcategory__c, Name, Website, Email, Status, Phone, LeadSource, Last_Activity_Date__c from Lead WHERE ownerid = :po.assigned_to__c AND Category__c = :po.Category__c AND isconverted = false AND Subcategory__c = :po.Subcategory__c ORDER BY Last_Activity_Date__c ASC];
  return  Listofleads;
} 

 

 

and here is my *attenpt* at the test class

 

private testMethod static void testRelevantLeads(){
        
        //String expected = '{cols: [{id: "col1", label: "Billing Country", type: "string"},{id: "col2", label: "Number of Opportunities", type:                "number"}], rows: [{c:[{v: "MyCountry"},{v: 2.0}]}]}';
        ApexPages.StandardController stc = new ApexPages.Standardcontroller();
        POsystem con = new RelevantLeads (stc);
        
        //ApexPages.StandardController <POsystem> pos = new POSystem((new ApexPages.StandardController(testleads)));
        
        Lead l1 = new Lead(Company='l1', Division__c = 'Hampton Roads', Category__c = 'Health & Beauty', Subcategory__c = 'Dental'); 
        Lead l2 = new Lead(Company='l2', Division__c = 'Hampton Roads', Category__c = 'Health & Beauty', Subcategory__c = 'Dental'); 
        list <lead> testleads = new list<lead>();
        testleads.add(l1);
        testleads.add(l2);
        //insert new List<Lead> {l1, l2};
        String actual = pos.getListofleads(testleads);

        //System.assertEquals(expected, actual);
    }

 

Thanks!

 

 

  • March 23, 2011
  • Like
  • 0

Hi,

 

What I'm trying to do:

Generate a custom data table on a page that renders based on the values entered in the record that is currently being viewed. The code compiles with no errors but doesn't output any related leads. The class and vf page are below. Any help would be appreciated.

 

Class:

 

public class POSystem {
    public POSystem(ApexPages.StandardController controller) {}  
    public List<Lead> getPOSystem() {
        
        String Category = ApexPages.currentPage().getParameters().get('Category__c');
        String Subcategory = ApexPages.currentPage().getParameters().get('Subcategory__c');
        id repid = ApexPages.currentPage().getParameters().get('Assigned_To__c');
        
        POSystem = [select company, Category__c, Subcategory__c, Name, Phone, Last_Activity_Date__c from Lead WHERE ownerid = :repid AND Category__c = :Category AND Subcategory__c = :Subcategory ORDER BY company ASC ];
  return  POSystem;
}
}

 VF Page

 

<apex:page standardController="Purchase_Order__c" extensions="POSystem">
  <apex:sectionHeader title="Purchase Order"/>
 <apex:pageBlock title="PO Leads">
  <apex:dataTable value="{!POSystem}" var="l" cellPadding="4" border="1" style="text-align:center">
   
   <apex:column >
    <apex:facet name="header">Lead</apex:facet>
    <apex:outputField value="{!l.company}"/>
   </apex:column>
   <apex:column >
    <apex:facet name="header">Category</apex:facet>
    <apex:outputField value="{!l.Category__c}"/>
   </apex:column>   
  
   
  </apex:dataTable>
 </apex:pageBlock>
</apex:page>

 

Thanks!

 

 

  • March 22, 2011
  • Like
  • 0

I'm stuck on this test class, I don't think I am consrtucting it correctly as I am incorrectly refrecing the object. This is my first time writing a test class for an extension class.

System.NullPointerException: Attempt to de-reference a null object - Class.testTotalGPbyDiv.testTotalGPbyDiv: line 4, column 1 External entry point
 

 

 

public class testTotalGPbyDiv {
static testMethod void testTotalGPbyDiv(){
Division__c div;
div.name = 'Hampton Test';
insert div;

ApexPages.currentPage().getParameters().put('id', div.Id);
ApexPages.StandardController std=new ApexPages.StandardController(div);

TotalGPbyDiv controller=new TotalGPbyDiv(std);

}
}

 

 


I'm really lost right now on how to get this to complie. Any thoughts?

 

_chris

  • March 17, 2011
  • Like
  • 0

Hi All,

 

I keep hitting the SOQL limit with this trigger, I know I need to move the query outside the For loop, but I can't figure out how to do that while still accomplishing my main goal.

 

Apex governor limit warning

Operation: update.Opportunity

Caused the following Apex resource warnings:

Number of SOQL queries: 100 out of 100


		
		

 

 

 

 

trigger updateDivisions on Opportunity (before update) {
    for(Opportunity o : trigger.new){
        /*
            I query for the division where the Name is equal to the picklist value selected on the Opportunity.
            It is important to query and store to a list (even though you are only expecting one value to be returned)
            because if you do not store it to a list and the query returns nothing, the trigger will break
            and throw an error message. 
        */
        List<Division__c> myDivision = [select Id from Division__c where Name =: o.Division__c limit 1];
        
        /*
            I have created a lookup on the Opportunity object to the Division__c object so that when you have the 
            Id of the division you queried for, you can relate it back to that record on the opportunity record
            detail page.
        */
        if(myDivision.size() > 0) {
            /*
                By specifying myDivision[0] you grab the first element of the list (in this instance, 
                it is the only element in the list as a result of the delimiter in the SOQL query
            */
            o.Division_Dynamic__c = myDivision[0].Id;
        } else {
            //Assign to a dummy division value for testing to isolate opportunities with an incorrect division
            o.Division_Dynamic__c = 'a0PC0000008CGfs';
        }
    }
}

 

Thanks!

 

  • March 15, 2011
  • Like
  • 0

Hey Guys,

 

I have no idea where to start with this, and my contact at Salesforce said that this would be a great resource. I appologize for my niaveness with this, I am not looking for you to do my work, just point me in the right direction. Thanks!

 

English explination of what I'm looking to do:

 

There is a field stored on each user (assistant) the type is a Lookup Relationship to another user. I want that field to autopopulate in an opportunity field, Field_B. It should lookup the opportunity owner, grab the Assistant field and associate that user with the opportunity as Field_B.

 

Can anyone help me?

 

Thanks!

-Chris

  • February 04, 2011
  • Like
  • 0

Hi,

 

I have an html input that I would like to pass to my apex controller. How can I have APEX access the value?


Sanitized code below, I am trying to pass the "rep2" field to my controller.

 

Sanatized code here, I'm using JQuery Autocomplete to populate the field.

VF Page:

 

$j(document).ready(function() 
    {
        $j("#rep2" ).autocomplete({
            'source': replist
        });
     });   

<apex:form >
<apex:pageBlock >

   <div class="ui-widget">
    <label for="rep2"><b>Reassign to: </b></label>
    <input id="rep2"/>
   </div>

<apex:pageBlockButtons >
        <apex:commandButton action="{!updateLeadOwner}" value="Save"   rerender="leadtoupdatetable"/>
       </apex:pageBlockButtons>
      </apex:pageBlock>

</apex:form>

 Controller:

public pagereference updateLeadOwner()
    {
        id leadid = ApexPages.currentPage().getParameters().get('id');
        string repname = Apexpages.currentPage().getParameters().get('rep2');
system.debug('-----------------DEBUG-------------');
        system.debug(repname);

 repname return null, what is the best way to access the value?

 

Thanks!

 

-Chris

  • July 29, 2011
  • Like
  • 0

I have been trying to implement jQuery into my visualForce pages to create a nicer appeal with simple animations and a better view of things. I have a prebuilt website demo for the new UI but already I am having trouble getting started by having the jQuery work. I've added the jQuery standard development to my static resources. But not even the simple hide() function isnt working.

 

Can anyone know what I am doing wrong or can lead me the right direction? The tutorials and things I've tried replicating off sites have not worked.

 

 

  • July 19, 2011
  • Like
  • 0

Hi Everyone

 

I have a google bar chart, at my client portal, showing client accounts info. 

 

As google bar chart has a limitation of 300000 pixels(chart size), i was wondering if there is any way i can paginate the bars(one bar showing one account), as in my case a person can have a large number of accounts.

 

So instead of reducing the bar width to fit frame size, i want to paginate the bars.

 

Any idea ?

 

Thanks

Sid

Hey, I'm trying to traverse relationships in Javascript, and the dot notation is not working in Javascript. Can you please help me access the name? I have written my own Javascript Remoting class that handles the query and then returns the results.

 

//Building the SOQL query to pass to the Javascript remoting class

var queryAcct = "SELECT id, Name, Owner.Name, Division__r.Name FROM Account ";
queryAcct += "WHERE Owner.name like '%{username}%'";
queryAcct += " ORDER BY Division__c ";
queryAcct += "Limit 5000";

 

//Fucntion that is called to query the account records, this then passes the results off to the next function that builds the table

function getaccts(){
var un = document.getElementById("username").value;
alert(queryAcct.replace("{username}",un));
RemotingToolkit.query(queryAcct.replace("{username}",un),function(result,event) {
        if (event.status) {
        handleAccts(result,$j('#acctresultsDiv'));
             } else {
                    alert('Remoting call failed');
                    }
        });
    }

 //Handles the Array that is returned from the query, then using Jquery builds the table and injects the HTML in to the div.

function handleAccts(records,tableObject) {
            var tableString ='<table border="1">';
                tableString+='<th>Owner</th><th>Company</th><th>Division</th>';
                $j.each(records, function(index,record) {
                tableString += '<tr><td> ' + record.Owner.Name + '</td><td>' + record.Name+''+ '</td><td>' + record.Division__r.Name+'';
                });
                tableString += '</td></tr></table>';
                tableObject.html(tableString);
                }

 I can pass in record.Division__c and it runs, when I try to pass in record.Division__r.Name it erros out. What can I do to access the name of the related object? What is really wierd is that "record.Owner.Name" works and returns the name of the owner, not the ID, but Division__r.Name throws an error.

 

Thanks!

 

-Chris

  • July 18, 2011
  • Like
  • 0

Hi all,

 

I have a custom object Territory__c in which there is lookup(User) Regional_Director field. I am trying to assign the Regional Director to appropriate user.

 

Following is the code in a trigger I have and want to update the regional director lookup field after insert. However it gives the following error: "Regional Director: id value of incorrect type:". It looks like terr.regional_director__c returns a SObject so the assignment may not work, how can I get it working? Thanks much for your help.

 

trigger addSalesDirReps on Territory__c (before insert) {
    Territory__c [] territoryList = trigger.new;
    List <Territory__c> updatedListToInsert= new List <Territory__c>();
       
    for(Territory__c terr: territoryList){
         List<User> lookupRMUser = [select Id from User where Name=:terr.Regional_Director_Name__c];
         terr.regional_director__c = lookupRM[0].Id;  
         updatedListToInsert.add(terr);
     }
    insert updatedListToInsert;

}

 

Hai friends,

 

I am new to salesforce, i have one issue with Datatable,pls helpme.

 

I have 3 datatables,one datatable contains Comapany Names,another data table contains Employee Names.Now issue is when i drag Employee Name to the Company name then EmployeeName and Company Name need to collect into another list then that list will display in another Datatable.

 

Thanks

Shri@Sfdc

Hi,

 

I just read through most of the boards including this recent post: http://forums.sforce.com/t5/Apex-Code-Development/Test-Methods-for-Extensions/td-p/260353

 

and I still am confused with the process for setting up my test method.  (I've already registered for the March 30th class but any help between now and then would be much appreciated)

 

Here is my class:

 

 

public class POSystem {
    Public Purchase_Order__c po {get; set;}
    public POSystem(ApexPages.StandardController controller) {po = (Purchase_Order__c)controller.getRecord();}  
    public List<Lead> getRelevantLeads() { 
    List<Lead>Listofleads = [select id, company, Category__c, Subcategory__c, Name, Website, Email, Status, Phone, LeadSource, Last_Activity_Date__c from Lead WHERE ownerid = :po.assigned_to__c AND Category__c = :po.Category__c AND isconverted = false AND Subcategory__c = :po.Subcategory__c ORDER BY Last_Activity_Date__c ASC];
  return  Listofleads;
} 

 

 

and here is my *attenpt* at the test class

 

private testMethod static void testRelevantLeads(){
        
        //String expected = '{cols: [{id: "col1", label: "Billing Country", type: "string"},{id: "col2", label: "Number of Opportunities", type:                "number"}], rows: [{c:[{v: "MyCountry"},{v: 2.0}]}]}';
        ApexPages.StandardController stc = new ApexPages.Standardcontroller();
        POsystem con = new RelevantLeads (stc);
        
        //ApexPages.StandardController <POsystem> pos = new POSystem((new ApexPages.StandardController(testleads)));
        
        Lead l1 = new Lead(Company='l1', Division__c = 'Hampton Roads', Category__c = 'Health & Beauty', Subcategory__c = 'Dental'); 
        Lead l2 = new Lead(Company='l2', Division__c = 'Hampton Roads', Category__c = 'Health & Beauty', Subcategory__c = 'Dental'); 
        list <lead> testleads = new list<lead>();
        testleads.add(l1);
        testleads.add(l2);
        //insert new List<Lead> {l1, l2};
        String actual = pos.getListofleads(testleads);

        //System.assertEquals(expected, actual);
    }

 

Thanks!

 

 

  • March 23, 2011
  • Like
  • 0

Hi,

 

What I'm trying to do:

Generate a custom data table on a page that renders based on the values entered in the record that is currently being viewed. The code compiles with no errors but doesn't output any related leads. The class and vf page are below. Any help would be appreciated.

 

Class:

 

public class POSystem {
    public POSystem(ApexPages.StandardController controller) {}  
    public List<Lead> getPOSystem() {
        
        String Category = ApexPages.currentPage().getParameters().get('Category__c');
        String Subcategory = ApexPages.currentPage().getParameters().get('Subcategory__c');
        id repid = ApexPages.currentPage().getParameters().get('Assigned_To__c');
        
        POSystem = [select company, Category__c, Subcategory__c, Name, Phone, Last_Activity_Date__c from Lead WHERE ownerid = :repid AND Category__c = :Category AND Subcategory__c = :Subcategory ORDER BY company ASC ];
  return  POSystem;
}
}

 VF Page

 

<apex:page standardController="Purchase_Order__c" extensions="POSystem">
  <apex:sectionHeader title="Purchase Order"/>
 <apex:pageBlock title="PO Leads">
  <apex:dataTable value="{!POSystem}" var="l" cellPadding="4" border="1" style="text-align:center">
   
   <apex:column >
    <apex:facet name="header">Lead</apex:facet>
    <apex:outputField value="{!l.company}"/>
   </apex:column>
   <apex:column >
    <apex:facet name="header">Category</apex:facet>
    <apex:outputField value="{!l.Category__c}"/>
   </apex:column>   
  
   
  </apex:dataTable>
 </apex:pageBlock>
</apex:page>

 

Thanks!

 

 

  • March 22, 2011
  • Like
  • 0

I'm stuck on this test class, I don't think I am consrtucting it correctly as I am incorrectly refrecing the object. This is my first time writing a test class for an extension class.

System.NullPointerException: Attempt to de-reference a null object - Class.testTotalGPbyDiv.testTotalGPbyDiv: line 4, column 1 External entry point
 

 

 

public class testTotalGPbyDiv {
static testMethod void testTotalGPbyDiv(){
Division__c div;
div.name = 'Hampton Test';
insert div;

ApexPages.currentPage().getParameters().put('id', div.Id);
ApexPages.StandardController std=new ApexPages.StandardController(div);

TotalGPbyDiv controller=new TotalGPbyDiv(std);

}
}

 

 


I'm really lost right now on how to get this to complie. Any thoughts?

 

_chris

  • March 17, 2011
  • Like
  • 0

Hi All,

 

I keep hitting the SOQL limit with this trigger, I know I need to move the query outside the For loop, but I can't figure out how to do that while still accomplishing my main goal.

 

Apex governor limit warning

Operation: update.Opportunity

Caused the following Apex resource warnings:

Number of SOQL queries: 100 out of 100


		
		

 

 

 

 

trigger updateDivisions on Opportunity (before update) {
    for(Opportunity o : trigger.new){
        /*
            I query for the division where the Name is equal to the picklist value selected on the Opportunity.
            It is important to query and store to a list (even though you are only expecting one value to be returned)
            because if you do not store it to a list and the query returns nothing, the trigger will break
            and throw an error message. 
        */
        List<Division__c> myDivision = [select Id from Division__c where Name =: o.Division__c limit 1];
        
        /*
            I have created a lookup on the Opportunity object to the Division__c object so that when you have the 
            Id of the division you queried for, you can relate it back to that record on the opportunity record
            detail page.
        */
        if(myDivision.size() > 0) {
            /*
                By specifying myDivision[0] you grab the first element of the list (in this instance, 
                it is the only element in the list as a result of the delimiter in the SOQL query
            */
            o.Division_Dynamic__c = myDivision[0].Id;
        } else {
            //Assign to a dummy division value for testing to isolate opportunities with an incorrect division
            o.Division_Dynamic__c = 'a0PC0000008CGfs';
        }
    }
}

 

Thanks!

 

  • March 15, 2011
  • Like
  • 0