Thursday, 20 August 2015

Manually firing an event in Salesforce Lightning

Manually firing an event


In contrast, other component and application events are fired manually by event.fire() in client-side controllers.
For example, in the component, define a handler with name="change"
<ui:inputDate aura:id="dateField" label="Birthday" value="2014-01-30" displayDatePicker="true"/>

A component can have multiple <aura:handler name="change"> tags to detect changes to different attributes.
In the controller, define the action for the handler.
({
    itemsChange: function(cmp, evt) {
        var v = evt.getParam("value");
        if (v === cmp.get("v.items")) {
        //do something
        }
    }
})

Thursday, 13 August 2015

How to create, update and navigate record in salesforce lightning

Event References

These events enable your components to open a record create or edit page, or navigate to a record.

force:createRecord:

To create a new record:


createRecord : function (component, event, helper) {
    var createRecordEvent = $A.get("e.force:createRecord");
    createRecordEvent.setParams({
        "entityApiName": "Contact"
    });
    createRecordEvent.fire();
}

force:editRecord

To Edit a existing record:

editRecord : function(component, event, helper) {
    var editRecordEvent = $A.get("e.force:editRecord");
    editRecordEvent.setParams({
         "recordId": component.get("v.contact.Id")
   });
    editRecordEvent.fire();
}

force:navigateToList

To navigate to a list view, set the list view ID on the listViewId attribute and fire the event.

gotoList : function (component, event, helper) {

    var action = component.get("c.getListViews");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            var listviews = response.getReturnValue();
            var navEvent = $A.get("e.force:navigateToList");
            navEvent.setParams({
                "listViewId": listviews.Id,
                "listViewName": null,
                "scope": "Contact"
            });
            navEvent.fire();
        }
    });
    $A.enqueueAction(action);
}

This Apex controller returns all list views for the contact object

@AuraEnabled
public static List<ListView> getListViews() {
    List<ListView> listviews = 
        [SELECT Id, Name FROM ListView WHERE SobjectType = 'Contact'];

    // Perform isAccessible() check here
    return listviews;
}

force:navigateToObjectHome


Navigates to the object home specified by the scope attribute.


navHome : function (component, event, helper) {
    var homeEvent = $A.get("e.force:navigateToObjectHome");
    homeEvent.setParams({
        "scope": "myNamespace__myObject__c"
    });
    homeEvent.fire();
}

force:navigateToRelatedList


Navigates to the related list specified by parentRecordId.


gotoRelatedList : function (component, event, helper) {
    var relatedListEvent = $A.get("e.force:navigateToRelatedList");
    relatedListEvent.setParams({
        "relatedListId": "Cases",
        "parentRecordId": component.get("v.contact.Id")
    });
    relatedListEvent.fire();
}



force:navigateToSObject


Navigates to an sObject record specified by recordId.


createRecord : function (component, event, helper) {
    var navEvt = $A.get("e.force:navigateToSObject");
    navEvt.setParams({
      "recordId": "00QB0000000ybNX",
      "slideDevName": "related"
    });
    navEvt.fire();
}



force:navigateToURL


Navigates to the specified URL.


1)   Using a relative URL.


gotoURL : function (component, event, helper) {
    var urlEvent = $A.get("e.force:navigateToURL");
    urlEvent.setParams({
      "url": "/006/o"
    });
    urlEvent.fire();
}


2)   Using external website when the link is clicked.


navigate : function(component, event, helper) {

    //Find the text value of the component with aura:id set to "address"
    var address = component.find("address").get("v.value");

    var urlEvent = $A.get("e.force:navigateToURL");
    urlEvent.setParams({
      "url": 'https://www.google.com/maps/place/' + address
    });
    urlEvent.fire();
}


You can also see on this link click





Wednesday, 12 August 2015

How to get Month Name from date



var dateOb = new Date("12/08/2015");
var lang = "en-us";

//If you want month name in long string like : March
var monthInLongStr = dateOb.toLocaleString(lang, { month: "long" });
alert(monthInLongStr );

//If you want month name in short string like : Mar
var monthInShortStr = dateOb.toLocaleString(lang, { month: "short" });
alert(monthInShortStr );

Tuesday, 11 August 2015

How to create portal user in test class or testing with a portal user

Some things to note about the portal and test sample below:
  • The organization (your Developer Edition environment, for example) in which this is run MUST have the requisite portal licenses
  • The respective portal MUST be enabled in the organization before this test can pass.
  • The user that creates the portal user MUST have a Role.

@IsTest
private class PortalRunAsTests {

    enum PortalType { CSPLiteUser, PowerPartner, PowerCustomerSuccess, CustomerSuccess }
    
    static testmethod void usertest() {
        User pu = getPortalUser(PortalType.PowerPartner, null, true);
        System.assert([select isPortalEnabled from user 
                        where id =:pu.id].isPortalEnabled,
                      'User was not flagged as portal enabled.');       
        
        System.RunAs(pu) {
            System.assert([select isPortalEnabled from user 
                            where id =:UserInfo.getUserId()].isPortalEnabled, 
                          'User wasnt portal enabled within the runas block. ');
        }
    }
    
    public static User getPortalUser(PortalType portalType, User userWithRole, Boolean doInsert) {
    
        /* Make sure the running user has a role otherwise an exception 
           will be thrown. */
        if(userWithRole == null) {   
            
            if(UserInfo.getUserRoleId() == null) {

                UserRole r = new UserRole(name = 'TEST ROLE');
                Database.insert(r);
                
                userWithRole = new User(alias = 'hasrole', email='userwithrole@roletest1.com', userroleid = r.id,
                                    emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
                                    localesidkey='en_US', profileid = UserInfo.getProfileId(), 
                                    timezonesidkey='America/Los_Angeles', username='userwithrole@testorg.com');
            } else {
                userWithRole = new User(Id = UserInfo.getUserId(), UserRoleId = UserInfo.getUserRoleId());
            }
            
            System.assert(userWithRole.userRoleId!= null, 
                          'This test requires the target org to have at least one UserRole created. Please create a user role in this organization and try again.');
        }

        Account a;
        Contact c;
        System.runAs(userWithRole) {

            a = new Account(name = 'TEST ACCOUNT');
            Database.insert(a);
            
            c = new Contact(AccountId = a.id, lastname = 'lastname');
            Database.insert(c);

        }
        
        /* Get any profile for the given type.*/
        Profile p = [select id from profile where usertype =:portalType.name()limit 1];   
        
        String testemail = 'puser000@amamama.com';
        User pu = new User(profileId = p.id, username = testemail, email = testemail, 
                           emailencodingkey = 'UTF-8', localesidkey = 'en_US', 
                           languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles', 
                           alias='cspu', lastname='lastname', contactId = c.id);
        
        if(doInsert) {
            Database.insert(pu);
        }
        return pu;
    }
}

Monday, 10 August 2015

How to check div display style

As sdleihssirhc says below, if the element's display is being inherited or being specified by a CSS rule, you'll need to get its computed style:


console.log(element.currentStyle ? element.currentStyle.display :
                          getComputedStyle(element, null).display);

Tuesday, 21 July 2015

Action Status Rerendering in salesforce vf page

<style>
.custPopup{
    background-color: white;
    border-width: 0px;
    border-radius:10px;
    z-index: 9999;
    left: 50%;
    padding:20px;
    position: absolute;
    /* These are the 3 css properties you will need to change so the popup 
    displays in the center of the screen. First set the width. Then set 
    margin-left to negative half of what the width is. You can add 
    the height property for a fixed size pop up if you want.*/
    margin-left: -100px;
    top:40%;
}
.popupBackground{
    background-color:black;
    opacity: 0.30;
    filter: alpha(opacity = 30);
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 9998;
}
</style>

 <apex:actionStatus id="fetching">
        <apex:facet name="start">
             <apex:outputPanel id="tstpopup">
                    <apex:outputPanel styleClass="popupBackground" layout="block"/>
                    <apex:outputPanel styleClass="custPopup" layout="block">
                        <img src="/img/loading24.gif" style="vertical-align:middle; horizontal-align:middle"/> 
                        <span>Please wait...</span>  
                    </apex:outputPanel>
              </apex:outputPanel> 
        </apex:facet>
    </apex:actionStatus>

<apex:commandButton reRender="fetching"/>

Friday, 17 July 2015

Get related objects or related list object


You can get related objects with function :

public static map<string,string> getRelatedObjects(string masterObjectName){
map<string,string> relatedObjectsMap = new map<string,string>();
list<Schema.Childrelationship> relatedObjectsList = Schema.getGlobalDescribe().get(masterObjectName).getdescribe().getChildRelationships();

for (Schema.Childrelationship  relatedObject : relatedObjectsList) {
if(relatedObject.getChildSObject().getDescribe().isUpdateable()
&&
relatedObject.getChildSObject().getDescribe().getKeyPrefix()!=null
&&
!relatedObject.getChildSObject().getDescribe().isCustomSetting()
&&
relatedObject.getChildSObject().getDescribe().isCreateable()
)
relatedObjectsMap.put(relatedObject.getChildSObject().getDescribe().getName(),relatedObject.getChildSObject().getDescribe().getLabel());
   }
return relatedObjectsMap;
}

Wednesday, 8 July 2015

Remote Function with parameter in apex

Class code


public class MyController {

    @RemoteAction
    public static List<Account> getAccountsList(String userId, String value1, String value2) {
 
        return [SELECT Id FROM Account WHERE  id =: userId];
    }
}

Page Script

<script type="text/javascript">
    var valueTakenFromSomewhere = 'This will be value1 in the remote action';
    var valueTakenFromSomewhereElse = 'This will be value2 in the remote action';

    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.MyController.getAccountsList}',
        '{!$User.Id}',
        valueTakenFromSomewhere,
        valueTakenFromSomewhereElse,
        'This will be value2 in the remote action',
        function(result, event) {
            if (event.status) {
                //do whatever rendering of the list you want
            } else if (event.type === 'exception') {
                //handle errors
            } else {
                //handle unknown responses
            }
        },
        {escape: true}
    );
</script>

Saturday, 27 June 2015

How to call rest api webservices

Step 1 : Initially create connected app in salesforce.
here:
callback URL: https://login.salesforce.com/services/oauth2/callback
selected OAuthScope:Full access (full)

Now you can use consumer key, consumer secret for rest api.

Step 2: How to get access token:

Method:POST
URL:https://login.salesforce.com/services/oauth2/token
client_id:consumer Key from salesforce connected app
client_secret:Consumer secret from salesforce connected app
grant_type:password
username:restAPi@soliant.com (user id)
password:password + security token



Output
{
    "id": "https://login.salesforce.com/id/.....",
    "issued_at": "1435335550081",
    "token_type": "Bearer",
    "instance_url": "https://ap2.salesforce.com",
    "signature": "-----xyz-----",
    "access_token": -------xyz------"
}


Step 3 : How to call Rest API from Postman or other rest client
Insert / update

Method:POST
URL:https://ap2.salesforce.com/services/apexrest/webservices
 (<instance_url>/services/apexrest/< urlMapping of class>)
Header1:Authorization
Value1:Bearer <space> <access_token>
Header2:Content-Type
Value2:application/json




Now select raw and write json in it like:

For insert contact
{
    "JSONString": {
        "attributes": {
            "type": "Contact"
        },
        "FirstName": "John",
        "LastName": "test",
        "Email": " testing @gmail.com",
        "Phone": "12121212"
    }
}

For update contact:
{
    "JSONString": {
        "attributes": {
            "type": "Contact"
        },
        "id":"00328000003KfhB"
        "FirstName": "John",
        "LastName": "testing",
        "Email": "testing@gmail.com",
        "Phone": "12121212"
    }
}