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?

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.)

| improve this answer | |
  • 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 Mar 29 '16 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 Mar 29 '16 at 17:25
  • 2
    @tjcinnamon Glad you figured it out. – Keith C Mar 29 '16 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.