Showing posts with label Apex Class. Show all posts
Showing posts with label Apex Class. Show all posts

Thursday, July 28, 2016

Salesforce : DML currently not allowed

If you write create/update/delete operation in apex controller constructor then this error would be thrown.
You have to do some trick to get rid of this problem.
First create an action with your create/update/delete operations in your controller.
And then add the action name in your apex:page as attribute which will call with constructor.





<apex:page standardController="Account" extensions="APEX_CONTROLLER_CLASS_NAME" action="{!YOUR_ACTION_NAME}">
DO YOUR OTHER WORKS HERE...
</apex:page>

Monday, July 18, 2016

Salesforce create custom controller

1. Go to "setup/Develop/Apex Classes" and click "new"
2. Write the following code:


public class CustomController {

    public Account account { get; private set; }

    public NewAndExistingController() {
        Id id = ApexPages.currentPage().getParameters().get('id');
        account = (id == null) ? new Account() :
            [SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
    }

    public PageReference save() {
        try {
            upsert(account);
        } 
        catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        //  After successful Save, navigate to the default view page
        PageReference r = new ApexPages.StandardController(Account).view();
        return (r);
    }
}


3. Go to "setup/Develop/Visualforce Pages" and click "new"
4. Write the following code:

<apex:page controller="CustomController" tabstyle="Account">
    <apex:form>
        <apex:pageBlock mode="edit">
            <apex:pageMessages/>
            <apex:pageBlockSection>
                <apex:inputField value="{!Account.name}"/>
                <apex:inputField value="{!Account.phone}"/>
                <apex:inputField value="{!Account.industry}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

5. Go to "setup/Create/Tabs" click on "new" under group "Visualforce Tabs"
6. Select "Visualforce Page" created before & provide other information & save.

7. Browse your custom tab to access the custom tab.


Show HTML string as an HTML output instead of plain text in Salesforce Visaul Force page

Write the following code snippet:


<apex:outputLabel escape="false" Value="{!html}" ></apex:outputLabel>


Instead of the following:

{!html} 

How to make a post or get request to some other server from apex class

1. Go to "setup/Develop/Apex Class"
2. Click "new"
3. Write code as following:


public class ApexClass_1 {
    @Future(callout=true)
    public static void c1(String Account_ID) {
        String name = '';
        try {
            HttpRequest req = new HttpRequest();
            req.setEndpoint('http://www.yahoo.com');
            req.setMethod('POST');
            req.setBody('Account_ID='+EncodingUtil.urlEncode(Account_ID, 'UTF-8')+'&other_param='+EncodingUtil.urlEncode('OTHER PARAM VALUE', 'UTF-8'));
            req.setCompressed(true);

            /* If you want to send basic authentication */
            String username = 'myname';
            String password = 'mypwd';
            Blob headerValue = Blob.valueOf(username + ':' + password);
            String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);

            Http http = new Http();
            HTTPResponse res = http.send(req);
            name = 'Status_Code=' + res.getStatusCode();
            String responseBody = res.getBody();
        }
        catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            name = ('Error=' + e.getMessage()).substring(0, 20);
        }

        /* Reading account object */
        Account account = [SELECT Id FROM Account WHERE Id = :Account_ID];
        account.Name = name;
        update op;
    }
}


4. Go to "setup/Security Controls/Remote Site Settings"
5. Click "New remote site" & enter the URL that you want to invoke from apex class.
6. Invoke method "ApexClass_1.c1" from wherever you want.

7. An example of invoke url in salesforce from apex sObjects trigger options
8. Go to "setup/Customize/Accounts/Triggers"
9. Click "new"
10. Write the following code:

trigger TriggerActionName on Account (before insert, after insert, after delete) {
    if (Trigger.isInsert) {
        if (Trigger.isAfter) {
            for (Account a : Trigger.New) {
                ApexClass_1.c1(a.Id);
            }
        }
    }
}


11. Once you create a new account the url would be invoked in a short time (Also you could write code for update & delete)
12. Apex trigger documentation: https://developer.salesforce.com/trailhead/en/apex_triggers/apex_triggers_intro