1

This is for a public site I'm building.

So I'm sending a parameter to check and see if a URL parameter is valid. However, every time the send a parameter that is not found the page redirects me to an Authorization Required Page.

Below is my code to grab the parameter then the getContactFound method which the page only loads when the contact is correct.

What is the return valud for getContactID when the parameter is not found

public String getContactID(){
        return System.currentPageReference().getParameters().get('contactID');
    }  

Why is the function not working when the parameter is not found

public boolean getContactFound(){

        if (getContactID() == null || getContactID().length() == 0){
            return false;
        }
        Id caster = Id.valueOf(getContactID());
        Contact C = [SELECT Id FROM Contact where id =: caster];

        if (C == null){
            return false;
        }else{
            return true;            
        }

}

Any ideas as to what is wrong?

1 Answer 1

2

If there is no contactID parameter then your getContactID will return null.

If there is a contactID parameter that is not a valid ID then Id.valueOf will throw a StringException.

If the contactID parameter is a valid ID but not a Contact ID then the Contact C = ... assignment will fail with a QueryException because there are no rows and that style of assignment requires exactly one row.

SOQL does not throw an error when you bind a string that is not an ID in a where term so you can skip the conversion to the ID and just check how many rows the query returns:

public boolean getContactFound() {

    String idString = getContactID();
    if (idString == null) return false;

    Integer count = [SELECT count() FROM Contact where Id = :idString];
    return count == 1;
}

(A SOQL query that returns SObjects returns zero or more SObjects in a list; a null is never returned in place of an SObject.)

3
  • So I updated my code to use counts instead of checking for Nulls. However, when I call the function, if the contact is there it works perfect. If not, the page says the URL is bad
    – tjcinnamon
    Commented Mar 29, 2016 at 17:21
  • Oh my gosh! It was because I was trying to set a contact ID to a contact that didn't exist yet!
    – tjcinnamon
    Commented Mar 29, 2016 at 17:25
  • 2
    @tjcinnamon Glad you figured it out.
    – Keith C
    Commented Mar 29, 2016 at 17:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .