How to fetch Notes related to specific Accounts in Salesforce? - salesforce

How can I fetch Notes data related to a specific Account using SOQL query in Salesforce?
I tried with the below SOQL query but it gives me empty rows.
SELECT Id, Title, Body FROM Note WHERE ParentId = '<Account_id>'
I am attaching a screenshot for better understanding.
I want to query the Notes which are marked in red color in the above image.
PS: Am new to Salesforce

Uh, bit tricky for first task :)
Note is old object primarily used in old Salesforce UI, maybe you have heard of "classic" or "aloha". You are using new Lightning UI and the object you're looking for is ContentNote.
Old: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_erd_documents.htm
New: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_erd_contentnote.htm
To make matters bit messier ContentNotes are built on top of the solution for uploading Files, they're a special type of file. And that one is split into 2 tables - the header that can be linked to from many areas in the system (ContentDocument), wasting space on disk only once... and actual payload which can be versioned (ContentVersion)
Anyway: this should work
SELECT ContentDocument.Title, ContentDocument.LatestPublishedVersion.VersionData
FROM ContentDocumentLink
WHERE LinkedEntityId = '001...'
AND ContentDocument.FileType = 'SNOTE'
Another, simpler way would be to use a flatter, readonly view of all the "files" linked to the record (old school attachments, new files, stuff uploaded as Chatter posts, stuff cross-linked from SharePoint for example...). You'd have to experiment with CombinedAttachment
SELECT Name, (SELECT Title FROM CombinedAttachments)
FROM Account
WHERE Id= '001...'

Related

How can I traverse through multiple related objects based on ID and return some related field?

I'm a little stuck.
I am trying to generate a report that determines whether anyone has made a manual change to certain fields within our order framework. I have figured out the proper fields and structures to audit, and even how to make the report, but I used a combination of extracts from the Dataloader and Excel xlookups to make it. Now, I'm being asked to find a way to automate the generation of the report, and I suspect that means I need to write a SOQL query to figure it out. I'm having trouble traversing multiple relationships based on these ID fields. Essentially, what I'm trying to do is make multiple "left joins" based on the 18 digit Salesforce IDs and extract some related piece of information from those other objects.
For example, if I'm starting with order_product_history (with a field OrderProductID to identify the order product) and I want to bring in "Product Name", I have to first match OrderProductID with the ID field in my order_product "table", then I have to match the Product2ID field in my order_product "table" with the ID in my product "table", then I have to get the matching Product Name as a column in my report:
Matching/Traversal Process
Desired Result
That's one example for one field. I also have to bring in things like User Name from the users "table", and order number from the orders table, but once I get the general idea, I think I'll be OK. I also want to filter the results to only include my Fee__c and UnitPrice fields, ignore the automated users and set a date filter--not sure if I have to do that using a WHERE clause just in my main query, or if I have to filter the subqueries as well.
I am not a programmer and I have no formal Salesforce training; I am just an analyst who is technically inclined and sort of fell into the role of Salesforce Admin. I am familiar with programming concepts and have been writing things using the flow application and have even dipped my toes into some Apex stuff, but it can be a bit of a struggle. I am not asking you to do my job for me and I am willing to work at the problem and learn; any help is appreciated. Sorry about the links; SO won't let me embed images yet.
There's high chance you don't have to write any code for it. I'll give you some tips, experiment a bit and edit the question or post new one?
This diagram might help: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_erd_products.htm
Developer way
It's all about writing the right query. You can play with it in Developer Console or Workbench for example. Read up about relationship queries in SF.
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_understanding.htm
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_hist.htm
I don't have org with orders enabled but this should be a good start:
SELECT CreatedById, Created.Name,
Parent.Name, Parent.Product2.Name, Parent.Order.Name,
Field, OldValue, NewValue, CreatedDate
FROM OrderItemHistory
If it throws errors about "Parent" see if "OrderItem" will work. Once you have it - WHERE Field IN ('UnitPrice', 'Fee__c') AND CreatedDate = LAST_WEEK might be good next step. (dates can be filtered by date but there are few "constants" that are more human-readable too)
You could even export this with Data Loader, you just have to start the wizard on Order Product history table. But you can ignore the whole query creator and paste a query you've created.
Admin way
Have you ever created a report in Salesforce? There are self-paced trainings (for Lightning and Classic UI) and tons of YouTube videos. Get a feel of making few reports.
What you want might be doable with built-in report type (see if there's new report -> order product history). If nothing exciting - as admin you can make new report type in setup. For example Orders -> Order Products -> Order Product History. Screenshots from here might help.
Just wanted to update this for anyone looking for a solution in the future.
Turns out you can traverse these as a parent-child relationship in the SOQL query. Here's the query I ended up using:
SELECT CreatedBy.Name, FORMAT(CreatedDate), OrderItem.Order.OrderNumber, OrderItem.Product2.Name, OrderItem.Product2.ProductCode, Field, OldValue, NewValue
FROM OrderItemHistory
WHERE (Field = 'Fee__c' OR UnitPrice) AND (CreatedBy.Name != 'Integration User') AND (Created Date >= 2020-11-24T00:00:00.000Z) ORDER BY CreatedDate DESC

How to download all attachments of all records of a custom object in Salesforce?

I am new to file handling in Salesforce. I want to grab all the files attached to all the records of a custom object. Can anyone help me with it?
Old-school SF used Attachment object and you could simply go SELECT Body, ContentType, Name FROM Attachment WHERE ParentId = '...'.
In Lightning there's high chance your attachments are called "Files" (the actual API name is ContentDocument / ContentVersion). Check if the attachment's ID starts with 068 or 069. They aren't linked directly to your record. Instead there's ContentDocumentLink table sitting in between, used to cross-share same file. (You upload it and waste database space once, then you can cross-link it in Chatter posts, groups, other records...)
The official ERD isn't great, try to click through it in Setup -> Schema Builder or this answer might help: https://salesforce.stackexchange.com/a/160285/799. There's a sample query which you might have to fine-tune a bit, for example to SELECT ContentDocument.LatestPublishedVersion.VersionData to get the actual payload.
Check out other questions around here about ContentVersion. For example https://stackoverflow.com/a/48668673/313628 (it's other way around, about upload but should give you good idea).
You can export all notes and attachments using open-source sfdx-hardis plugin command
First, define a files export
sfdx hardis:org:configure:files
When prompted for SOQL request, you can input SELECT Id,Name FROM YourCustomObjectName__c
Then, run the files export
sfdx hardis:org:files:export
More details in this article
Disclaimer: My company authors sfdx-hardis plugin

Set up relation on two existing Salesforce objects

I have a custom object in Salesforce which I need to setup a Master Detail relationship from Accounts. Accounts being the Master and CompHist being the Detail. The problem I am running into is that I need to set the relation to work off of custom fields within the objects. Example:
1.) Accounts has a custom field called CustomerId.
2.) CompHist also has custom field called CustomerId.
3.) I need to be able to have this linked together by CustomerId field for report generation.
About 2,000 records are inserted into CompHist around the 8th of each month. This is done from a .NET application that kicks off at the scheduled time, collects info from our databases and then uploads that data to salesforce via the SOAP API.
Maybe I'm misunderstanding how Salesforce relationships work as I am fairly new (couple months) to salesforce development.
Thanks,
Randy
There is a way to get this to work without triggers that will link the records or pre-querying the SF to learn Account Ids in .NET before you'll push the CompHistories.
Setup
On Account: set the "External ID" checkbox on your CustomerId field. I'd recommend setting "Unique" too.
On CompHist: you'll need to make decision whether it's acceptable to move them around or when the relation to Account is set - it'll stay like that forever. When you've made that decision tick / untick the "reparentable master-detail" in the definition of your lookup / m-d to Account.
And if you have some Id on these details, something like "line item number" - consider making an Ext. Id. for them too. Might save your bacon some time in future when end user questions the report or you'll have to make some kind of "flush" and push all lines from .NET (will help you figure out what's to insert, what's to update).
At this point it's useful to think how are you going to fill the missing data (all the nulls in the Ext. Id) field.
Actual establishing of the relationship
If you have the external ids set it's pretty easy to tell salesforce to figure out the linking for you. The operation is called upsert (mix between update and insert) and can be used in 2 flavours.
"Basic" upsert is for create/update solving; means "dear Salesforce, please save this CompHist record with MyId=1234. I don't know what's the Id in your database and frankly I don't care, go figure this out will ya?"
If there was no such record - 1 will be created.
If there was exactly 1 match - it will be updated.
If there were more than 1 found - SF won't know which one to update and throw error back at you (that's why marking as "unique" is a good idea. There's a chance you'll spot errors sooner).
"Advanced" upsert is for maintaining foreign keys, establishing lookups. "Dear SF, please hook this CompHist up to Account which is marked as "ABZ123" in my DB. Did I mention I don't care about your Ids and I can't be bothered to query your database first prior to me uploading my stuff?"
Again - exact match - works as expected.
0 or 2 Accounts with same ext. id value = error.
Code plz
I'd recommend you to play with Data Loader or similar tool first to get a grasp. of what exactly happens, how to map fields and how to not be confused (these 2 flavours of upsert can be used at same time). Once you'll manage to push the changes the way you want you can modify your integration a bit.
SOAP API upsert: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_upsert.htm (C# example at the bottom)
REST API: http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_upsert.htm
If you'd prefer an Salesforce Apex example: Can I insert deserialized JSON SObjects from another Salesforce org into my org?

how to display salesforce attachments in asp.net website to download

we are creating asp.net website which uses salesfoce webservice api and pull all the information. We have a functionality within the site to display a contact "notes and attachments" which can be downloaded. I have been googling a lot about it, but no use.
Can any one guide me please.?
thanks,
You have to query the Attachment table, either directly:
SELECT Id, Name, Body, BodyLength, ContentType, CreatedBy.Name, CreatedDate, Description, Owner.Name, ParentId
FROM Attachment
LIMIT 10
Or indirectly with a subquery:
SELECT Id, Name, Email, (SELECT Name FROM Attachments ORDER BY CreatedDate DESC)
FROM Contact
LIMIT 10
The actual content of the file is stored in the Body column, base64-encoded. You'll have to decode it and (based on content type?) save as text / binary file, server to the user with the proper content header...
The inclusion of the Body column slows things down a bit - I'd recommend you skip it initially in the "see attachments related list" part of your ASP application and retrieve them (by Id for example) only when user actually wants it... I've noticed that you can get just 1 row returned (initially) with Body queried for so if you really want to do it all in one go - check out the documentation for queryMore() function and make sure your app has processed whole query locator ("cursor" if you're familiar with that word).
So, the above should work both in SOAP API and REST API as long as you can send queries (you didn't specify which one you use... "webservice api" sounds like you're limited to using few selected Apex classes exposed as webservice). Additionally REST API has special retrieve() command.

Generate invoice with Salesforce

I am new in Salesforce and I would like to know how to generate an invoice.
I think to different solutions and I don't know if there are possible, time-consuming, difficult...
A service has different steps.
The service must be invoiced when the step is "completed". a new record have to be added in the table "Invoice" and a link to the invoice document (PDF or Word format)
For the moment, I think to use the section "Note and Attachment Fields". but perhaps that the object "document" is better...
Invoice Creation: I can use the standard button to create a new record but I would like to create it automatically when the status of the file is changed to "completed" for example.
1.I have read the workflow description but I am not sure that it could be use to create automaticaly a specific record in a table.
2.I have also thought to use a button that could fill in the fields and create the record. I fand information to update field with onclick javascript code. But I don't know how to add a record.
Electronic invoice: how can I generate the invoice in PDF or Word format ? and make it available from the record "Invoice n°10" ?
For exemple, the record "Invoice_10" would have an attachment field that contain a link to the document "Inv_010.pdf". The user could open the document from the link.
You might also consider using the standard quote object for your purpose. It comes with a neat PDF generator that is easy to set up. If you set it up right you can (ab)use the quote functionality for creating invoices related to an opportunity. Customizing the New Quote button would allow you to enable this functionality only after the opportunity is closed (using JavaScript). Regarding MS Word generation I recommend DocMocracy: http://www.cloudgizmos.com/salesforce-sfdc-word-excel-document-generator since it is really cheap and you can create read-only word documents.
To answer your first question, you want to write an Apex trigger — run it on your service object (sounds like Opportunity) after insert, and after update, and if the status has been changed to completed then generate your invoice record.
As for generating a PDF invoice you can do this by creating a Visualforce Page and using the renderAs="pdf" attribute in the <apex:page> tag. Storing it against a record will be a bit more tricky, though I suggest you look at examples of how you can attach a Visualforce PDF to an email, you can likely use the same blob object (which stores the content) as a document in Salesforce.
There is already an application: Invoices for Salesforce listed on the Appexchange that automatically creates invoices - records and PDF, straight out of your sales data. The application includes an invoice template editor that gives you complete freedom to design your invoice documents. In addition, the application can automatically deliver the invoices via email, or can group the invoices in files for batch printing in case you need to send them by post or fax.
Check it out: http://www.invoicesforsalesforce.com

Resources