New answers tagged

0

First principles - don't put your whole SOQL on 1 line - too hard to read/debug If you have shared activities enabled, you'll need to query from Contact via relationship TaskRelations and because TaskRelation has a lookup field to the Task, you can filter on the TaskRelation that has the most recent Task.LastModifiedDate return [SELECT Id,Firstname,...


0

As suggested by @DavidCheng - Created a new Custom Metadata Type Setting (CMDTS) Created a field RoleId Created a new record where RecordName = 'Role Name' RoleId = 'copied and pasted roleid' Queried the CMDTS record String CSR_RoleID = [select RoleId__c from Id_Store__mdt Where DeveloperName = 'Customer_Support_Rep'].RoleId__c; system.debug('>>...


3

Personally, I would suggest that the solution is to be aware of the pitfalls of changing the Developer/API name of anything on the platform, and then not to do it. Change the label by all means, but not the API name, as only problems will ensue. There are plenty of examples where Salesforce themselves have changes the name of something (Wave -> Einstein ...


0

You have to create a new Entitie with the following REGEX code as a patern ^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[...


0

This may be related to the View All Data permission. Can you try with a non Sys Admin profile that has View All Data enabled? Faced this issue with EmailMessage object, so I'm guessing the root cause should be similar.


3

You need at least one indexed field in order to avoid expensive table scans, and potentially query timeout problems or non-selective query errors. You have two real options. First, use your first option. The OR operator will be just fine, as long as you're not filtering for null. The second option is to use the formula field, but request a custom index. ...


0

You can use Relationship queries like: for Normal Lookup fields: SELECT Amount, Id, Name, (SELECT Quantity, ListPrice, PriceBookEntry.UnitPrice, PricebookEntry.Name, PricebookEntry.product2.Family FROM OpportunityLineItems) FROM Opportunity for Polymorphic Lookup fields: SELECT TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN ...


0

Using query editor, I don't think you can get a list of all user names and their groups in a single query. You can query each group separately, one query for each group SELECT Id, FirstName, LastName FROM User WHERE Id IN (SELECT UserorGroupId FROM GroupMember WHERE group.Name='YourGroupName') AND isActive = true Or if you want a list of all groups and ...


0

Try this, lstusers = [ SELECT Id ,Name FROM User LIMIT 200 ]; List<GroupMember> = [ SELECT Id ,Group.Name ,Group.Type ,UserOrGroupId ,Group.Id FROM GroupMember WHERE UserOrGroupId IN :lstusers AND Group.Name = 'MyPublicGroup' ];


0

Please try the below steps. Run the below SOQL to get the PermissionSet Id. SELECT Id, Profile.Name FROM PermissionSet WHERE Profile.Name = 'System Administrator' Use the PermissionSet Id from the step 1 and use it in the below SOQL for ParentId. SELECT Name FROM ApexClass WHERE Id IN ( SELECT SetupEntityId FROM SetupEntityAccess WHERE ParentId = '...


2

Parent references are not an Array, but a simple Object. No need to use [0]. row.Tasks[0].Owner.Name


0

I had the exact same problem and I found the solution as a scheduled apex batch class only. Batch Class global class BatchLoginData implements Database.Batchable<sObject>{ public string sQuery; public string ProfID = '00e5w000000k5JMAAY'; global Database.Querylocator start (Database.BatchableContext BC){ sQuery = 'SELECT Id, ...


2

You are going to have to post process the result - the owner name is there, but you will need to iterate through the array to extract it. The reason you can't see it is because the query viewer is not capable of showing deeply nested objects - you need to serialize it to JSON and then examine that. I wrote this little query to get the output below: Contact[] ...


2

You would need to enable 'Track Field History checkbox' under object settings. Select Object Manager--> Click the custom object (Teacher__c) and click Edit--->Under Optional Features, select the Track Field History checkbox. Later add Custom object History (Teacher__c) related list on the detail page or you can run above query to check 'New Value' ...


-1

Please check if you have enable the same field for field history tracking 1 From Setup, click Object Manager and select Teacher__c 2 Select Fields & Relationships, and click Set History Tracking. 3 Select Enable Teacher History, then select these two fields to track: teacher_name__c 4 Click Save.


0

All right (assuming you're not asking this for a homework assignment), let's give this a go! Account[] Accs = [SELECT Id FROM Account WHERE Type != 'Type1' AND Type != 'Type2' AND Ignore_Type_Update__c = false AND CreatedDate > :Date.today().addDays(-30) ORDER BY LastModifiedDate DESC LIMIT 50]; Set<Id> AccIds = (new Map<Id, Account>(Accs))...


3

The SOQL for loop is focused on avoiding heap space issues, as that page says: Developers should always use a SOQL for loop to process query results that return many records, to avoid the limit on heap size. This is important when you are querying a lot of large records. The SOQL for loop structure does not allow you to circumvent the hard limit of 50000 ...


1

We have found that COUNT queries can still face limits in the form of exceeding CPU limits in the transaction, and I believe this is actually caused when the WHERE clause for the SOQL query requires significant filter-related processing against unindexed columns. This help page discusses "selectivity": For best performance, SOQL queries must be ...


1

userType Field has these value options (not updateable): Standard: user license. This user type also includes Salesforce Platform and Salesforce Platform One user licenses. Label is Standard. PowerPartner: User whose access is limited because they’re a partner and typically access the application through a partner portalor Experience Cloud site. Label is ...


3

You can get the object name from the Id like this String objectName = theId.getSObjectType().getDescribe().getName(); "theId" refers to an "Id" type variable (not a string). You can cast it from a string like this, Id.valueOf('1234'). Also, you will need to use dynamic SOQL for this. e.g. Database.query('SELECT Name FROM ' + objectName + ...


6

Couldn't find code for this anywhere - many examples ignore the possibility of characters that have special meaning in regular expressions being present. This is what I ended up with as a solution, posted here in case it helps anyone else (and in case there is a better way to do it). Updated per Derek F's feedback: public static Boolean soqlLikeMatch(String ...


0

TriggerToUpdatePracticeOnOpp is the trigger called once OpportunityLineItems is updated or a Product is added to it. It should be created under triggers folder then deployed to your org, if you're doing from Salesforce Dev Console just make sure you hit ctrl+s/cmd+s to save your code. //This trigger should be fired every time there's an insert/update in ...


2

You can make your life easier (in my opinion, of course; perceptions of readability may differ) by using string formatting to inject the dynamic elements of your query, rather than adding more concatenation. Note that you cannot use an Apex variable name (or a bind, for that matter) in the SELECT clause of your query; you must construct it yourself. String ...


0

Do you have a reason why you want to use a batch to send emails when the articles are published and their status changes? Why a batch and not a Process Builder or a Record-triggered Flow or an Apex Trigger? If you are very sure you want to send your emails from a batch, then maybe you can combine these mechanisms, e.g. use a Record triggered Flow to detect a ...


3

Bind variables e.g. :kesIds are a good way to go because they leave the type conversion formatting up to the framework and in the process also eliminate the SOQL injection risk. And make your code simpler and much easier to read. But the variable must be in scope - visible to the code - at the point that Database.query executes as illustrated in Rijwandeltax'...


0

Set<ID> accId = new Set<ID>(); accId.add('0016F00002QHh3E'); String query = 'Select id from Account Where ID IN :accId'; for(Account acc : Database.query(query)){ System.debug('acc=>'+acc); } Its working for me You only need to set keyids variable global variable


1

If you look at the schema, you can see that KnowledgeArticleVersionHistory is not related to the Knowledge__kav. Instead it is related (via ParentId lookup field) to the Knowledge__ka object (which is the parent of all Knowledge Article versions.


0

PermissionsManageContentPermissions & PermissionsContentAdministrator can be used to retrieve those two app permissions from the PermissionSet object. select Id, PermissionsManageContentPermissions, PermissionsContentAdministrator from PermissionSet where <CustomFilter>


2

Related to the previous post here is the sample query you can run in Developer Console with 'Use Tooling API' enabled in Query Editor. SELECT MetadataComponentType, MetadataComponentName, RefMetadataComponentName, RefMetadataComponentId FROM MetadataComponentDependency WHERE RefMetadataComponentId = 'fieldId' AND RefMetadataComponentType = 'CustomField' ...


0

I believe the object you are looking to query is: MetadataComponentDependency This is most likely what Salesforce uses behind the scenes with the 'Where is this used?' button. I have not tested this, but according to the documentation you should be able to call this using the Tooling API or Bulk API 2.0 Please note, it says that this is currently a feature ...


1

Each foreign key has its own "relationship name". You'll need to check your setup to see what the custom name looks like, but it'll look something like: [SELECT Id, Name__c, Date_First_Joined_BE__c, CreatedDate, (SELECT Name, Expiry_Date__c, Effective_From__c FROM Assets__r WHERE Expiry_Date__c >= TODAY AND Effective_From__c <=...


2

The problem with these lists is that they are "magical" (i.e. they do not obey the normal rules for lists), because they are technically QueryLocator objects pretending to be normal lists. To get it the way you expect, you need to make a JSON string and then pop it back out as an object. Case c = (Case)JSON.deserialize( new Map<String, Object&...


3

A Contact Id is not a User Id. You probably mean: SELECT Email, FirstName, LastName FROM Contact WHERE Id IN (SELECT ContactId FROM User) The aliases are not necessary, like in SQL when referring to the same object.


2

@TestVisible is used to make private methods visible to tests so is not relevant here. Some objects are not intended to be modified at runtime, but finding a comprehensive list of those is tricky. One list is Setup Objects. If the goal is to test a query method, the mocking approach has the problem that the mocking code is replacing the query. So great for ...


2

Your update of Opportunity at the end of the trigger causes the Opportunity trigger to run again, resulting in a never ending loop. But it looks like you are modifying OpportunityLineItem and so should be adding those to a list and updating that list. That change is likely to fix the problem. In general, only doing an update when the data actually changes ...


3

If you asking whether or not you can avoid having to insert NavigationMenuItem instances into the database, then the answer is yes, though ideally you would move away from simply using static methods and start using instance methods and separation of concerns so you can start mocking classes. The first option is to take the quick but dirty approach, though ...


2

In the developer console, If you write a query for example Select Id, Name FROM Account and click on the 'Execute' button, it will execute the query. Once a tab is open in the dev. console with queryresults loaded, if you click on 'Execute' again with the same query, it will not re-execute the query so your new Accounts will not show up. To re-execute the ...


0

If your business case requires you to give a user a UI to perform an action that their sharing rules don't permit, the best practice would be: The Apex controller (for VF/Aura/LWC/etc) should still be in with sharing mode. Any SOQL/DML that would contravene sharing rules should be refactored to a utility class that is without sharing. You should ensure the ...


2

Just to be clear, these mechanisms control different things: WITH SECURITY ENFORCED: enables field- and object-level security permissions checking. These are the object and field permissions that you normally set in the profile / permission sets. WITH SHARING: enables record level security checking. Record security is controlled by owd, sharing rules, ...


1

This should work : SELECT Id, Account.Name FROM Asset Account.Name should work. Kindly share your error if you are still getting it. It's the same between all standard object relationships between them.


1

For child-parent relationships, there are two possible ways to use it to reference data on the parent record. It depends on whether the relationship field is a standard field (one provided by Salesforce, like OwnerId on pretty much every object, or AccountId on things like Opportunity and Asset) or a custom field (one ending in __c). The rule of thumb for ...


1

You need to specify a full URL, as in: String endpoint = 'https://mydomain.my.salesforce.com/services/data/...'; If you want to call the local Salesforce server, you can use a PageReference: PageReference ref = new PageReference('/services/data/...'); Blob result = ref.getContent(); The advantage of this approach is that you don't need to specify the ...


1

There's a couple things that need fixing You need to use ?q= in your query. See the example below from the REST API developer guide https://yourInstance.salesforce.com/services/data/v51.0/query/?q=SELECT+name+from+Account The object you're querying is only available through the Tooling API as well so you need to use that endpoint /services/data/v50.0/...


1

createContact returns a Contact, not an Array of Contact values. You don't need the for loop. You didn't get an error, because rows.length is undefined, and 0 > undefined, so the loop ends without a single execution. Your code should look like: let contact = response.getReturnValue(); contact = { ...contact, AccountName: contact.Account && ...


1

You must use a binding by prefixing the reference to newContact.Id using a colon: @AuraEnabled public static Contact createContact(Contact newContact){ upsert newContact; return [SELECT Name, Email, Contact_Level__c, Account.Name, Owner.Name, CreatedBy.Name, CreatedDate FROM Contact WHERE Id = :newContact.Id]; }


Top 50 recent answers are included