function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Aviator517Aviator517 

Apex custom controller

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
Best Answer chosen by Admin (Salesforce Developers) 
CheyneCheyne

You could search for the different conditions using OR. Something like

 

[SELECT Id FROM Contact WHERE WorkEmail = :email OR PersonalEmail = :email OR (FirstName = :firstName AND LastName = :lastName)]

 

All Answers

CheyneCheyne

Try something like this, of course substituting for your object/fields.

 

Apex Class

public class MyController {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String val) {
        name=val;
    }

    public PageReference save() {
//This is where you check if the account already exists if ([SELECT Id FROM Account WHERE Name = :this.Name].size() == 0) { Account acct = new Account(Name=this.name); insert acct; } else { System.debug('Account already exists'); } return null; } }

 Visualforce Page

<apex:page controller="MyController">
  <apex:form>
      <apex:inputText value="{!name}"/>
      <apex:commandButton action="{!save}"/>
  </apex:form>
</apex:page>

 

Aviator517Aviator517

Thanks! I think this is what I was looking for. What is the best way to handle multiple conditions in which I'd like to match a record?

 

For example:

  • Match on work email
  • If not then, match on personal email
  • If not then, match on First name, Last name, organization or something like that.

Is there an efficient way without doing multiple SOQL queries? Thank you!

CheyneCheyne

You could search for the different conditions using OR. Something like

 

[SELECT Id FROM Contact WHERE WorkEmail = :email OR PersonalEmail = :email OR (FirstName = :firstName AND LastName = :lastName)]

 

This was selected as the best answer