• Aviator517
  • NEWBIE
  • 35 Points
  • Member since 2013

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 17
    Questions
  • 10
    Replies

I'm trying to use the ConnectAPI to display a chatter feed in a Visualforce page, and have gotten most of it down but having issues display the authors picture. When I loop through the feed element, and access the feedelement.parent I get this output:

ConnectApi.UserSummary[buildVersion=34.0, additionalLabel=null, communityNickname=al1.358461640710149E12, companyName=Developerforce, displayName=Al Oht, firstName=Al, id=005i0000000M1YEAA0, isActive=true, isInThisCommunity=true, lastName=Ohrt, motif=ConnectApi.Motif[buildVersion=34.0, color=34BECD, largeIconUrl=/img/icon/profile64.png, mediumIconUrl=/img/icon/profile32.png, smallIconUrl=/img/icon/profile16.png, svgIconUrl=null], mySubscription=null, name=Al Oht, photo=ConnectApi.Photo[buildVersion=34.0, fullEmailPhotoUrl=https://na15.salesforce.com/img/userprofile/default_profile_200.png?fromEmail=1, largePhotoUrl=https://c.na15.content.force.com/profilephoto/005/F, photoVersionId=null, smallPhotoUrl=https://c.na15.content.force.com/profilephoto/005/T, standardEmailPhotoUrl=https://na15.salesforce.com/img/userprofile/default_profile_45.png?fromEmail=1, url=/services/data/v34.0/connect/communities/0DBi0000000GmdIGAS/chatter/users/005i0000000M1YEAA0/photo], reputation=null, title=null, type=User, url=/services/data/v34.0/connect/communities/0DBi0000000GmdIGAS/chatter/users/005i0000000M1YEAA0, userType=Internal] 

Which clearly shows data points for photo URL in the ConnectApi.Photo class, but am having issues accessing the data and displaying on the page. Has anyone encountered this issue?

If its a matter of processing further in the controller, I suppose that's fine...but would rather not if I don't have to.

Thanks!

We would like to have several Salesforce accounts that individually authorize access via Oauth2. It would be preferred to deploy a connected app and have the same id and secret, but given that we would not be selling this app and making a profit we prefer not to go the managed package route.

Is the only alternative to this to create a seperate connected app for each Saleforce instance, and setup the integration using the unique ID and Client Secret?
We are in the unique situation of managing multiple Salesforce accounts, but having very similar setups (custom objects, fields, apex code).

I'm trying to find the best way to maintain code between the Salesforce orgs in an efficient way. If we make an update to an apex class, we'd rather not have to go into each org and manually push an update. What do you guys recommend as the best approach?

Managed Package: We don't want the package to be public, and we won't be making a profit so it doesn't make sense to pay to have it on the AppExchange. Otherwise, this seems like the ideal scenario to take advantage of automatic pushing of updates.

Unmanaged Package: Seems to fit the bill, except for the workflow of updating code. Would we just have to install the updated unmanaged package onto each org (and the deployment process is smart enough to update and not replace the components?)

Force.com Migration tool: Also seems like a feasible option. Although I envision the same scenario in which pushing updates would be hard to do.

Anyone have advice for this scenario?
I'm working off of some code that I found on this blog:
http://prats23.wordpress.com/2014/04/27/salesforce-dynamically-addingdeleting-rows-in-visualforce/

To implement an "Add/Remove" functionality to a visualforce page. The trick is, I'd like to add the add/remove functionality to the Account level as well.

Currently, it is working with Contacts that are related to a single Account and it let's you create a datatable that you can have an add/remove button on each row. I'd like it to be that I can add/remove at the Account level as well. Here is the controller code:
 
public class addAttendee {
public Account accounts;
 public Contact del;
 public List<Contact> addattendeeList {get;set;}
 public List<Contact> delattendeeList {get;set;}
 public List<Contact> attendeeList {get;set;}
 public Integer totalCount {get;set;}
 public Integer rowIndex {get;set;}
 
 
 public List<Contact> delAttendees {get; set;} 
 public addAttendee(ApexPages.StandardController controller) {
 
 accounts = (Account)controller.getRecord();
 attendeeList = [Select id, firstName, LastName, Email, Phone from Contact where AccountId =: accounts.Id];
 totalCount = attendeeList.size();
 
 delattendeeList = new List<Contact>();
 delattendees = new List<Contact>();
 }
 
 public void addRow(){
 addattendeeList = new List<Contact>();
 attendeeList.add(new Contact(AccountId = accounts.Id));
 }
 
 public PageReference ave(){
 
 upsert attendeeList;
 delete delattendeeList;
 return (new ApexPages.StandardController(accounts)).view();
 } 
 
 public void deleteRow(){
 
 rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
 System.debug('row to be deleted ' + rowIndex );
 System.debug('row item to be deleted '+attendeeList[rowIndex]);
 del = attendeeList.remove(rowIndex);
 delattendeeList.add(del);
 
 }
 }

 
For a given record, how could I go about getting all the fields in that object (schema describe?) and back up field specific data for a record. The use case would be, if I deleted a record, could I backup all fields and associated values into a text file or something? Would want it to be scalable so that if I added a new field, I wouldn't have to modify the code everytime.
We are trying to integrate a callout to retrieve data and append to a record when inserted or updated. Given the limts of only 10 callouts per execution, we are trying to find a work around.

Initial thought was to have the trigger execute a batchable class to make the callouts, but it brings up the secondary issue of not having more than 5 batch jobs at a time. (

How would you guys handle? In the trigger, I could check if the list only contains 1-5 records and process normally, and if more than that then execute the batch class. But does this seem practical? What other limits might I be forgetting? I just want to make it will be scalable and won't break the first time we do a mass insert of a few thousand records.

I have this JSON parser class:

public class GoogleAPIParser {

    public class Address_components {
        public String long_name;
        public String short_name;
        public List<String> types;
    }

    public List<Results> results;
    public String status;

    public class Location {
        public Double lat;
        public Double lng;
    }

    public class Geometry {
        public Location location;
        public String location_type;
        public Viewport viewport;
    }

    public class Results {
        public List<Address_components> address_components;
        public String formatted_address;
        public Geometry geometry;
        public List<String> types;
    }

    public class Viewport {
        public Location northeast;
        public Location southwest;
    }

   
    public static GoogleAPIParser parse(String json) {
        return (GoogleAPIParser) System.JSON.deserialize(json, GoogleAPIParser.class);
    }

}

Which I invoke using:

GoogleAPIParser parser = GoogleAPIParser.parse(jsonResponse);

 

How do I go through and access those attributes within the class that is returned now?

I have this JSON code, that I'd like parsed within and apex controller and displayed on a Visualforce page.

{"Object1":[{"id":1,"name":"SomeName"}],"Object2":[{"id":1,"location":"SomeLocation"}]}

I feel like this should be fairly simple, but can't get it to work. Can anyone point me in the right direction?
I'm having trouble wrapping my head around the json parser, and getting it work to a fairly simple JSON string.

{
 "Object1":[{"id":1,"name":"SomeName"}],
 "Object2":[{"id":1,"location":"SomeLocation"}]
}

Basically, I'd like to parse through the JSON and seperate the two objects and display some of the attributes on a visualforce page. If I create two classes like so:

public class Object1 {
        public Integer id;
        public String name;
    }
public class Object2 {
        public Integer id;
        public String location;
    }

How can I run through the Json and create an instance of each class?

I am working on this code to send an email with an .ics attachment, everything seems to be working ok, except the Description in the .ics attachment is not populating. Could anyone advise on why that might be? Thanks in advance for the help!

 

public class AttendeeConfirmationEmail{
    public static void sendEmail(List<Attendee__c> Attendees) {
List<Attendee__c> attendeelist = [Select ID, Training_Event__r.Start_Date_Time__c, Training_Event__r.End_Date_Time__c, Training_Event__r.Location__c, Contact__r.Email, Contact__r.FirstName, Contact__r.LastName, Training_Event__r.Name, Confirmation_email_sent__c, Training_Event__r.Webinar_Dial_in__c, Training_Event__r.Webinar_Access_Code__c, Training_Event__r.Webinar_Info__c From Attendee__c Where Status__c = 'RSVP - Yes' AND Id in :Attendees];
List<Attendee__c> attendeeupdate = New List<Attendee__c>(); OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'test@email.org']; List<Messaging.SingleEmailMessage> EmailList = New List<Messaging.SingleEmailMessage>(); for(Attendee__c a : attendeelist){ if(a.Confirmation_email_sent__c == False){ DateTime startDate = a.Training_Event__r.Start_Date_Time__c; String formatted_startDate = startDate.format('yyyyMMdd\'T\'Hmm\'00\''); String formatted_startDateII = startDate.format('MMMM d, yyyy \'at\' h:mma'); DateTime endDate = a.Training_Event__r.End_Date_Time__c; String formatted_endDate = endDate.format('yyyyMMdd\'T\'Hmm\'00\''); String dialin = a.Training_Event__r.Webinar_Dial_in__c; String accesscode = a.Training_Event__r.Webinar_Access_Code__c; String location = a.Training_Event__r.Location__c; String body = + 'Thank you for registering for ' + a.Training_Event__r.Name + ' on ' + formatted_startDateII + '. ' + 'The training will be held at ' + a.Training_Event__r.Location__c + '. ' + 'To cancel and/or register for a different training session, please email test@email.org' +(a.Training_Event__r.Webinar_Dial_in__c == Null ? '' : (' \r\n' + ' \r\n' + 'Conference Dial-in Number:' + ' ' + a.Training_Event__r.Webinar_Dial_in__c)) +(a.Training_Event__r.Webinar_Access_Code__c == Null ? '' : (' \r\n' + 'Participant Access Code:' + ' ' + a.Training_Event__r.Webinar_Access_Code__c)) + ' \r\n' + ' \r\n' + 'Best,' + ' \r\n' + 'Training Team'; String subject = a.Training_Event__r.Name + ' confirmation'; String fromAddress = 'test@email.org'; String displayName = a.Contact__r.FirstName + ' ' + a.Contact__r.LastName; String toAddress = a.Contact__r.Email; if(toAddress != null){ String attachmentName = 'Meeting.ics'; Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage(); msg.setOrgWideEmailAddressId(owea.get(0).Id); msg.setToAddresses(new String[] {toAddress}); msg.setSubject(subject); msg.setUseSignature(false); msg.setPlainTextBody(body); Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); efa.setFileName(attachmentName ); Blob b = doIcsAttachment(formatted_startDate, formatted_endDate, location, body, subject, fromAddress, displayName, toAddress, dialin, accesscode); efa.setBody(b); msg.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); a.Confirmation_email_sent__c = True; attendeeupdate.add(a); EmailList.add(msg); } } } system.debug('Email list size: ' + EmailList.size()); if(EmailList.size()>0){ Messaging.SendEmailResult[] results = Messaging.sendEmail(EmailList); } if(attendeeupdate.size()>0){ update attendeeupdate; } } private static Blob doIcsAttachment(String formatted_startDate, String formatted_endDate, String location, String body, String subject, String fromAddress, String displayName, String toAddress, String dialin, String accesscode) { // Now Contruct the ICS file String [] icsTemplate = new List<String> {'BEGIN:VCALENDAR', 'PRODID:-//Schedule a Meeting', 'VERSION:2.0', 'METHOD:REQUEST', 'BEGIN:VEVENT', 'DTSTART: ' + formatted_startDate, 'DTSTAMP: '+ String.valueof(DateTime.Now()), 'DTEND: ' + formatted_endDate, 'LOCATION: ' + location, 'UID: ' + String.valueOf(Crypto.getRandomLong()), 'DESCRIPTION: ' + dialin, 'X-ALT-DESC;FMTTYPE=text/html: ', 'SUMMARY: ' + subject, 'ORGANIZER:MAILTO: ' + fromAddress, 'ATTENDEE;CN="' + displayName + '";RSVP=TRUE:mailto: ' + toAddress, 'END:VEVENT', 'END:VCALENDAR' }; String attachment = String.join(icsTemplate, '\n'); return Blob.valueof(attachment); } }

 

I'm trying to send a basic email from apex, and have defined the "ReplyTo" to an address, but everytime I send a test email, the reply email is the email associated with my account.

 

Here is a bit of the code:

                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();

                msg.setReplyTo('testemail@gmail.com');
                msg.setSenderDisplayName(displayName);
                msg.setToAddresses(new String[] {toAddress});
                msg.setSubject(subject);
                msg.setPlainTextBody(body);

                EmailList.add(msg);

 

Is there some quirk with the sandbox that doesn't allow the replyto email address to be assigned?

I'm trying to code (what would seem to be) a fairly simple trigger, but I keep getting hung up on how to conceptualize it.

 

There is a checkbox on contact called "Primary" for each account, I want to enforce that each account has one contact that is primary.

 

So, I want to enforce changing the primary by checking the box on the new contact, and the code go through and uncheck the previous primary record.

 

Then I want to run validation that will give an error if there are no contacts with it checked, or if there are two and display the error to the user. I'm assuming I would process the contacts being inserted or updated in a before trigger, then process validation in an after trigger. But, in the after trigger would it see the changes I made in the before trigger to know that a new contact has been made primary?

 

If someone could help me with the rough framework on what this would look like, I'd very much appreciate it!

 

Thanks.

I found this article online which shows how to create a visualforce email template, that can send an email with an ics attachment.

 

http://developer.force.com/cookbook/recipe/creating-email-templates-and-automatically-sending-emails

 

<messaging:emailTemplate subject="Received your resume" 
    recipientType="Contact" relatedToType="Job_Application__c">

<messaging:plainTextEmailBody >
Dear {!relatedTo.Candidate__r.First_Name__c}  
        {!relatedTo.Candidate__r.Last_Name__c}

Thank you for your interest in the position 
        {!relatedto.Position__r.name}

We would like to invite you for an interview. 
Please respond to the attached invitation.

Regards,
Company
</messaging:plainTextEmailBody>


<messaging:attachment filename="meeting.ics" 
        renderAs="text/calendar; charset=UTF-8; method=REQUEST">
BEGIN:VCALENDAR
METHOD:REQUEST
BEGIN:VTIMEZONE
TZID:(GMT-08.00) Pacific Time (US and Canada)
BEGIN:STANDARD
DTSTART:16010101T020000
TZOFFSETFROM:-0700
TZOFFSETTO:-0800
RRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=11;BYDAY=1SU
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:16010101T020000
TZOFFSETFROM:-0800
TZOFFSETTO:-0700
RRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=3;BYDAY=2SU
END:DAYLIGHT
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20090921T202219Z
DTSTART;TZID="(GMT-08.00) Pacific Time 
        (US and Canada)":20090923T140000
SUMMARY:Invitation: Interview Schedule @ Wed Sep 23 2pm - 4pm 
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;
        CN="{!recipient.name}":MAILTO:{!recipient.email}
ORGANIZER;CN="John.Smith":MAILTO:recruiter@company.com
LOCATION:Hawaii 
DTEND;TZID="(GMT-08.00) Pacific Time 
        (US and Canada)":20090923T160000
DESCRIPTION: You are invited to an inverview
        \NInterview Schedule
        \NWed Sep 23 2pm - 4pm 
        (Timezone: Pacific Time) \NCalendar: John Smith 
        \N\NOwner/Creator: recruiter@company.com   
        \NYou will be meeting with these people:
        CEO Bill Jones, 
        Office Manager Jane Jones
\N
SEQUENCE:0
PRIORITY:5
STATUS:CONFIRMED
END:VEVENT
END:VCALENDAR

</messaging:attachment>

</messaging:emailTemplate>

 

 

The problem I'm running into is assigning the DTSTART and DTEND values from a Date/Time field on a record. When I put the field there, I don't think it's in the correct format, and even if it was, I think it's showing as GMT.

 

Does anyone have advice or have worked with something like this in the past?

 

Thanks!

I'm getting a weird issue with this bit of code. It's a visualforce controller, and on the visualforce page I have fields to insert/update 2 contact records. At the end I want one of the contact records, to be populated in a contact lookup on the 2nd contact page.

 

Here is the code:

public with sharing class ReferralFormController {
    Contact referrer;
    Contact candidate;
    List<SelectOption> referreroptions;
    
    public ReferralFormController() {
    // blank constructor
    }
    
    // the contact record you are adding values to
    public Contact getReferrer() {
        Id id = ApexPages.currentPage().getParameters().get('id');
        referrer = (id == null) ? new Contact() :
            [SELECT FirstName, LastName, Title, Personal_Email__c, Work_Email__c FROM Contact WHERE Id = :id];
        return referrer;    
    }
    public Contact getCandidate() {
        if(candidate == null) candidate = new Contact();
        return candidate;    
    }

    // save button is clicked
    public PageReference save() {
        try {
            Contact existingref = New Contact();
                for(Contact refchecker : [Select ID, FirstName, LastName, Title, Personal_Email__c, Work_Email__c
                                          From Contact
                                          Where Work_Email__c = :referrer.Work_Email__c OR
                                                Personal_Email__c = :referrer.Personal_Email__c OR
                                                (FirstName = :referrer.FirstName AND LastName = :referrer.LastName)
                                          LIMIT 1]){
                    existingref = refchecker;
                }
                if(existingref.Id != Null){
                    existingref.Title = 'Referrer Found!';
                update existingref;
                }
                if(existingref.Id == Null){
                    referrer.AccountId = '001L000000GFQip'; //change this when deploying to production!
                insert referrer;
                }
            Contact existingcan = New Contact();
            system.debug('CanFirstName =' + candidate.FirstName + 'CanLastName =' +candidate.LastName);
                for(Contact canchecker : [Select ID, FirstName, LastName, Title, Personal_Email__c, Work_Email__c  
                                          From Contact
                                          Where Work_Email__c = :candidate.Work_Email__c OR
                                                Personal_Email__c = :candidate.Personal_Email__c OR
                                                (FirstName = :candidate.FirstName AND LastName = :candidate.LastName)
                                          LIMIT 1]){
                    existingcan = canchecker;
                }
                system.debug('existing can =' + existingcan);
                if(existingcan.Id != Null){
                    existingcan.Title = 'It works a last time!';
                    if(existingcan.Referral_1__c == Null && existingref.Id != Null){
                        existingcan.Referral_1__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c == Null && existingref.Id == Null){
                        existingcan.Referral_1__c = referrer.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id != Null){
                        existingcan.Referral_2__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id == Null){
                        existingcan.Referral_2__c = referrer.id;
                    }
                update existingcan;
                }
                if(existingcan.Id == Null){
                    candidate.AccountId = '001L000000GFQip'; //change this when deploying to production!
                    if(existingcan.Referral_1__c == Null && existingref.Id != Null){
                        existingcan.Referral_1__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c == Null && existingref.Id == Null){
                        existingcan.Referral_1__c = referrer.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id != Null){
                        existingcan.Referral_2__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id == Null){
                        existingcan.Referral_2__c = referrer.id;
                    }
                insert candidate;
                }
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new contact.'));
      return null;
    }
    // if successfully inserted new contact, then displays the thank you page.
    return Page.referralthankyou;
  }
}

 

Not sure how the code as it currently stands (though probably very inneffient, so advice on improving would be great) could have the possibility to have a record reference itself?

 

Any help would be MUCH appreciated!

I"m trying to build a visualforce page, where I'd like a user to input information. When they hit submit, I'd like it to query the database to check if the record exists (based on values like FirstName or Lastname), and if not, create a new record. I can't seem to find a decent example online to help me work through this, does anyone have advice? Thanks, Alix
I'm running into recursive issues when designing code to enforce having at least 1 contact within a household to have "Head of Household" checked. Does anyone have any advice when working with something like this in the past? The code should be such that there is always someone designated "Head of Household" and can be changed at any point, but there can never be two. The problem comes in when I have 2 more contacts, with one set as the head of household. I then go to the other contact, to select the check box (which should go through and uncheck the other contact), but it gets in a loop where it keeps going back and forth updating each other. It seems to be an issue with dealing with not allowing the end user to uncheck a checkbox, but then in the code I should be able to uncheck it (to facilitate changing the head of household). Any friendly advice would be greatly appreciated.
Say we want to deploy an apex trigger that acts as a counter, but we are deploying it into an existing org. What is the best way to update all the existing records to reflect the accurate count? I'm assuming since they won't have triggered the apex code, that the counter wont reflect accurately. Thanks!

I have this JSON parser class:

public class GoogleAPIParser {

    public class Address_components {
        public String long_name;
        public String short_name;
        public List<String> types;
    }

    public List<Results> results;
    public String status;

    public class Location {
        public Double lat;
        public Double lng;
    }

    public class Geometry {
        public Location location;
        public String location_type;
        public Viewport viewport;
    }

    public class Results {
        public List<Address_components> address_components;
        public String formatted_address;
        public Geometry geometry;
        public List<String> types;
    }

    public class Viewport {
        public Location northeast;
        public Location southwest;
    }

   
    public static GoogleAPIParser parse(String json) {
        return (GoogleAPIParser) System.JSON.deserialize(json, GoogleAPIParser.class);
    }

}

Which I invoke using:

GoogleAPIParser parser = GoogleAPIParser.parse(jsonResponse);

 

How do I go through and access those attributes within the class that is returned now?

I'm having trouble wrapping my head around the json parser, and getting it work to a fairly simple JSON string.

{
 "Object1":[{"id":1,"name":"SomeName"}],
 "Object2":[{"id":1,"location":"SomeLocation"}]
}

Basically, I'd like to parse through the JSON and seperate the two objects and display some of the attributes on a visualforce page. If I create two classes like so:

public class Object1 {
        public Integer id;
        public String name;
    }
public class Object2 {
        public Integer id;
        public String location;
    }

How can I run through the Json and create an instance of each class?

I'm trying to send a basic email from apex, and have defined the "ReplyTo" to an address, but everytime I send a test email, the reply email is the email associated with my account.

 

Here is a bit of the code:

                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();

                msg.setReplyTo('testemail@gmail.com');
                msg.setSenderDisplayName(displayName);
                msg.setToAddresses(new String[] {toAddress});
                msg.setSubject(subject);
                msg.setPlainTextBody(body);

                EmailList.add(msg);

 

Is there some quirk with the sandbox that doesn't allow the replyto email address to be assigned?

I'm trying to code (what would seem to be) a fairly simple trigger, but I keep getting hung up on how to conceptualize it.

 

There is a checkbox on contact called "Primary" for each account, I want to enforce that each account has one contact that is primary.

 

So, I want to enforce changing the primary by checking the box on the new contact, and the code go through and uncheck the previous primary record.

 

Then I want to run validation that will give an error if there are no contacts with it checked, or if there are two and display the error to the user. I'm assuming I would process the contacts being inserted or updated in a before trigger, then process validation in an after trigger. But, in the after trigger would it see the changes I made in the before trigger to know that a new contact has been made primary?

 

If someone could help me with the rough framework on what this would look like, I'd very much appreciate it!

 

Thanks.

I'm getting a weird issue with this bit of code. It's a visualforce controller, and on the visualforce page I have fields to insert/update 2 contact records. At the end I want one of the contact records, to be populated in a contact lookup on the 2nd contact page.

 

Here is the code:

public with sharing class ReferralFormController {
    Contact referrer;
    Contact candidate;
    List<SelectOption> referreroptions;
    
    public ReferralFormController() {
    // blank constructor
    }
    
    // the contact record you are adding values to
    public Contact getReferrer() {
        Id id = ApexPages.currentPage().getParameters().get('id');
        referrer = (id == null) ? new Contact() :
            [SELECT FirstName, LastName, Title, Personal_Email__c, Work_Email__c FROM Contact WHERE Id = :id];
        return referrer;    
    }
    public Contact getCandidate() {
        if(candidate == null) candidate = new Contact();
        return candidate;    
    }

    // save button is clicked
    public PageReference save() {
        try {
            Contact existingref = New Contact();
                for(Contact refchecker : [Select ID, FirstName, LastName, Title, Personal_Email__c, Work_Email__c
                                          From Contact
                                          Where Work_Email__c = :referrer.Work_Email__c OR
                                                Personal_Email__c = :referrer.Personal_Email__c OR
                                                (FirstName = :referrer.FirstName AND LastName = :referrer.LastName)
                                          LIMIT 1]){
                    existingref = refchecker;
                }
                if(existingref.Id != Null){
                    existingref.Title = 'Referrer Found!';
                update existingref;
                }
                if(existingref.Id == Null){
                    referrer.AccountId = '001L000000GFQip'; //change this when deploying to production!
                insert referrer;
                }
            Contact existingcan = New Contact();
            system.debug('CanFirstName =' + candidate.FirstName + 'CanLastName =' +candidate.LastName);
                for(Contact canchecker : [Select ID, FirstName, LastName, Title, Personal_Email__c, Work_Email__c  
                                          From Contact
                                          Where Work_Email__c = :candidate.Work_Email__c OR
                                                Personal_Email__c = :candidate.Personal_Email__c OR
                                                (FirstName = :candidate.FirstName AND LastName = :candidate.LastName)
                                          LIMIT 1]){
                    existingcan = canchecker;
                }
                system.debug('existing can =' + existingcan);
                if(existingcan.Id != Null){
                    existingcan.Title = 'It works a last time!';
                    if(existingcan.Referral_1__c == Null && existingref.Id != Null){
                        existingcan.Referral_1__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c == Null && existingref.Id == Null){
                        existingcan.Referral_1__c = referrer.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id != Null){
                        existingcan.Referral_2__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id == Null){
                        existingcan.Referral_2__c = referrer.id;
                    }
                update existingcan;
                }
                if(existingcan.Id == Null){
                    candidate.AccountId = '001L000000GFQip'; //change this when deploying to production!
                    if(existingcan.Referral_1__c == Null && existingref.Id != Null){
                        existingcan.Referral_1__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c == Null && existingref.Id == Null){
                        existingcan.Referral_1__c = referrer.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id != Null){
                        existingcan.Referral_2__c = existingref.id;
                    }
                    if(existingcan.Referral_1__c != Null && existingref.Id == Null){
                        existingcan.Referral_2__c = referrer.id;
                    }
                insert candidate;
                }
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new contact.'));
      return null;
    }
    // if successfully inserted new contact, then displays the thank you page.
    return Page.referralthankyou;
  }
}

 

Not sure how the code as it currently stands (though probably very inneffient, so advice on improving would be great) could have the possibility to have a record reference itself?

 

Any help would be MUCH appreciated!

I"m trying to build a visualforce page, where I'd like a user to input information. When they hit submit, I'd like it to query the database to check if the record exists (based on values like FirstName or Lastname), and if not, create a new record. I can't seem to find a decent example online to help me work through this, does anyone have advice? Thanks, Alix
I'm running into recursive issues when designing code to enforce having at least 1 contact within a household to have "Head of Household" checked. Does anyone have any advice when working with something like this in the past? The code should be such that there is always someone designated "Head of Household" and can be changed at any point, but there can never be two. The problem comes in when I have 2 more contacts, with one set as the head of household. I then go to the other contact, to select the check box (which should go through and uncheck the other contact), but it gets in a loop where it keeps going back and forth updating each other. It seems to be an issue with dealing with not allowing the end user to uncheck a checkbox, but then in the code I should be able to uncheck it (to facilitate changing the head of household). Any friendly advice would be greatly appreciated.

I'm trying to create a very simple visualforce form, that just doesn't seem to be working and I don't know why

 

VF:

<apex:page controller="SubmitReferralController" standardStylesheets="false" showHeader="false" sidebar="false">
    <apex:stylesheet value="{!$Resource.semantic}"/>
<html lang="en">
<head>
</head>
<body>
<div style="margin-left:200px">    
<h1>Referrals Fee Program</h1>
<p>
  Any questions? Contact the <a href="semantic-form.css">Referral team</a>.
</p>
</div>
<apex:form styleClass="semantic"> 
<apex:pageBlock >
<div style="margin-left:200px">
<apex:outputPanel >
    <div>
      <apex:outputlabel Value="First Name"></apex:outputlabel>
      <apex:inputText value="{!c.FirstName}" size="30" id="referrer_first_name"/>
      <apex:outputlabel Value="Last Name"></apex:outputlabel>
      <apex:inputText value="{!c.LastName}" size="30" id="referrer_last_name"/>
     </div>
<div style="margin-left:200px">
<apex:commandButton value="Submit Referral" action="{!submitReferral}"/>
</div>
</apex:outputPanel>
</div>
</apex:pageBlock>
</apex:form>         
</body>
</html>
</apex:page>

 Controller:

public class SubmitReferralController {
    
    public Contact c { get; set; }
    
    public PageReference submitReferral(){
        try {
        insert c;
       }
       catch(System.DMLException e) {
           ApexPages.addMessages(e);
       return null;
       }
       return null;
     }
}

 

I'm sure it's something really stupid, but I just can't sort it out.

 

Any help would be greatly appreciated!