5

I am trying to have a custom object link to other objects without specifying a type. By that I mean I want to make something like an "OtherObject" lookup without specifying the type, so that I can link it to any object type. However, this does not seem to be available in Salesforce.

What I am doing as a replacement is I store the record ID of the other object. However, the problem is I need a way to check if that record still exists when I attempt to fetch data using that ID.

Get SObject by Id

seems to be only usable if you have a valid ID, is there any apex method that lets you do something similar with a String or something that may or may not be an existing ID?

1 Answer 1

9

You just need to make an Id instance from your String value, which you can do with Id.valueOf(stringValue). If you want to simply get a Boolean whether or not a corresponding record exists, you can do:

public Boolean doesRecordExist(String value)
{
    Id recordId;
    try { recordId = Id.valueOf(value); }
    catch (StringException e) { return false; }
    String soql = 'SELECT count() FROM ' +
        recordId.getSObjectType() +
        ' WHERE Id = :recordId';
    return Database.countQuery(soql) == 1;
}

If you'd like to avoid try catch block, use instanceof method as value instanceof Id

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.