4

While moving code from developer org to packaging org using ANT in few places of the apex code we need to prefix the packaging namespace. Is there any way to automate this process?

For instance:

RecordType Test = [
    SELECT Id, Name
    FROM RecordType
    WHERE SobjectType = 'abc__books__c'
    AND DeveloperName = 'bookreview'
]; 

In the above code abc is the namespace which is added manually.

2 Answers 2

5

There are several ways to achieve this:

  1. Querying the namespaceprefix. You can perform query on ApexClass to find if namespace exist or not. eg. ApexClass cs =[select NamespacePrefix from ApexClass where Name =:'<name of the class from your package>'];

  2. Create a field in custom setting(Hierarchy) which will contain the namespaceprefix. Hierarchy type custom setting record can be retrieved without using queries.

  3. One more nice approach is using custom metadata types. Actually they have namespaceprefix standard field which auto populates in namespaced environment.With custom metadata types, you can issue unlimited Salesforce Object Query Language (SOQL) queries for each Apex transaction.

6
  • 1
    Nice to see your contributions on here. :)
    – Adrian Larson
    Jun 15, 2016 at 5:46
  • 2
    Another benefit of hierarchy settings is they can be used in merge fields. Could be useful for dynamic Visualforce, perhaps.
    – Adrian Larson
    Jun 15, 2016 at 5:48
  • Thanks for your answer. Could you please let me know, how it inject into the problem asked by @Namarta. Jun 15, 2016 at 5:51
  • Exactly the way you did @anurag. Here you will grab the namespace dynamically and not from any class.Because it is not sure the code is executing in a namespaced environment or non-namespaced one.
    – Mr.Frodo
    Jun 15, 2016 at 5:58
  • Thanks for the response. Can you please suggest me any documents or links which gives me knowledge about custom metadata types and namespaceprefix @Mr.Frodo
    – user31035
    Jun 15, 2016 at 9:08
1

I think you need to create a common class where you declare the namespace as private variable like this:

private static String NAMESPACE_PREFIX='abc';

Then you use this variable wherever you need this prefix like in your case:

String sObject = NAMESPACE_PREFIX+'books__c'; String devName = books; String qry = '[select Id,Name from RecordType where SobjectType = :sObject and DeveloperName = :devName]

Hope it helps you

You must log in to answer this question.

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