Salesforce Platform Developer 1 Exam - salesforce

I am prepping for my PD1 cert and am doing questions with the following link:
https://www.proprofs.com/quiz-school/quizshow.php?title=developer-i_18b7&q=102
I have come across questions below which I am sure why the answers are correct. Please could someone advise me on the following 6 questions.
Q1.
Which three statements are accurate about variable scope? Choose 3 answers
A. A sub-block can reuse a parent block's variable name if it is static
B. A sub-block can reuse a parent block's variable name if it is not static
C. Parallel blocks can reuse the same variable name
D. A variable can be declarated at any point in a block
E. A variable must be declared before it can be referenced in a block
Website correct answers: B, C, D
I am sure E should be correct. Cannot think of an instance where you can reference a variable without declaring it first.
Q2.
A developer wants to display all of the picklist entries for the opportunity stagename field and all of the available record types for the opportunity object on a visualforce page. Which two actions should the developer perform to get the available picklist values and record types in the controller? Choose 2 answers
A. Use schema.recordtypeinfo returned by recordtype.sobjecttype.getdescribe().getrecordtypeinfos()
B. Use schema.picklistentry returned by opportunity.sobjecttype.getdescribe().getpicklistvalue()
C. Use schema.recordtypeinfo returned by opportunity.sobjecttype.getdescribe().getrecordtypeinfos()
D. Use schema.picklistentry returned by opportunity.stagename.getdescribe().getpicklistvalue()
Website correct answers: B, C
Just want to confirm if this is correct. So for picklist and record types you query through: object.sobjecttype.getdescribe().get…
Q3.
A developer created a visualforce page using a custom controller that calls an apex helper class. A method in the helper class hits a governor limit. what is the result of the transaction?
A. All changes made by the custom controller are saved
B. The custom controller calls the helper class method again
C. All changes in the transaction are rolled back
D. The helper class creates a savepoint and continues
Website Answer: B
I would say C as governor limit exceptions are unrecoverable
Q4.
A developer creates a custom controller and custom visualforce page by using the code block below:
public class mycontroller{
public string mystring{ get{ If(mystring ==null){mystring='a';} return
mystring; }
public string getmystring(){ return 'getmystring'; }
public string getstringmethod(){ if(mystring==null){ mystring='b'; }  
return mystring;  }
}
<apex:page controller="mycontroller">   {!stringmethod},{!mystring},
{!mystring} </apex:page>
What can the user expect to see when accessing the custom page?
A. A,a,a
B. A,b,b
C. B,a,getmystring
D. A,b,getmystring
Website Answer: A
Can someone explain this to me? Not sure about this one
Q5.
The account object has a custom percent field, rating, defined with a length of 2 with 0 decimal places. An account record has the value of 50% in its rating field and is processed in the apex code below after being retrieved from the database with SOQL
public void processaccount(){     
decimal acctscore = acc.rating__c * 100;
}
What is the value of acctscore after this code executes?
A. 50
B. 5000
C. 5
D. 500
Website Answer: D
I tested this and got 5000. Am I incorrect?
Q6.
Given the code below, which three statements can be used to create the controller variable?
Public class accountlistcontroller{
public list<account>getaccounts(){  return controller.getrecords();   }
}
Choose 3 answers
A.
Apexpages.standardcontroller controller= new
apexpages.standardcontroller([select id from account]);
B.
Apexpages.standardsetcontroller controller=new
apexpages.standardsetcontroller(database.getquerylocator('select id from
account'));
C.
Apexpages.standardcontroller controller= new
apexpages.standardcontroller(database.getquerylocator('select id from
account'));
D.
Apexpages.standardsetcontroller controller = new
apexpages.standardsetcontroller (database.getquerylocator([select id
from account]));
E.
Apexpages.standardsetcontroller controller = new
apexpages.standardsetcontroller (database.query('select id from
account'));
Website Answers: A, D, E
Not sure why C is incorrect. If you want a list of records you need StandardSet.

As per your options mentioned here:::
options a,b,d,e are correct when tested in Anonymous window.
option c is incorrect as standardcontroller with getquerylocator gives below error.
Constructor not defined: [ApexPages.StandardController].(Database.QueryLocator)
a: true
Apexpages.standardsetcontroller controller=new apexpages.standardsetcontroller(database.getquerylocator('select id from account limit 1'));
b: true
Apexpages.standardcontroller controller= new apexpages.standardcontroller([select id from account limit 1]);
c: false
Apexpages.standardcontroller controller= new apexpages.standardcontroller(database.getquerylocator('select id from account limit 1'));
d: true
Apexpages.standardsetcontroller controller=new apexpages.standardsetcontroller(database.query('select id from account limit 1'));
system.debug('controller '+controller);
e: true
Apexpages.standardsetcontroller controller = new apexpages.standardsetcontroller (database.getquerylocator([select id from account limit 1]));

Related

Writing a Custom Controller extension to get related records and iterate over list/index and use with apex:repeat

I have 3 custom objects with a Master-Detail Relationship and Lookup Relationship.
CustomA__c (related CustomB__c) <-> CustomB__c <-> CustomC_c (related CustomB_cc)
I´ve built a Visualforce page with HTML table to replicate a PDF document and a Custom Controller Extension, so far so good.
But I´m just a beginner with apex coding.
The problem is that I need to replicate the document as it is, when there are no related records for CustomA__c or less then 5, it should still show the full table (the empty rows). Max. rows/related records on the document is 5, no second page needed.
Currently I´m trying to accomplisch that by using apex:variable and apex:repeat as I´ve seen some examples, but perhaps there is also another solution. For the Visualforce page I already wrote the code for the rows with data and another apeax:repeat for the empty rows.
But I´m really strugling with the controller, i know i need to iterate over the list, the code that i already wrote is also put together out of examples as i just don´t understand it yet good enough.
Any help would be appreciated! Thanks, Josip
public with sharing class CustomAController {
public CustomA__c customa{get; set;}
public CustomA__c ca{get; set;}
public CustomAController (ApexPages.StandardController controller) {
ca = (CustomA__c )controller.getRecord();
customa= [SELECT Id, Name FROM CustomA__c WHERE Id = :ApexPages.currentPage().getParameters().get('Id')];
}
public List<CustomB__c > getrelatedCustomB() {
List <CustomB__c > cbList = New List<CustomB__c >(5);
for(CustomA__c acc:[SELECT Id, Name, (SELECT Id, Name, ... , CustomCfield__r.Name FROM CustomBs__r ORDER BY Name LIMIT 5) FROM CustomA__c WHERE Id = :customa.Id]){
for(CustomB__c cb:acc.CustomBs__r)
cbList.add(cb);
}
return cbList;
}
}
You can dramatically simplify your code by writing a direct query on the child object instead of a parent-child SOQL query.
public List<CustomB__c > getrelatedCustomB() {
return [SELECT Id, Name, ... , CustomCfield__r.Name
FROM CustomB__c
WHERE CustomA__c = :customA.Id
ORDER BY Name
LIMIT 5];
}
There's no need to iterate in Apex here.

Salesforce apex controller extension for custom object and visualforce page

I have 2 custom objects i have created and due to the limitations of salesforce lists and reports i cant get more then 255 characters to be displayed on a long textarea.
Sales_Trip__c
- Name - string
- Date_From - date
- Date_To - date
- Salesman - lookup User
Sales_Trip_Visit__c
- Sales_Trip - master-detail
- Account - master-detail
- Notes - Long Textarea
- Date - date
so i'm trying to create a new visualforce page that displays the sales_trip_visit__c's in a table ordered by Sales_Trip_Visit__c.Date
I have the page working using the Sales_Trip__c standard controller
But that returns the visits unordered.
From what i can tell i cant do that within the page so i am attempting to create an extension for the Sales_Trip__c standard controller that has a method that returns a list of visits ordered by the date.
This is what i have so far and i think i'm not doing something right.
public class mySalesTripControllerExtension {
private final Sales_Trip__c satr;
public mySalesTripControllerExtension(ApexPages.StandardController stdController) {
this.satr = (Sales_Trip__c)stdController.getRecord();
}
public List<Sales_Trip_Visits__c> getVisitList() {
con = new List<Sales_Trip_Visits__c>();
con = [SELECT Date, Account.Name, Notes FROM Sales_Trip_Visits__c WHERE Sales_Trip__c.id = :this.satr.id ORDER BY Date]
return con;
}
}
I'm getting the following error but i think I am doing it completely wrong.
Error: Compile Error: sObject type 'Sales_Trip_Visits__c' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names. at line 18 column 15
Thanks for the help this is now my revised code. and i have kept the nameing convention i am using which is a duplicate custom object same fields / same relationships just a different name ( original had a rich textarea. _2 has a long textarea
public class mySalesTripControllerExtension {
private final Sales_Trip__c satr;
// The extension constructor initializes the private member
// variable acct by using the getRecord method from the standard
// controller.
public mySalesTripControllerExtension(ApexPages.StandardController stdController) {
this.satr = (Sales_Trip__c)stdController.getRecord();
}
public List<Sales_Trip_Visit_2__c> getVisitList() {
Sales_Trip_Visit_2__c con = [SELECT Date__c, Account__r.Name, Notes__c FROM Sales_Trip_Visit_2__c WHERE Sales_Trip__r.Id = :satr.id ORDER BY Date__c];
return con;
}
}
Current error.
Error: Compile Error: Return value must be of type: LIST<Sales_Trip_Visit_2__c> at line 16 column 9
First of all you can make a sorting on a page but you will have to use some javascript for it. A better approach would be as you're doing to make the sorting on the controller side.
You making it right overall except the error i mentioned in a comment.
Here is modified code
public List<Sales_Trip_Visits__c> getVisitList() {
Sales_Trip_Visits__c con = [SELECT Date__c, Account__r.Name, Notes__c FROM Sales_Trip_Visits__c WHERE Id = :satr.id ORDER BY Date__c]
return con;
}

getting Value of a field by its Name in apex 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...

Apex Compile Error: sObject type 'Book__c' is not supported

I am new in apex programming. I am using site.com.
I am creating New apex class using this code --
#isTest
private class HelloWorldTestClass {
static testMethod void validateHelloWorld() {
Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
System.debug('Price before inserting new book: ' + b.Price__c);
// Insert book
insert b;
// Retrieve the new book
b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
System.debug('Price after trigger fired: ' + b.Price__c);
// Test that the trigger correctly updated the price
System.assertEquals(90, b.Price__c);
}
}
but it gives me this error -Error: Compile Error: sObject type 'Book_c' is not supported. If you are attempting to use a custom object, be sure to append the '_c' after the entity name. Please reference your WSDL or the describe call for the appropriate names. at line 13 column 12.
help me out..
Have you actually created such object in your Salesforce instance? There are some standard objects (like User) and you most likely also have the objects related to the CRM product (like Account, Contact, Opportunity) but Book__c will be a custom object created by you or another System Administrator in your organization.
Check Setup (upper right corner in web interface) -> Create -> Objects. There's a youtube tutorial or you can always click "Help for this page" link.
To expose this object on the Site (which means anybody in the world will be able to view and insert Books) you'll have to follow few more steps. But as it's a test class that fails to compile I think you haven't reached this problem yet. More info about permissions: http://login.salesforce.com/help/doc/en/siteforce_data_access_perms.htm

How can I get the name of the Lead Owner in a Lead custom formula field?

I've got an application that reads Lead records from Salesforce via the API and I want to link the Lead Owner field to an attribute in the application. The Lead Owner field doesn't up in the list of available fields but all the custom fields do.
So, my first attempt at a solution was to create a custom field that displayed the Lead Owner name. In the SF formula editor, as far as I can tell, it doesn't display the actual data field but instead displays the ID string. Which is pretty meaningless in the context that I need it for.
alt text http://skinny.fire-storm.net/forposting/insertfield.JPG
Is there a way that we can get at the data in the object that the ID string references?
alt text http://skinny.fire-storm.net/forposting/havewant.JPG
I have the RED BOX but need the GREEN BOX.
EDIT: I can't change the application code that calls the API. I can only change salesforce. So, this is more of a salesforce superuser / formula-writer question, not a question about writing code that calls the SF API.
Salesforce allows access to related data through what they call relationship queries. Instead of joining, you specify the query like this:
System.debug([SELECT Owner.Name FROM Lead WHERE Id = '00QS00000037lvv'].Owner.Name);
Try running that in the system log, just replace the lead ID with one that you're looking at.
When accessing the data through the API, the principle is the same, your proxy objects should allow you to access Lead.Owner.Name.
EDIT:
I agree with eyescream, since you can't change the application code, creating an Apex trigger would be the best way to go here. Here's some code to get you started:
trigger Lead_UpdateOwner on Lead(before insert, before update)
{
Map<Id, String> ownerMap = new Map<Id, String>();
for (Lead lead : Trigger.new)
{
ownerMap.put(lead.OwnerId, null);
}
if (ownerMap.size() > 0)
{
for (User[] users : [SELECT Id, Name FROM User WHERE Id IN :ownerMap.keySet()])
{
for (Integer i=0; i<users.size(); i++)
{
ownerMap.put(users[i].Id, users[i].Name);
}
}
for (Lead lead : Trigger.new)
{
lead.OwnerName__c = ownerMap.get(lead.OwnerId);
}
}
}
lead.OwnerName__c would need to be the name of your custom field on the lead object that will hold the owner name. Type Text, length 121.
I had a similar problem, but wanted all the current and future User fields available. Since a custom lookup field to the User is not restricted by formula fields, I created one named
OwnerLookup
on the Opportunity and Account objects, then used a triggers to populate it on creation or edit. For example the Opportunity trigger is this:
trigger OpportunityTrigger on Opportunity (before insert, after insert, before update, after update) {
if(trigger.isBefore && trigger.isInsert) {
OpportunityTriggerHandler.newOpportunity(Trigger.old, Trigger.new);
}
else if(trigger.isAfter && trigger.isInsert){
//OpportunityTriggerHandler.futureUse(Trigger.new);
}
else if(trigger.isBefore && trigger.isUpdate){
OpportunityTriggerHandler.updateOpportunity(Trigger.new, Trigger.oldMap);
}
else if(trigger.isAfter && trigger.isUpdate){
//OpportunityTriggerHandler.futureUse(Trigger.new, Trigger.oldMap);
}
}
and the OpportunityTriggerHandler class (Apex code) is:
public with sharing class OpportunityTriggerHandler {
public static void newOpportunity( List<Opportunity> oldOpportunitys, List<Opportunity> newOpportunitys ) {
for (Opportunity opp: newOpportunitys) {
updateOwnerData( opp );
}
}
public static void updateOpportunity( List<Opportunity> oldOpportunitys, Map<Id, Opportunity> newOpportunitys ) {
for (Opportunity opp: oldOpportunitys) {
updateOwnerData( opp );
}
}
public static void updateOwnerData( Opportunity opp ) {
opp.OwnerLookup__c = opp.OwnerId;
}
}
I then create Formula fields on the Opportunity/Account objects to get to any of the owner (User) object fields, such as Oppty Owner Name formula field:
OwnerLookup__r.FirstName & " " & OwnerLookup__r.LastName
VLOOKUP function would be a good try, but
it's available only in validation rules, not in field definitions
it can be used only on custom objects and you need data from User
I'd say you need to query from your application for
SELECT Owner.FirstName, Owner.LastName FROM Lead
Other than that... some "after insert, after update" trigger that would populate your custom field when owner changes?
Just posting for completeness sake (and for the Google searches): The issue arises with any object that can be queued, not just Lead, since the source of it is that the owner can refer to either a user (as usual) or a queue object.
This can be resolved using a formula field instead of triggers, like below:
BLANKVALUE(Owner:Queue.QueueName, Owner:User.FirstName & " " & Owner:User.LastName)
Basically, the BLANKVALUE function in the formula checks whether the owner.queuename is blank, and if so gives the name of the user.

Resources