getting Value of a field by its Name in apex salesforce - salesforce

in my visualforce page i have some campaign object first user select an object then there is a multi picklist. in this picklist there is Label for all the fields user selects some fields then i have to show the value of these fields in the selected campaign object
for showing multiple picklist my apex function is
public List<SelectOption> getOptionalFields(){
Map <String, Schema.SObjectField> fieldMap= Campaign.sObjectType.getDescribe().fields.getMap();
List<SelectOption> fieldsName =new List<SelectOption>();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
fieldsName.add(new SelectOption(dfield.getName(),dfield.getLabel()));
}
but i have no idea how to show value for the the field
for exmple i have object instance like
Campaign c;
now i have to get value of any field whose Name is in string form.how to get corresponding value for that field.one solution is just write like
say
String fieldName;
and use multiple if
if(fieldName=='Name')
c.Name=
if(fieldName=='Id')
c.Id=
is there any other convenient method??please explain!!

You need to read about "dynamic apex". Every "concrete" sObject (like Account, Contact, custom objects) can be cast down to generic sObject (or you can use the methods directly).
Object o = c.get(fieldName);
String returnValue = String.valueOf(o);
There are some useful examples on dynamic get and set methods on Salesforce-dedicated site: https://salesforce.stackexchange.com/questions/8325/retrieving-value-using-dynamic-soql https://salesforce.stackexchange.com/questions/4193/update-a-records-using-generic-fields (second question is a bit more advanced)
You'll still need to somehow decide when to return it as String, when as number, when as date... Just experiment with it and either do some simple mapping or use describe methods to learn the actual field type...

Related

How to get a document from mongodb by using its string id and string collection name in SpringData

I know that generally, we need to do something similar to this for getting a document back from mongodb in spring data:
Define a class and annotate it with #Document:
#Document ("persons")
public class Person
Use MongoTemplete:
mongoOps.findById(p.getId(), Person.class);
The problem is that in runtime I don't know the class type of the document, I just have its string collection name and its string Id. How is it possible to retrieve the document using SpringData? Something like this:
db.myCollectionName.findOne({_id: myId})
The result object type is not a concern, it can be even an object, I just want to map it to a jackson JsonNode.
A possible workaround for this you can use the aggregate function of mongooperation like this
AggregationResults<Object> aggResults = mongoOps.aggregate(newAggregation(match(Criteria.where("_id").is(myId)) ,
myCollectionName, Object.class);
return aggResults.getUniqueMappedResult();

How do I get info from lookup in salesforce query

I have a custom salesforce object Installation__c and it has a custom field Product__c which is a lookup to a custom object Product__c I am trying to get the fields from the child object using these query:
public with sharing class InstallationController {
#AuraEnabled
public static List<Installation__c> getItems() {
// Perform isAccessible() checking first, then
return [SELECT Id, Name, Installation_Display_Name__c, Product__c, Status__c, (SELECT Product__c.Name FROM Product__c) FROM Installation__c];
}
}
I get the error:
Didn't understand relationship 'Product__c' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.
I have tried changing the Query to
FROM Product__rand FROM Product__c__r but neither seems to work, how do I fix my query?
If you're traversing up or down a relationship hierarchy, the __c suffix becomes __r (r for 'relationship') until you finally get to the field that you're looking for (which still ends in __c if it's a custom field). So in your case, it will be
public with sharing class InstallationController {
#AuraEnabled
public static List<Installation__c> getItems() {
// Perform isAccessible() checking first, then
return [SELECT Id, Name, Installation_Display_Name__c, Product__r.Name, Status__c FROM Installation__c];
}
}
So, the change here is, for the relationship you have to use Product__r.Name
Click into the relationship on the object that has the look up. Copy the relationship name adding __r to it
This example would be Test_Drives__r

Unable to filter using ContentDocument id in query in trigger query not retrieving any results

I have a requirement to make to make a file private and be available to only the user whose role name consists the name of the file for a specific custom object. For this I am trying to retrieve from Content Document Link with the custom object name LinkedEntity.Type and ContentDocumentid as filters, when I hard code the ContentDocumentid it is working fine but when I try to dynamically provide the ContentDocumentId then the query is not returning any result. I am adding a snippet of my code. Please Help!!. Thanks
List<Id> listOfConDocuId = new List<Id>();
for(ContentVersion cv: Trigger.new){
if((!cv.Title.contains('product proposal')) || (!cv.Title.contains('final')) || (!cv.Title.contains('packet')))
listOfConDocuId.add(cv.ContentDocumentId);
}
Map<Id, Project__c> mapOfProjectId = new Map<Id, Project__c>([SELECT Id FROM Project__c]);
Set<Id> setOfProjectId = mapOfProjectId.keySet();
List<ContentDocumentLink> LinkedProject = [SELECT ContentDocumentId, LinkedEntityId, ContentDocument.Title FROM ContentDocumentLink where LinkedEntityId in :setOfProjectId and LinkedEntity.Type='Project__c' and ContentDocumentId IN :listOfConDocuId];`
I don't think it's necessary to add a WHERE clause for both ID and TYPE. Id should be enough. As far as restricting files to only users with certain roles, have you tried sharing the Custom Object (Project__c) with only those users and then simply linking the files to that Custom Object record with Inferred Permission?
Read more about the sharing types and visibility of Content Document Link here:
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocumentlink.htm

Create Class object through class name in Salesforce

I am new to Salesforce and want to code one requirement, I have an api name in string variable through which I want to create an object of that class.
For Eg. Object name is Account which is stored in string variable.
String var = 'Account'
Now I want to create object of 'Account'. In java it is possible by Class.forName('Account') but similar approach is not working in Salesforce Apex.
Can anyone please help me out in this.
Have a look at Type class. The documentation for it isn't terribly intuitive, perhaps you'll benefit more from the article that introduced it: https://developer.salesforce.com/blogs/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html
I'm using this in managed package code which inserts Chatter posts (feed items) only if the org has Chatter enabled:
sObject fItem = (sObject)System.Type.forName('FeedItem').newInstance();
fItem.put('ParentId', UserInfo.getUserId());
fItem.put('Body', 'Bla bla bla');
insert fItem;
(If I'd hardcode the FeedItem class & insert it directly it'd mark my package as "requires Chatter to run").
Alternative would be to build a JSON representation of your object (String with not only the type but also some field values). You could have a look at https://salesforce.stackexchange.com/questions/171926/how-to-deserialize-json-to-sobject
At the very least now you know what keywords & examples to search for :)
Edit:
Based on your code snippet - try something like this:
String typeName = 'List<Account>';
String content = '[{"attributes":{"type":"Account"},"Name":"Some account"},{"attributes":{"type":"Account"},"Name":"Another account"}]';
Type t = Type.forName(typeName);
List<sObject> parsed = (List<sObject>) JSON.deserialize(content, t);
System.debug(parsed);
System.debug(parsed[1].get('Name'));
// And if you need to write code "if it's accounts then do something special with them":
if(t == List<Account>.class){
List<Account> accs = (List<Account>) parsed;
accs[1].BillingCountry = 'USA';
}

Populate select list with contacts

I want to use a apex:selectList to populate contacts. The problem is that it gives an error
Collection size 3,403 exceeds maximum size of 1,000
This is because i have 3403 contacts, and Vf has limitation on the collections in the VF page.
I want to limit the inital set of contacts to <1000, and as the user starts typing in the characters i would want to query the contacts. For ex if the user types in Ji i want to query the contacts to retrieve records starting with JI.
Is this possible to do?
<apex:selectlist id="ClientsSearch" value="{!Appointment.Client__c}"
size="1" required="true" rendered="{!NOT (SearchMode)}">
<apex:selectOptions value="{!Clients}" />
</apex:selectlist>
public List<SelectOption> getClients() {
List<SelectOption> options = new List<SelectOption>();
List<Contact> Clients = [Select id, Name From Contact order by Name];
options.add(new SelectOption('0001', '--Select--'));
for(Contact c : Clients ){
options.add(new SelectOption(c.id, c.Name));
}
return options;
}
You can use wild cards in your query to do this — so you'll want to add an <apex:inputText> element in your page to allow them to enter a search term, which writes to a string variable in the controller. Then add a search button to run the query and re-render the list with the new list of contacts.
The important parts of the controller will look something like this:
public string SearchTerm {get; set;}
public list<ContacT> Contacts {get; set;}
public Pagereference SearchContacts()
{
// etc.
Contacts = [select Id, Name from Contact where name like : '%' + SearchTerm + '%' order by name limit 1000];
// populate list here
return null;
}
You could perform the search using an action function and firing it from the onChange event of the input field but having a button to do the search will make the whole thing more response (IMO) from the user's point of view.
Note: I wrote this code on the fly, it may be that you can't just concat '%' with the search term in this manner or maybe that you don't even need to when querying directly. Usually in these cases I've had to utilise dynamic SOQL due to other requirements, where you build up the query in a string:
strQuery = 'select id from contact where name like \'%' +
String.escapeSingleQuotes(SearchTerm) + '%\' order by name';
for(Contact sContact : Database.query(strQuery) ...
There are a few options to get the functionality you'd like. It depends on how complicated of a solution you'd like, but there is always a solution.
You may want to consider using jQuery and SOSL (Search Language) in a controller. Here's an example of jQuery autocomplete with the Ajax API in Salesforce. Click the link below:
http://matthewkeefe-developer-edition.na8.force.com/jQueryAutocompleteWithAjaxAPI
Also, check out Tehnrd's post "Super Cool Advanced Lookup Component" for another option.

Resources