Using Salesforce Apex to find a record and pull data from a field - salesforce

In salesforce we have two objects. The first is a Component pricing object (Comp_Pricing__c). This has records with component part numbers and pricing in their respective fields, Part_Number & Pkg_Price__c. We also have an object in which we put together proposals with quotes. In this object we use an apex class and trigger to run our calculations to determine quantities of parts needed. We would like to have the apex class, based on a variable (apPart), search through the records, find the corresponding part number and then pull back the price for use in further apex calculations. I believe I will need to run a query on the records but have no idea how to do this. Can I get some help?

list cpFTList = [SELECT Pkg_Price__c FROM Component_Pricing__c WHERE Component_Pricing__c.Part_Number__c = :PRT_Pr_Ft]; Pr_Ft = cpFTList[0].Pkg_Price__c;
This is the final query that works.
Thanks Chiz for the help.

Related

Number of fields

I am new in salesforce and I have a question. I am creating a new reporty type using opportunites and when I was in field layout properties I noticed there were total 40 fields for opporutiy object. I didnt had another object relation with opportunity just simple opportunity. But when I went to opportunity in in object manager there were only 29 items listed in fields and realtionship. Why are there 11 more fields in opportunity in reprot type then in fields and realtuionship
I was expeting the same number of fields in object manager and in report type but report type had more fields even when no object was linked with it
There's a number of fields that exist in the table but aren't visible in setup because you can't modify them, can't change user's right to see/edit them. It's bit like https://help.salesforce.com/s/articleView?id=sf.dev_objectfields.htm&type=5 but it doesn't mention CreatedDate, LastmodifiedDate, SystemModStamp... and on Opportunity there are more.
https://developer.salesforce.com/docs/atlas.en-us.238.0.object_reference.meta/object_reference/sforce_api_objects_opportunity.htm may be a good start but if you truly want everything - run a "describe" operation in Apex or maybe REST API (https://workbench.developerforce.com/ -> utilities -> rest explorer for example)

Access a field from another table using the object relation

I am new to SalesForce and SOQL so sorry in advance if the question has already been answered, if yes link it to me.
The aim of my SOQL query is to get all the contract information to generate PDF.
There are tables: Contract, Contact and Account
In the Contract table there are fields: Maitre_d_apprentissage__c, MaitreApprentissageNom1__c, MaitreApprentissagePrenom1__c, Apprenti__c, ApprentiNom__c, ApprentiPrenom__c
There are relationships:
Apprenti__r which link Apprenti__c to Contact table
Maitre_d_apprentissage__r which link Maitre_d_apprentissage__c to Contact table
When I looked at table, I saw that MaitreApprentissageNom1__c was equal to Maitre_d_apprentissage__r.LastName and ApprentiNom__c was equal to Apprenti__r.LastName. So I conclude I could get other information of Apprenti__c and Maitre_d_apprentissage__c from the Contact Table following the same principle. So I added to my query Apprenti__r.Date_de_naissance__c and Maitre_d_apprentissage__r.Date_de_naissance__c to get the Date_de_naissance__c field which is in my Contact table.
I see in the results that the query succeeds in getting the information but some values have changed column (lines 6 and 7), you can see the difference between query 1 and query 2. In the first query I only return the Apprenti__r.Date_de_naissance__c and in the second query I return Apprenti__r.Date_de_naissance__c and Maitre_d_apprentissage__r.Date_de_naissance__c
Query 1:
SELECT ApprentiNom__c, ApprentiPrenom__c, Apprenti__r.Date_de_naissance__c, MaitreApprentissageNom1__c, MaitreApprentissagePrenom1__c
FROM Contract
Result 1:
Query 2:
SELECT ApprentiNom__c, ApprentiPrenom__c, Apprenti__r.Date_de_naissance__c, MaitreApprentissageNom1__c, MaitreApprentissagePrenom1__c, Maitre_d_apprentissage__r.Date_de_naissance__c
FROM Contract
Result 2:
I would like to understand from where is coming the problem and how to correct it. Thank you in advance.
It's possible that it's just your query editor displaying stuff incorrectly. You can see it got confused with 2 lookups to Contact table, why there's even a column header "Contact.Date_de_naissance__c" (and why it's there twice). And they aren't shown in the order you requested...
What editor you're using? You could try built-in "Developer Console" or http://workbench.developerforce.com/
What do you need it for? In Apex order of fields won't matter, in REST API query the values fetched via lookup will come as JSON sub-objects so there will always be a way to figure out exactly which value is coming from which relation.
In Dev Console try to run this and check if it solves your fears:
System.debug(JSON.serializePretty([SELECT
ApprentiNom__c, ApprentiPrenom__c,
Apprenti__r.Date_de_naissance__c,
MaitreApprentissageNom1__c, MaitreApprentissagePrenom1__c,
Maitre_d_apprentissage__r.Date_de_naissance__c
FROM Contract]));
Then add Maitre_d_apprentissage__r.LastName to query and see what changed, what stayed as is.

Query of Arrays in Salesforce

I need to do 1 of two things (I believe):
1- Get a Custom Object ID so I can query it directly
2- Get a list of values of a specific field within the Object entries.
Ultimate End goal:
Add and modify rows in my custom object via external API. However to do this I need to check and make sure my new entry/row does not already exist.
What I have:
I have a custom object (called Customer_Arrays__c). It is a table that I can add new rows to (I will call entrys). Each entry has 6 or 7 fields. 1 of these fields is called (external_ID__c). This is the field I utilize to match to new incoming data to see if the entry already exists, or if it needs to add a new row to my table. This Customer_Arrays__c is a child to my opportunity I believe – it is part of every opportunity and each line item I add has a field defaulted to the opportunity.
Help I need:
1- How do I query the value of my Cutomer_Arrays__c based upon an opportunity ID?
2- How do I query a list of values in my (external_ID__c) based upon an opportunity ID?
Thanks for your help! I have read half a dozen+ posts on similar topics and am missing something. Examples of some Past try's that failed:
Select external_ID__c,FROM Custom_Arrays__c WHERE Opportunity='00...'
Select Id (Select ID, Custom_Arrays__c from Custom_Arrays__c) from Opportunity where id ='00...'
List FROM Custom_Arrays__c WHERE Opportunity='00...'
Select Id, external_ID__c, (Select external_ID__c FROM Custom_Arrays__c) WHERE Opportunity__c='00...'
Thanks again!
Only you know how did you name the lookup field (foreign key) from arrays to Opportunity. You'll need to check in setup, next to where external_ID__c is. Since it's a custom field (gets __c at the end), my guess is you went with default.
Try
SELECT Id, Name, External_Id__c
FROM Customer_Arrays__c
WHERE Opportunity__c = '006...'
Thank you eyescream, that got me almost all the way there. Turns out I also needed a __r for the parent child relationship.
Here is a snip out of my final code that works - I think it covers everything:
SELECT Field1__c, Opportunity__r.Id, Opportunity__r.Opportunity__c,
FROM Customer_Arrays__c
WHERE Opportunity__r.Id = '006...'.
Thank you so very much!!!

Django Query Optimisation

I am working currently on telecom analytics project and newbie in query optimisation. To show result in browser it takes a full minute while just 45,000 records are to be accessed. Could you please suggest on ways to reduce time for showing results.
I wrote following query to find call-duration of a person of age-group:
sigma=0
popn=len(Demo.objects.filter(age_group=age))
card_list=[Demo.objects.filter(age_group=age)[i].card_no
for i in range(popn)]
for card in card_list:
dic=Fact_table.objects.filter(card_no=card.aggregate(Sum('duration'))
sigma+=dic['duration__sum']
avgDur=sigma/popn
Above code is within for loop to iterate over age-groups.
Model is as follows:
class Demo(models.Model):
card_no=models.CharField(max_length=20,primary_key=True)
gender=models.IntegerField()
age=models.IntegerField()
age_group=models.IntegerField()
class Fact_table(models.Model):
pri_key=models.BigIntegerField(primary_key=True)
card_no=models.CharField(max_length=20)
duration=models.IntegerField()
time_8bit=models.CharField(max_length=8)
time_of_day=models.IntegerField()
isBusinessHr=models.IntegerField()
Day_of_week=models.IntegerField()
Day=models.IntegerField()
Thanks
Try that:
sigma=0
demo_by_age = Demo.objects.filter(age_group=age);
popn=demo_by_age.count() #One
card_list = demo_by_age.values_list('card_no', flat=True) # Two
dic = Fact_table.objects.filter(card_no__in=card_list).aggregate(Sum('duration') #Three
sigma = dic['duration__sum']
avgDur=sigma/popn
A statement like card_list=[Demo.objects.filter(age_group=age)[i].card_no for i in range(popn)] will generate popn seperate queries and database hits. The query in the for-loop will also hit the database popn times. As a general rule, you should try to minimize the amount of queries you use, and you should only select the records you need.
With a few adjustments to your code this can be done in just one query.
There's generally no need to manually specify a primary_key, and in all but some very specific cases it's even better not to define any. Django automatically adds an indexed, auto-incremental primary key field. If you need the card_no field as a unique field, and you need to find rows based on this field, use this:
class Demo(models.Model):
card_no = models.SlugField(max_length=20, unique=True)
...
SlugField automatically adds a database index to the column, essentially making selections by this field as fast as when it is a primary key. This still allows other ways to access the table, e.g. foreign keys (as I'll explain in my next point), to use the (slightly) faster integer field specified by Django, and will ease the use of the model in Django.
If you need to relate an object to an object in another table, use models.ForeignKey. Django gives you a whole set of new functionality that not only makes it easier to use the models, it also makes a lot of queries faster by using JOIN clauses in the SQL query. So for you example:
class Fact_table(models.Model):
card = models.ForeignKey(Demo, related_name='facts')
...
The related_name fields allows you to access all Fact_table objects related to a Demo instance by using instance.facts in Django. (See https://docs.djangoproject.com/en/dev/ref/models/fields/#module-django.db.models.fields.related)
With these two changes, your query (including the loop over the different age_groups) can be changed into a blazing-fast one-hit query giving you the average duration of calls made by each age_group:
age_groups = Demo.objects.values('age_group').annotate(duration_avg=Avg('facts__duration'))
for group in age_groups:
print "Age group: %s - Average duration: %s" % group['age_group'], group['duration_avg']
.values('age_group') selects just the age_group field from the Demo's database table. .annotate(duration_avg=Avg('facts__duration')) takes every unique result from values (thus each unique age_group), and for each unique result will fetch all Fact_table objects related to any Demo object within that age_group, and calculate the average of all the duration fields - all in a single query.

SOQL query to traverse several levels on Task

I'm trying to write some apex code using this query and not getting anywhere:
List<Task> tasks = [SELECT id, whatid, who.account.parent.name FROM task WHERE who.account.parent.name LIKE 'Procter%'];
I'm not surprised this doesn't work, but can't seem to find documentation anywhere that explains how I would go about this. Does anyone have any idea? I'm trying to get all tasks linked to a contact linked to an account with a parent account of "procter and gamble"...
Looks like the options to "go up" in the mixed fields (the ones where Lookup goes to multiple objects like WhatId going to Account or Opportunity) are very limited. I was able to write "WHERE what.name LIKE 'Procter%' but not "WHERE what.parent.name LIKE 'Procter%'".
By the way I think it should be WhatId and not the WhoId (check out the Validation Rule editor for Tasks, try to insert fields "Contact/Lead ID" and "Opportunity/Account ID"). You will also see that you can't "go up" (or in case of this editor - "go right") on these fields while for some other fields you can explore the relation like for "CreatedBy.UserRole.Name".
Can you try this subquery instead?
[SELECT id, whatid FROM task WHERE whatid IN (SELECT Id FROM Account WHERE Parent.Name LIKE 'United%')]
WhatId and WhoID are polymorphic fields, so these fields do not support traversing multiple levels.
I had a similar requirement for hierarchal traversing, in my case i had to select the lead information associated with a task. What I had to do was first query for a list of tasks, then query for a list of leads based off those tasks, then use a wrapper class to combine the two lists into a custom object and display the object accordingly using visualforce. The wrapper class was certainly my answer to the equation since it seems you are in fact unable to query directly using the Who.Id.
Hope this helps!
The AccountID field on Tasks is populated by SF automatically for Contacts. Obviously, it is blank for Leads. So, if you want to get Account data you can just do something like this:
SELECT ID, Who.FirstName, Who.LastName, Account.Parent.Name FROM Task WHERE WhoID = '00Q12SDFUUALDLKJF'
Obviously, Account.Parent.Name is blank for Leads.

Resources