Forum Replies Created

Page 1 of 4
  • Hello Uday,

    Hope you will have better understanding now with these many answers... 🙂

    Let me add few more points here, I would say, A Controller is an Apex Class but an Apex Class is not always a Controller. Further you can call apex class in many different ways:-

    From another class
    From Trigger
    From Visualforce page
    From Developer console
    Form JavaScript button, Links
    From Home page components

    Now if we talk about Controller:-
    In MVC, the view (the Visualforce page) interacts with a controller, and the controller provides functionality to the page. For example, the controller can contain the logic to be executed when a button is clicked. A controller also typically interacts with the model (the database)—making available data that the view might want to display, or pushing changes back to the database.

    Standard Controller:-
    Most standard and all custom objects have standard controllers that can be used to interact with the data associated with the object, so you don’t need to write the code for the controller yourself. You can extend the standard controllers to add new functionality, or create custom controllers from scratch.

    Custom controller:-
    When you want to override existing functionality, customize the navigation through an application, use callouts or Web services, or if you need finer control for how information is accessed for your page, Visualforce lets you take the reigns. You can write a custom controller using Apex and completely control your app’s logic from start to finish.

    Now I will give you a simple scenario:-
    Suppose you have been asked to display the list of all Account on a visual force page then you will definitely start with Standard controller and using pageBlock table you can simply display all accounts. Now if I say to display list of account having Industry = "Agriculture" and Type = "Customer - Channel", then you have to think about custom controller where you write SOQL with some filter on Account.

    So, you have a better control over the page now as you are writing the code (a custom controller) that will fetch the data based on your requirement.

    Hope this will help you..!!!

  • Radhakrishna

    Member
    August 14, 2017 at 11:17 am in reply to: any batch apex scenarios in Salesforce?

    Hello Uppada kishore,

    We use batch apex for bulk processing. Let's say you want to update thousands to accounts on a regular basis or (even if just one time) and real time update is not a MUST HAVE requirement. You know how you are bound by governor limits for all the retrievals , updates , inserts.

    Batch class has much wider governor limits . Its an async operation and you can run a nightliy job and process all these records without hitting limits.

    Examples :
    I used batch class for a scenario where I had to send email to all contract owners 15 days before payment due date. There were thousands of contracts and at one time there could be many contract owners meeting this criteria. Also, apart from sending email, I had to update a flag on contract. So, I schedules a daily nightly batch job for this.

  • Hello Shubham,
    You can call the flow when the user clicks on a custom button/link ,A Process starts ,Apex is called ,Inline Visualforce page ,The user accesses a custom tab. Flows can execute logic, interact with the Salesforce database, call Apex classes, and guide users through screens for collecting and updating data. You can take a look here Figure Out Which Tool To Use

    I will suggest following the awesome blog series to getting started with flow here

    https://automationchampion.com/learning-flow/

     

  • Hello Shariq,

    JavaScript variable in Visualforce page

    A simple example :

    Visualforce :

    <apex:page controller="javascriptLearning">
    <script>
    alert('{!lstAssignToArray}');
    var myList = new Array();
    myList = '{!lstAssignToArray}';
    alert(myList);
    </script>
    </apex:page>

    Apex Controller:

    public with sharing class javascriptLearning {
    public List<String> lstAssignToArray {get;set;}

    public javascriptLearning()
    {
    lstAssignToArray = new List<String>();
    lstAssignToArray.add('ABC');
    lstAssignToArray.add('DEF');
    lstAssignToArray.add('GHI');
    lstAssignToArray.add('JKL');
    lstAssignToArray.add('MNO');
    lstAssignToArray.add('PQR');
    lstAssignToArray.add('STU');
    lstAssignToArray.add('VWX');
    lstAssignToArray.add('YZ');
    }
    }

    This works for me and in my alerts, I see that array has those values from the list!

  • Hello Shariq,

    Instead of onclick try - oncomplete event.

    <apex:commandButton value="Save" action= "{!save}"
    Oncomplete="javascript:top.window.opener.closeFunction()" />

  • Radhakrishna

    Member
    August 11, 2017 at 8:57 am in reply to: How to turn my input field empty on the button click?

    Hello Shariq,

    Add a check when the button is clicked to see if there is any text. If there isn't, pop up an alert box (or some other form of feedback) to tell the user to enter data, and don't do the button functionality.

    <input id="myText" type="text" onkeyup="stoppedTyping()">
    <input type="button" value="Click to begin!" id="start_button" onclick="verify()" disabled/>

    <script type="text/javascript">
    function stoppedTyping(){
    if(this.value.length > 0) {
    document.getElementById('start_button').disabled = false;
    } else {
    document.getElementById('start_button').disabled = true;
    }
    }
    function verify(){
    if myText is empty{
    alert "Put some text in there!"
    return
    }
    else{
    do button functionality
    }
    }
    </script>

    • This reply was modified 7 years, 3 months ago by  Radhakrishna.
  • Hello Aman,

     

    The MIME types you mention are the two Content-Type headers for HTTP POST requests that user-agents (browsers) must support. The purpose of both of those types of requests is to send a list of name/value pairs to the server. Depending on the type and amount of data being transmitted, one of the methods will be more efficient than the other. To understand why, you have to look at what each is doing under the covers.

    For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

    MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

    [Reserved and] non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character

    That means that for each non-alphanumeric byte that exists in one of our values, it's going to take three bytes to represent it. For large binary files, tripling the payload is going to be highly inefficient.

    That's where multipart/form-data comes in. With this method of transmitting name/value pairs, each pair is represented as a "part" in a MIME message (as described by other answers). Parts are separated by a particular string boundary (chosen specifically so that this boundary string does not occur in any of the "value" payloads). Each part has its own set of MIME headers like Content-Type, and particularly Content-Disposition, which can give each part its "name." The value piece of each name/value pair is the payload of each part of the MIME message. The MIME spec gives us more options when representing the value payload -- we can choose a more efficient encoding of binary data to save bandwidth (e.g. base 64 or even raw binary).

    Why not use multipart/form-data all the time? For short alphanumeric values (like most web forms), the overhead of adding all of the MIME headers is going to significantly outweigh any savings from more efficient binary encoding.

  • Radhakrishna

    Member
    August 11, 2017 at 8:43 am in reply to: Any one tell me Salesforce visualforce best practices
  • Hello,

    IsTest(SeeAllData=true) Annotation
    use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization,
    1) If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword
    2) The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level

    http://amitsalesforce.blogspot.in/2015/09/test-classes-with-istest.html

    Use the isTest(SeeAllData=true) means you need to create the test data in your org.

    User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
    SeeAllData=true will not work for API 23 version eailer .

    NOTE:- Always try to avoid use SeeAllData= true because in that case your test class depend on your sandbox data. You May get some issue will deployment.

    Let us know if this will help you

  • Hello Shaharyar,

    One trigger per object is recommended for best practice. Please see the link below for apex trigger best practices
    https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices
    https://developer.salesforce.com/page/Best_Practice:_Streamline_Multiple_Triggers_on_same_Object

  • Radhakrishna

    Member
    August 10, 2017 at 5:33 am in reply to: Why we use Test.starTest and Test.stopTest in Salesforce?

    Hello Shaharyar,

     

    As you must know by now that Apex is governed by certain boundaries. THe term coined for this is 'Governor Limits'.

    There are two additional system static methods provided by Apex. These methods, Test.startTest and Test.stopTest, are used when testing governor limits. Or in other words, executing test scenarios with a larger data set.

    These static methods allow a test method to separate the Apex resources and governor limits being used to prepare and initialize the dataset from the resources and limits used during the actual test execution.

    Bottom Line -

    Governor limits are reset when the Test.startTest appears and the code between Test.startTest and Test.stopTest executes in fresh set of governor limits (Context changes). Also Test.stopTest appears, the context is again moved back to the original code.

    Example -

    you have 100 lines of code in your test class.

    you have start test at 30
    you have stop test at 70

    So the line of code from 30 -70 is in different context of governor limits and
    line 1-30/71-100 in in different context.

    Total of 2 contexts here.

    Please mark this as best answer if your query is resolved.

     

  • Hello Naren,

    Are you trying to pass data from one object to another when a new record is created? Assuming so you have a few options depending on if you are in Classic or Lightning.

    If in Classic you can create a hacked URL button that passes data from one record to another.

    If in Lightning you can use Quick Actions and prepopulate values when the Action is called

    If in either you (or a developer) could have a before insert trigger that copies data over when the record is created.

  • Hello Shariq,

    Try this once...

    1. Go to Setup | Customize | <Standard Object Name> | Buttons, Links & Actions and then Click 'New Button or Link' or if it is a Custom Object then go to Setup | Create | Objects and then click on the Custom Object name. Scroll down to find the section 'Buttons, Links, and Actions' and then click 'New Button or Link'.
    2. Give it the Label: <A Valid Name>.
    3. Display Type: Detail Page Button.
    4. Behavior: Execute JavaScript.
    5. Content Source: OnClick JavaScript.

    Here is the JS:

    {!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')}
    {!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')}
    try{
    jQuery(function() {
    /*Append the jQuery CSS CDN Link to the Head tag.*/
    jQuery('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css" type="text/css" />');

    /*Create the HTML(DIV Tag) for the Dialog.*/
    var html =
    '<div id="dialog" title="Go Home"><p>Do you want to go to the Home tab ?</p></div>';

    /*Check if the Dialog(DIV Tag) already exists if not then Append the same to the Body tag.*/
    if(!jQuery('[id=dialog]').size()){
    jQuery('body').append(html);
    }

    /*Open the jQuery Dialog.*/
    jQuery( "#dialog" ).dialog({
    autoOpen: true,
    modal: true,
    show: {
    effect: "bounce",
    duration: 1000
    },
    hide: {
    effect: "bounce",
    duration: 1000
    },
    buttons: {
    "Continue": function() {
    location.replace('/home/home.jsp');
    jQuery( this ).dialog( "close" );
    },
    Cancel: function() {
    jQuery( this ).dialog( "close" );
    }
    }
    });
    });
    }
    catch(e){
    alert('An Error has Occured. Error: ' + e);
    }

    Save the same!

    7. Now, just open any Record, click Edit Layout at top-right..
    9. From the Page Host, select Buttons list and drag the new button onto the Page Layout.
    10. Save and you are done!

  • Radhakrishna

    Member
    August 2, 2017 at 6:13 am in reply to: Difference between global and static keyword in Salesforce?

    Hello Shubham,

    Static and global variable differ a lot in their behaviour to life and scope. First, let me distinguish between life and scope. Life of an object determines whether the object is still in the memory (of the process) whereas scope of the object is whether can I know the variable by its name at this position. It is possible that object is live, but not visible (not in scope) but not that object is not alive but in scope (except for dynamically allocated objects where you refer object through pointers).

    Static variables are local in scope to their module in which they are defined, but life is throughout the program. Say for a static variable inside a function cannot be called from outside the function (because it's not in scope) but is alive and exists in memory. The next time this function is entered (within the same program) the same chunk of memory would be accessed now retaining the variables old value and no new memory is allocated this time for this variable like other variables in the function (automatic variables). So basically the variable persists throughout the program. Similarly if a static variable is defined in a global space (say at beginning of file) then this variable will be
    accessible only in this file (file scope).

    On the other hand global variables have to be defined globally, persists (life is) throughout the program, scope is also throughout the program. This means such variables can be accessed from any function, any file of the program.

    So if you have a global variable and u r distributing ur files as a library and you want others to not access your global variable, you may make it static by just prefixing keyword static (of course if same variable is not required in other files of yours).

    Example:

    void staticTest(){
    static int i;
    printf("%d\n",i);
    i++;
    }
    void main(){
    staticTest();
    staticTest();
    staticTest();
    }

    Output:

    0

    1

    2

    In above example use of local static variable is demonstrated.

    global static: you can declare static variable in global scope also it will be almost same as other global variable except it has initial value as zero, if you don't assign any value to it.

  • Hello Shariq,

    Displaying a JavaScript variable can be done, but not as easily as you might think, as you can't embed '<' characters in the output string.

    I use the following mechanism:

    Two methods in my controller to generate the beginning/end of the JavaScript write:
    public String getJSStart() { return '<script>document.write('; } public String getJSEnd() { return ')</script>'; }

    I can then do the following on my page:

    <script> var str="Hello world!"; </script> <apex:outputText value="{!JSStart}str{!JSEnd}" escape="false"/>

    and I get the output I expect. Make sure you set the escape="false" attribute, otherwise you will just see a text version of the JavaScript.
    Setting a value is a little easier, although you still have to work a bit to get the component's id. Here's an example:

    var reasonEle=document.getElementById('{!$Component.dcForm.dcBlock.dcSection.reasonItem.reason}'); var str='Hello world'; if (reasonEle.value.length==0) { reasonEle.value=str; }

    When getting the element by ID, you have to supply the full path through the VisualForce component hierarchy. In my example above, the element (id=reason) is within a PageBlockSectionItem (id=reasonItem) within a PageBlockSection (id=dcSection) within a pageblock (id=dcBlock) within a form (id=dcForm)

  • Hello Shubham,

     

    You need to create new "instance" of Account and need to add Id and RecordTypeId in it to update.

    Right now in your code it is taking entire object returned from SOQL. Rather than updating same list you received from SOQL, create new list of Account and update that.

    Put this line before SOQL on account.
    List<Account> = new List<Account>();

    Wherever you are setting RecordTypeId, set following code for adding account in list of Accounts to be updated.

    Account a = new Account(
    Id = acc.Id,
    RecordTypeId = rt.Id
    );
    AccListToBeUpdated.add(a);

    Let me know if any issues. Mark it as best answer if it works!

  • Radhakrishna

    Member
    August 1, 2017 at 8:19 am in reply to: What is mixed DML error?

    Hello Shariq,

    sObjects That Cannot Be Used Together in DML Operations. DML operations on certain sObjects, sometimes referred to as setup objects, can't be mixed with DML on other sObjects in the same transaction.

    Mixed DML operations within a single transaction aren’t allowed. You can’t perform DML on a setup sObject and another sObject in the same transaction. However, you can perform one type of DML as part of an asynchronous job and the others in other asynchronous jobs or in the original transaction. This class contains an @future method to be called by the class in the subsequent example.

    public class InsertFutureUser {
    @future
    public static void insertUser() {
    Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
    UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
    User futureUser = new User(firstname = 'Future', lastname = 'User',
    alias = 'future', defaultgroupnotificationfrequency = 'N',
    digestfrequency = 'N', email = '[email protected]',
    emailencodingkey = 'UTF-8', languagelocalekey='en_US',
    localesidkey='en_US', profileid = p.Id,
    timezonesidkey = 'America/Los_Angeles',
    username = '[email protected]',
    userpermissionsmarketinguser = false,
    userpermissionsofflineuser = false, userroleid = r.Id);
    insert(futureUser);

    }

    }

  • Radhakrishna

    Member
    August 1, 2017 at 8:09 am in reply to: how to override standard list view page

    Hello Uday,

    You can create a VF page.

    Step 1: Create a VF page using the code below

    <apex:page standardController="Your_Object_API" recordSetVar="x"
    action="{!URLFOR($Action.Your_Object_API.List,$ObjectType.Your_Object_API)}" />

    Step 2 Go to: Setup > Customize > "Your_Object" > Buttons, Links and Actions or Setup > Create > Objects > "Your_Object" > Buttons, Links and Actions or Setup

    Step 3: Edit the "Your_Object" Tab link

    Step 4: Override the "Your_Object" Tab with a VisualForce Page you created

  • Hello Shariq,

     

    Effective Summer '13, you can reference fields from the account owner using the following syntax:

    Account__r.Owner.SomeField

    The syntax is a little different depending on whether the object supports Queues as owners, or just Users. For more information, see "Using the Owner Field" in Tips on Building Formulas.

    However you can't create a lookup to the owner, because there isn't a lookup formula field return type and you can't update a lookup field using a workflow field update action. Yet.

  • Hello Adarsh,

    It's easier to read the code if you use the <> and paste code in there, then you can also refer to the line in the code the error is pointing to. There is a blog post out there that might help you out:
    http://www.infallibletechie.com/2013/09/trigger-to-count-number-of-contacts.html

  • Radhakrishna

    Member
    July 28, 2017 at 7:29 am in reply to: Can we deactivate a flow through workbench in Salesforce?

    Hello Shariq,

    please check this may help you:

    https://help.salesforce.com/articleView?id=000221117&type=1

  • Hello Aman,

    The PriceBookEntry object is a hidden junction object so you can't add fields to it. When a Product is added to the Pricebook, this record is created.

    You might be able to get close to what you want using Validation Rules on the OpportunityProduct object. Since PriceBookEntries are used to associate a PriceBookEntry to an Opp, you could have a VR check that the OppProduct.UnitPrice is within some limits of the PriceBookEntry.Product2.ListPrice.

    This would only really make sense if your Min/Max prices follow general rules like +/- 10%.

  • Radhakrishna

    Member
    July 25, 2017 at 6:37 am in reply to: how to debug trigger in salesforce?
  • Radhakrishna

    Member
    July 25, 2017 at 6:34 am in reply to: how to delete the meta data from production org?

    Hello Saloni,

     

    As Bob suggested, you should first delete it from your sand box using force.com IDE.

    Below are the steps:

    1) From Force.com IDE, select the class that you want to delete (Look for .xml extension )

    2) Open that .xml version of your class and change the Status tag to Deleted.

    3) Right click and save the file.

    4) Now select "SRC" folder and right click--->Select Force.com---> select Deploy to server

    5) Log into your production org and follow the steps.

    Note: if you have any test class for the class that you are deleting make sure you do the same like above and then select those 2 classes for final deployment.

    Hope it helps.

  • Radhakrishna

    Member
    July 24, 2017 at 10:28 am in reply to: Difference between Compact Layout and Page Layout ?

    Hello Saloni gupta,

     

    Compact Layouts :

    Compact layouts display a record’s key fields at a glance in both Salesforce1 and Lightning Experience.
    In the full Salesforce site, a compact layout determines which fields appear in the Chatter feed item that appears after a user creates a record with a quick action.
    In Salesforce1, the first four fields that you assign to a compact layout appear in:
    An object’s record highlights area
    Expanded lookup cards on a record’s related information page
    In Lightning Experience, the first five fields that you add to a compact layout display in an object’s record highlights panel and in the expanded lookup card you see when you hover over a link in record details.
    Page Layouts :

    Page layouts control the layout and organization of buttons, fields, s-controls, Visualforce, custom links, and related lists on object record pages. They also help determine which fields are visible, read only, and required. Use page layouts to customize the content of record pages for your users.
    Page layouts can include s-controls and Visualforce pages that are rendered within a field section when the page displays. You can control the size of the s-controls and Visualforce pages, and determine whether or not a label and scroll bars display.
    Salesforce has two drag-and-drop tools for editing page layouts: the original page layout editor and an enhanced page layout editor. The enhanced page layout editor is enabled by default, and provides all the functionality of the original editor, as well as additional functionality and an easier-to-use WYSIWYG interface.
    You can enable the original page layout editor in the User Interface settings. Your Salesforce org can use only one page layout editor at a time.
    From within a page layout, you can access a mini page layout. The mini page layout defines the hover details that display when you mouse over a field on an object’s detail page in the Agent console or in the Recent Items section of the sidebar in Salesforce Classic.

     

     

Page 1 of 4