• arizona
  • NEWBIE
  • 170 Points
  • Member since 2008

  • Chatter
    Feed
  • 6
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 49
    Replies

I'm new to VF and Apex programming, but making good progress in building some custom pages and classes by Googling a lot.  But one thing I'm still trying to better understand is the transfer of values between the web browser, VF page, and the backend Apex class.

 

For example, if I have an input text field on a VF page, when a user inputs a value, or changes a value, in that field, at what point is that value actually "set" in the variable in the Apex class, and available for computations?

 

New/changed values seem to get transferred and set upon some sort of page refresh, or action, but I'm having a hard time finding documentation on exactly how the transfer of data occurs.  Please note, I'm not assuming there's any special event processing occurring on the field (such as onblur, onchange, etc), just interested in basic field input/output and when the values actually get transferred.

 

I hope this question is making sense...

 

Is anything like this covered in any Apex or VF documentation that maybe I missed?

 

Thanks!

Can anyone help me with the below test class? It is for a trigger that creates a new record in the "Onboarding" object based off criteria in the "Application__c" object.

 

Here is the test class as I have it now, but I am getting an error of "Error: Compile Error: unexpected token: 'insert' at line 13 column 8"

 

@isTest
private class OnboardingTest {

    static testMethod void myOnboardingTest() { 
        
        Account a=new Account();
        a.Name='ob test account';
        insert a;

        Contact con=new Contact();
        con.Lastname='onboarding contact';
        con.AccountId=a.Id
        insert con;

        Job__c job=new Job__c();
        job.Name='Test job1';
        insert job;

        test.startTest();

        Application__c app=new Application__c();
        app.RecordType='012C0000000Bhsc';
        app.JobId=job.Id
        insert app;

        app.Stage__c='Signed';
        update app;

        test.stopTest();
        }
}

 

I'm trying to test an apex class that scans a chatter group for posts.  I have a query in my class that queries on the CollaborationGroupFeed object.  In my test class I have the following code:

 

Test.startTest();
     CollaborationGroup cg = new CollaborationGroup(Name='Test Group', CollaborationType='Public');
     insert cg;
            
     // Create Chatter Post
     FeedItem testFeed1 = new FeedItem(Body='Test Feed 1 Post', ParentId = cg.Id, Type='TextPost');
     insert testFeed1;
            
     // Create Chatter Comment
     FeedComment testFeed1Comment = new FeedComment(CommentBody='Test Feed 1 Comment', FeedItemId=testFeed1.Id, CommentType='TextComment');
     insert testFeed1Comment;
            
     // Create Chatter Post
     FeedItem testFeed2 = new FeedItem(Body='Test Feed 2 Post', ParentId = cg.Id, Type='TextPost');
     insert testFeed2;
            
     // Create Chatter Comment
     FeedComment testFeed2Comment = new FeedComment(CommentBody='#answer Test Feed 2 Comment', FeedItemId=testFeed2.Id, CommentType='TextComment');
     insert testFeed2Comment;
            
     List<CollaborationGroupFeed> feeds = [Select Body from CollaborationGroupFeed];
     system.debug('-------------- ' + feeds);
Test.stopTest();

 When I do a query on CollaborationGroupFeed to confirm the records, it returns 0 records.  What am I doing wrong?

  • November 29, 2012
  • Like
  • 0

Hey guys, I've lurked the forums in search of an answer but haven't found anything that could help me, and my problem seems so stupid I just can't figure it out.

 

I'm working with the PHP toolkit. Works like a charm except I'm querying for my Case sObject records. I created a custom field named Customer_Portal_User__c, that is a lookup relationship type field to a User__c object.

 

One would figure this code would be enough...

 

Query and result validation function:

 

public function getCasesByAccount($logged_acct, $connection) {
$query = "SELECT AccountId, Id, Customer_Portal_User__c, CaseNumber, Origin, Reason, Type, Category_Identifier__c, Client_Reference__c, Description, Subject, Priority, Status, OwnerId FROM Case WHERE Status IN ('New', 'Updated by Customer') AND AccountId = '".$logged_acct."'"; try { $response = $connection->query($query); } catch (Exception $e) {} if (count($response->records) >= 1) { return $response; } else { return "No cases under this account."; } }

 

And this is how I call my function and go through the records.

 

$acctCases = $salesforceDML->getCasesByAccount($logged_acct, $connection);
foreach ($acctCases->records as $record) {
echo "<div class='row'>";
echo "<div class='span-3'><a href='view_case.php?id=".$record->Id."'>View</a></div>";
echo "<div class='span-9'>".'Lalala'.$record->Customer_Portal_User__c."</div> ";
echo "<div class='span-6'>".$record->Subject."</div> ";
echo "<div class='span-9'>".$record->Type."</div> ";
echo "</div>";
}

 

 

Which outputs All of the fields, EXCEPT Customer_Portal_User__c:

 

if I var_dump the $record variable from the foreach, I get the following...

 

object(stdClass)#16 (10) { ["Id"]=> string(18) "500e0000000UZmkAAG" ["AccountId"]=> string(18) "001e0000003FQsSAAW" ["CaseNumber"]=> string(8) "00026957" ["Description"]=> string(5) "fghgh" ["Origin"]=> string(5) "Phone" ["OwnerId"]=> string(18) "005a0000008678DAAQ" ["Priority"]=> string(23) "4 - Feature Enhancement" ["Status"]=> string(3) "New" ["Subject"]=> string(5) "hgfhg" ["Type"]=> string(10) "Activation" }

 

THE FIELD ISN'T EVEN THERE!!! ALLLLLLLLLLLLLLLLLLLLLLLLLLLLL the fields are returned except THAT one. CHRISTTT. This is RIDICULOUS.

 

I've even tried swapping the $query from my function for this, but the same results.

 

$query = "SELECT FirstName__c, LastName__c, Account__c, 
				(SELECT Id, Subject, Customer_Portal_User__c from Cases__r)
				FROM User__c";

 

I just don't know anymore. Any suggestions? 

 

I have a number of custom object records in Salesforce that have been associated to the wrong parent object. I have managed to extract the data out and look up the correct parent record, which means I now have a csv file that contains:


object id | parent id

12345     | abcdef

67890     | ghijkl

...

 

When I try to use either the LexiLoader or the Workbench however, the master-detail doesn't show up as one of the fields I have amend.


Is there a way to amend master-detail relationships using one of these data loader mechanisms (there are 4000 records to update) or do I have to change the relationship to a look-up value and do it that way?

 

Thanks

Hi All,

 

I embeded a jquery codes in my custom vf page. What I would like to do is to use the jquery elements (ie, textbox,radio button, links, etc.) to communicate with Salesforce objects that is when a user clicks the save button, records will be created using the data that was filled in from the jquery elements. Please advise on what is the best way to do this kind of scenario. 

 

Thanks in Advance

Hi All,

 

I am new to REST API,I got a requirement like this

When the stage is closed-won.I need to query all the Stage that are closed-won,and update 10 feilds to other databases.

So that the site does some operation?How can this possible.

 

Pl help me out.

 

Regards

Sailer

  • September 18, 2013
  • Like
  • 0

I am trying to get better coverage of a particular controller extension and am having a few issues with one particular line.  I have a custom object where I store a task Id and a user Id and a few other fields.  This class is meant to query, insert, or delete records in that object.

 

In the getInformedUsers method below, all the lines test fine with the exception of the Return property.  I keep getting a Attempt to dereference a null object error.  The only other place where I can't seem to get coverage is in the removeInformed method for the redirect lines.  

 

I am currently at 61% pass if I do not test the getInformedUsers method but would love figure out how to cover that as well.  Code below:

 

public with sharing class informedUserList {
	
	private ApexPages.StandardController controller;
	
	
	public informedUserList(ApexPages.StandardController stdController) {     
      controller = stdController;
   }	   
	public List<Task_Informed_Users__c> getInformedUsers() {
		
		String tskID = ApexPages.currentPage().getParameters().get('Id');
		String longTaskId = String.valueOf(tskId);
		String shortTaskId = longTaskId.left(15);	
		     
        return [SELECT id, Informed_User__r.Name, Chatter_Notification__c, Send_Email__c FROM Task_Informed_Users__c WHERE Task_Id__c =: shortTaskId];
    }   
    
	public PageReference addInformed() {		
		string tskId = ApexPages.currentPage().getParameters().get('Id');		
		
		PageReference tskInformed = new pagereference('/apex/informedUsers?tId='+tskId);
		tskInformed.setRedirect(true);
  		return tskInformed;  			

	}

	public PageReference removeInformed() {		
		string tskId = ApexPages.currentPage().getParameters().get('Id');
		Id iuRecId = System.currentPageReference().getParameters().get('iuRec');
		
		delete [select id from Task_Informed_Users__c where ID=: iuRecId ]; 

   		return null;
		
		PageReference tskInformed = new pagereference('/apex/taskDetail?Id='+tskId);
		tskInformed.setRedirect(true);
  		return tskInformed;  			

	}
	
    
    public static Task testTsk;
    public static Task_Informed_Users__c testInformedUser;
    public static ID testTaskId;
    public static User testUserId;
        
    static testMethod void informedUserListTest() {    	
    	Test.startTest();
    	
    	testUserId = [SELECT ID FROM User WHERE LastName=: 'User2'];
        testTsk = new Task(Subject='testTask', ownerId=testUserId.Id); 
        insert testTsk;
        testTaskId = testTsk.Id;
            
        testInformedUser = new Task_Informed_Users__c(Informed_user__c=testUserId.Id, Task_ID__c=testTaskId, Chatter_Notification__c=FALSE, Send_Email__c=FALSE);
        insert testInformedUser;
        
        Test.setCurrentPage(Page.taskDetail);
		ApexPages.currentPage().getParameters().put('tId',testTaskId);         
              
        ApexPages.StandardController con = new ApexPages.StandardController(testInformedUser);
        informedUserList tInformedUserList = new informedUserList(con); 
        
        tInformedUserList.addInformed();  //Tests Fine
      
        tInformedUserList.removeInformed(); //Tests all but the redirect code    
        
        tInformedUserList.getInformedUsers();  //Get Attempt to DeReference a Null Object error
           
        
        Test.stopTest();        
    }
      
}

 

  • September 09, 2013
  • Like
  • 0

Hi Ya,

 

I am trying to run a upsert operation using data loader for Campaign Object but its not available to select. Its only available for Export finctionality.

 

I can see the Campaign object when I connect data loader to the sand box environment. Please advise whether this is expected behavior.

 

I have around 1K records to be updated, so is there anyway I can run a upsert operation for Campaigns.

 

Please help.

 

Regards,

Dpat

  • September 08, 2013
  • Like
  • 0

I am trying to add multiple markers to my google maps on my positions layout where you have a 1 to many with many addresses which i have to get plotted on the map. I tried the same Google api calls on an HTML page with JS calls and it worked.  When i am hardcoding the object names in my page and then call ,without the APEX :REPEAT tag it works again. dont know what is wrong. can someone look into this and tell if something stands out

 

<apex:page standardcontroller="Position__c">
<apex:pageBlock >
<head>
This map shows the locations of candidates who have applied for the {!Position__c.Name} position.....

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

   function initialize()
   {
        var myCenter = new google.maps.LatLng(40.825612,-74.402413);
        var myOptions = { center: myCenter, zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP };

        var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
        var geocoder = new google.maps.Geocoder();

        <apex:repeat var="ja" value="{!Position__c.nanlabs__Job_Applications__r}">
          counter++;
          var address = "{!ja.nanlabs__Candidate_Number__r.Street__c}, {!ja.nanlabs__Candidate_Number__r.City__c}, {!ja.nanlabs__Candidate_Number__r.State_Province__c}";
          geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK && results.length) {
              if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {      
               map.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                   // title: "{!ja.nanlabs__Candidate_Number__r.First_Name__c} + ' ' + {!ja.nanlabs__Candidate_Number__r.Last_Name__c}"
                });
                marker.setmap(map);
              }      
            }
          });
        </apex:repeat>
        
         if(counter == 0) {
         // Display map of US if no Candidates found
            var myPoint = new YGeoPoint(40,-95);
            map.drawZoomAndCenter(myPoint, 14);
            alert("There are no candidates for this position to map.");
        }
    }
  google.maps.event.addDomListener(window, 'load', initialize );
</script>
</head>

<body>
<div id="googleMap" style="width:100%;height:400px;"></div>
</body>
</apex:pageBlock>
</apex:page>

Hello.  I'm troubleshooting a custom grid editing VF page that was built by someone else.  I'm getting conflicting results when I look at View State vs. the system log.  Also I'm wondering what commandLink and commandButton do behind the scenes.
 
The grid displays custom related records to a Case record.  There is a delete commandLink on each row.  Clicking the delete link does not immediately delete the record - you need to click a Save commandButton to commit all changes and deletions.  The Save button is a pageBlockButton.
 
I have found that if there are 3 or more rows in the grid and I delete one row at or near the top and click Save to commit the changes, one field in all the rows below the deletion is updated with wrong information.  However, if I don't click Save, the data looks correct.
 
The field is Product and it is a lookup field to the Product object.
 
Example:
Step one:
Row 1, Product is A
Row 2, Product is B
Row 3, Product is C
Row 4, Product is D
Row 5, Product is E
 
Step two:
I delete Row 2 BUT I DO NOT CLICK SAVE.  The screen refreshes and I see, correctly:
Row 1, Product is A
Row 2, Product is C
Row 3, Product is D
Row 4, Product is E
 
Step three:
Now I click Save and the screen refreshes:
Row 1, Product is A
Row 2, Product is C
Row 3, Product is C
Row 4, Product is D
 
(Of course the controller is maintaining two lists - one of rows to display, and one of rows for DML deletion.)
 
Here are things I don't understand:
 
* In step 2, the view state show 5 items in the related record list, even though the system log shows only 4 items.  The system log show each item has the correct Product.  Why isn't the view state updated also, especially since I saw the page refresh?
 
* Why is the delete commandLink rerendering the screen in step 2?  Is that typical operation for commandLink?  The way it is built, it is calling a public void method in the controller, not a public PageReference, so there is no return statement in it.  I have not been able to find any explicit rerender in the controller method.
 
* I have created a dummy Save button that does nothing.  When I click the dummy button immediately after clicking the delete commandLink, I see in the system log that the Product are incorrect as in step 3 above.  I can't understand how that happens, since I see the correct values on the screen just before I click the dummy button, and the system log confirms it.
 
 

I'm new to VF and Apex programming, but making good progress in building some custom pages and classes by Googling a lot.  But one thing I'm still trying to better understand is the transfer of values between the web browser, VF page, and the backend Apex class.

 

For example, if I have an input text field on a VF page, when a user inputs a value, or changes a value, in that field, at what point is that value actually "set" in the variable in the Apex class, and available for computations?

 

New/changed values seem to get transferred and set upon some sort of page refresh, or action, but I'm having a hard time finding documentation on exactly how the transfer of data occurs.  Please note, I'm not assuming there's any special event processing occurring on the field (such as onblur, onchange, etc), just interested in basic field input/output and when the values actually get transferred.

 

I hope this question is making sense...

 

Is anything like this covered in any Apex or VF documentation that maybe I missed?

 

Thanks!

Hi,

I've tried this a few different ways to make this work, but have been unsuccessful. My company has multiple program years for our clients. Most times, we are interested in pulling reports that are specific to the client's current program year. Unfortunately, not all program years start on the same date, and don't last the same length of time. 


I thought, with a "Current Program Year" identifier (checkbox) I would solve this. I would eliminate the need for users to keep this field up to date by using a Field Update Workflow. However, I just can't get it to work. If anyone can help, I'd greatly appreciate it:

 

IF(AND (Program_Year_Start_Date__c < Today(), Program_Year_End_Date__c > Today()), Program_Year_Status__c = True, null)

 

 

IF(AND (Program_Year_Start_Date__c < Today(), Program_Year_End_Date__c > Today()), True, null)

 

 

Program Year Start Date and Program Year End date are what we are comparing. If today falls between these two dates, then we are in the client's current program year. Current Program Year (i.e.., Program Year Status) should then be checked.

 

The syntax appears to be correct, but the the workflow doesn't work.

 

 

 

  • February 08, 2013
  • Like
  • 0

We have our Admin trying to deploy permission sets and new fields on the Activity object via a change set. Every time he validates he runs into validation errors in a couple of our test classes. However, when I run the unit tests on the classes in Salesforce, I receive no errors. Plus, when we push that same change set to one of our development environments that has the same classes as production, we do not receive any errors in validation.

 

Has anyone seen this before? Does anyone know of a solution. Eclipse is a workaround, but we would like to fix this as soon as possible.

Hello everyone,
I have been struggling on this for 2 days. It looks simple and still I can not figured it out. Thanks in advance for your help.
I want to feed a PHP program from a VF page, and in particular from an <apex:form> / <apex:commandButton>
Thanks in advance for your help,
Jerome
The PHP program:
--------------------------
<?php
session_start();
$_SESSION['ndfsession']="";
?>
<html><head>
<title>nomdefamillephp</title>
</head>
<body>
<?php
$nomDeFamille =$_POST['PersonvNomDeFamille'];
?>
nomDeFamille is : <?php echo $nomDeFamille; ?>
</body>
</html>
------------------------------
My controller:
public with sharing class CCNPersonContExt {
Id id = ApexPages.currentPage().getParameters().get('id');
private Person__c Personv;
public Person__c getPersonM() {
if (Personv == null) { Personv = new Person__c() ;
personv = [SELECT Name, id, Nom_de_Famille__c FROM Person__c WHERE Id = :ApexPages.currentPage().getParameters().get('id') ]; }
return Personv;
}
public PageReference actionphp(){
PageReference actionphp = new PageReference('http://www.thehardyfamily.fr/ccnfrsb/php/nomdefamille.php');
return actionphp.setRedirect(true);
}
}
----------------------------
The VF page that works fine as long as the PHP is launched from a pure HTML form
<apex:page controller="CCNPersonContExt" sidebar="no" showHeader="no" id="CNbropersphp" >
<apex:outputField value="{!personM.Nom_De_famille__c}" id="of"/>
<form action="http://www.thehardyfamily.fr/ccnfrsb/php/nomdefamille.php" method="post" id="fmhtml">
<input name="PersonvNomDeFamille" value="{!personM.Nom_de_Famille__c}" type="hidden" id="ihhtml"/>
<input value="PHP" type="submit" id="suhtml" />
</form>
</apex:page>
------------------------------
The VP page that I would like to work but does not pass the value to the PHP priogram. What am I missing?
<apex:page controller="CCNPersonContExt" sidebar="no" showHeader="no" id="CNbropersphp" >
<apex:outputField value="{!personM.Nom_De_famille__c}" id="of"/>
<apex:form id="fm">
<input name="PersonvNomDeFamille" value="{!personM.Nom_de_Famille__c}" type="hidden" id="ihhtml"/>
<apex:commandButton action="{!actionphp}" value="PHP" id="btnphp" />
</apex:form>
</apex:page>
-------------------------------
Thanks again for your help.
Jerome

 

Hi.

 

I have a VF page that displays two date properties, which can be edited with the standard datepicker. I am setting these properties value to a default date but the when the page loads the text fields linked to them are showing me the dates formatted differently than what the datepicker is expecting (i guess?).

 

Controller:

public class slotMarcacaoController {
        
    public Date startDate { get; set; }
    public Date endDate { get; set; }
     
    public slotMarcacaoController(ApexPages.StandardController controller) {
        init();
    }
        
    public slotMarcacaoController (){
      init();
    }
    private void init(){
        startDate = Date.Today();
        endDate = startDate.addDays(7);        
    }
    
    public void reserveSlot(Integer index){
    
    }
    
    public PageReference refreshSlots(){
        //some code
        return null;
    }

    
    public Datetime lowerLimit {get; set;}
    public Datetime upperLimit {get; set;}
}

 

VF Page:

<apex:page standardController="Case" extensions="slotMarcacaoController" >

   <script type="text/javascript">
    
    window.onload=function() {
        focus('defaultFocus');     
    }
    
    function focus(id){
        document.getElementById(id).focus();
    }
  </script>
  
    <apex:form >
        <div>
            <span id="defaultFocus">Data Inicio</span>
            <apex:inputText style="position:relative; left:20px;" 
                label="Data Inicio" value="{!startDate}"
                onfocus="DatePicker.pickDate(true, this, true);" id="date1"> 
            </apex:inputText>
        </div>
        <div>
           <span>Data Fim</span>
           <apex:inputText style="position:relative; left:28px;"
               label="Data Fim" value="{!endDate}"
               onfocus="DatePicker.pickDate(false, this, false);" id="date2"/> 
        </div>
        <apex:commandButton action="{!refreshSlots}" value="Actualizar">
        </apex:commandButton>           
    </apex:form>
    
    <apex:outputText value="{!lowerLimit}"></apex:outputText><br/>
    <apex:outputText value="{!upperLimit}"></apex:outputText>
   
</apex:page>

After the page load the text fields for both dates are in the following format "Fri Feb 08 00:00:00 GMT 2013". When i choose the same date with the datepicker, they show it like "2/8/2013". How can i make it always display the date in the latter format? 

 

Thanks in advance.

I have an Apex class that is trying to get information from my custom object Invoice and send an email.

 

However, I get this error message:

SObject row was retrieved via SOQL without querying the requested field: Invoice__c.Invoice_Due_Date__c
Error is in expression '{!doMyApexLogic}' in component <apex:page> in page apexbuttonpage

 My code is here:

 

public class ApexButtonPageController {
    Invoice__c theInvoice;
    

    public ApexButtonPageController(ApexPages.StandardController stdController) {
        // get the current Invoice
        theInvoice = (Invoice__c)stdController.getRecord();
    }

    public PageReference doMyApexLogic() {
        //logic to send email out
        
        
        
        // First, reserve email capacity for the current Apex transaction to ensure
                        
// that we won't exceed our daily email limits when sending email after
                        
// the current transaction is committed.
Messaging.reserveSingleEmailCapacity(2);

// Processes and actions involved in the Apex transaction occur next,
// which conclude with sending a single email.

// Now create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'name@domain.com'}; 
  

// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);

// Specify the address used when the recipients reply to the email. 
mail.setReplyTo('test@test.com');

// Specify the name used as the display name.
mail.setSenderDisplayName('Billing');

// Specify the subject line for your email address.
mail.setSubject('Invoice');

// Set BCC as false
mail.setBccSender(false);

// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);


mail.setHtmlBody('Dear theInvoice.Email_Invoice_To__c <p>'+
     'Please find attached the invoice on your account that will be due on'+ theInvoice.Invoice_Due_Date__c+'.<p>'+
                'The invoice summary is as follows:<p>'+
'Account Name'+                      theInvoice.Account_Name__c+'<p>'+
'Contract Number'+                   theInvoice.Contract__c+'<p>'+

'Invoice Date'+                      theInvoice.Targeted_Date__c+'<p>'+
//'Invoice Due Date                  {!Invoice__c.Targeted_Date__c}<p>'+
//Invoice Number                    {!Invoice__c.Invoice__c}
//Invoice Amount                    USD {!Invoice__c.Amount_Invoiced__c}

'');

// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });      
        
        
        update theInvoice;
        //</demo logic>
        return new PageReference('/' + theInvoice.id);
    }
}

 

  • February 08, 2013
  • Like
  • 0

I'm having trouble retrieving values from multiple SObjects.

I have a Custom Object which has a Master-Detail relationship to Account.  Call it Object1.  I need to retrieve values from the Account which are lookup fields to the User Object.

 

Select account__r.Name, account__r.Account_Manager From Object  >this returns the account name and the userId of the Account Manager

 

I need to retrieve the Account Manager's name and e-mail

Select account__r.Account_Manager.Name, account__r.Account_Manager.email from Object1  > doesn't return anything.

 

I can retrieve the userId for the Account_Manager, but how do I then access the User fields for that Id?

 

Thanks! 

Hello Fellas,

 

I was advised to post here. Maybe you will be able to help.

I cannot get this trigger to work upon Data Loader Account upsert.

It works when I do the changes within the application (UI), but it does not when I change the account owner of using the Data Loader.  When I use the Data Loader to upsert account ownership, it changes ownership of ALL opportunities in ALL accounts no matter whether account owner for a particular opportunity has changed or not.

 

Objective: After A Data Loader account upsert - Check IF an owner of an opportunity is NOT the owner of the account and a sharing person of the account,
THEN change owner of that opportunity to the NEW owner of the account to which that opportunity pertains.


For this purpose there is a custom field in account called SLS2__c,  which is updated each time accounts are upserted. This field contains the 15 character SF UserID of the person who shares the account.

 

trigger updateOppOwner on Account (after insert, after update) {
  if (Trigger.isAfter) {
  Set<Id> acctIds = new Set<Id>();
    for (Account acct : Trigger.new) {
       acctIds.add(acct.Id);
       }    
 
    List<Opportunity> optyList = [SELECT OwnerId  FROM Opportunity WHERE AccountId in :acctIds];
    if ( !optyList.isEmpty() ) {
    for (Account acct : Trigger.new) {
        for(Opportunity opty : optyList ) {      
            if(opty.OwnerId != acct.OwnerId && opty.OwnerId != acct.SLS2__c){
               opty.OwnerId = acct.OwnerID;
                    } else {
                      opty.OwnerId = opty.OwnerId ;
           }
            }
        update optyList;
        }
    }
   }
}

 


Again, the trigger works when account ownership is changed manually, but when I use the Data Loader, it changes ownership of ALL opportunities in ALL accounts no matter whether account owner for a particular opportunity has changed or not.


Do you have any suggestions?

  • February 07, 2013
  • Like
  • 0

Seems like missing something obvious. The below statement is only updating the first field when its called from a Trigger. If I then edit the record and save, it updates the 2nd field. I obviously am expecting it to update both fields at once.

 

public class UpdateAddressTypeManager{


/* Updates value of AddressType record when received from SalesForce to SalesForce
Lookup fields cannot be mapped from Connections */

// Update Address value
public static void handleAddrProvUpdate(Address_Type__c[] addrtypes) {

// create a set of all the unique Remote Address ids
// Remote_AddressId__c stores text value of SalesForce Id for updating
Set<String> remoteaddr = new Set<String>();
Set<String> remoteprov = new Set<String>();
for(Address_Type__c at : addrtypes){
remoteaddr.add(at.Remote_AddressId__c);
remoteprov.add(at.Remote_ProviderId__c);
}
System.debug('RemoteAddr set = ' + remoteaddr);
System.debug('RemoteProv set = ' + remoteprov);

// create list of Address__c items with matching remote address id
List<Address__c> addrids = [Select Id, Remote_Address_Id__c From Address__c Where Remote_Address_Id__c in:remoteaddr];
List<Contact> provids = [Select Id, Remote_ProviderId__c From Contact Where Remote_ProviderId__c in:remoteprov];


// Verify size of address list
System.debug('AddressId size ' + addrids.size());

// Verify size of provider list
System.debug('ProviderId size ' + provids.size());

// creates map of Address_Type and Address for updating
Map<Address_Type__c,Id> addrmap = new Map<Address_Type__c,Id>();
Map<Address_Type__c,Id> provmap = new Map<Address_Type__c,Id>();

for(Address_Type__c at : addrtypes) {
For(Address__c ad : addrids) {
If(ad.Remote_Address_Id__c == at.Remote_AddressId__c)
addrmap.put(at,ad.id);
}
For(Contact cont : provids) {
If(cont.Remote_ProviderId__c == at.Remote_ProviderId__c)
provmap.put(at,cont.id);
}
}

System.debug('Address Map ' + addrmap);
System.debug('Provider Map ' + provmap);


// Only updating first field. If put in different order, still just does first one
for(Address_Type__c atupd : addrtypes){
atupd.Provider__c = provmap.get(atupd);
atupd.Address__c = addrmap.get(atupd);
}
}
}

 

Thanks,
Darrell

Hi,

 

I'm totally green with Apex trigger, and this is my first stab at writing one.  I'm trying to add this Opportunity trigger on NPSP to assign a Designation to an Opportunity transaction when it's created.  The trigger is created from Setup->Customize->Opportunity->Trigger.  DonationDesignationRelationship is a custom object, which has a master-detail relationship with Opportunity.

 

When I hit "Quick Save", I got this error:

 

Error: Compile Error: Invalid type: DonationDesignationRelationship at line 5 column 57 

 

It might be something really straighforward, but somehow I can't figure out.  The code is pretty simple:

 

// Add Designation to a brand new Opportunity

trigger OpportunityAddDesignation on Opportunity (after insert) {    

 

  List<DonationDesignationRelationship> ddrs = new List<DonationDesignationRelationship>();    

  if (Trigger.isInsert && Trigger.isAfter) {    

    for (Opportunity opp: Trigger.new) {      

      if (opp.Amount > 0) {        

        ddrs.add(new DonationDesignationRelationship 

           (Amount = opp.Amount, Designation = a18U000000BOP4r, Opportunity = opp.Id));      

      }    

    }  

  }  

  insert ddrs;

 

}

 

I'd really appreciate any help or pointers to accomplish this.

 

Thanks!

 

 

  • February 07, 2013
  • Like
  • 0