Showing posts with label Metadata(SOAP API). Show all posts
Showing posts with label Metadata(SOAP API). Show all posts

Monday, 21 August 2017

Create Custom Permission Set Using Custom Metadata API Via JavaScript

It is very useful article to create custom permission set using metadata.

What is custom metadata

By using custom metadata , we can create our framework for partners, teams, customers etc. Metadata is the data that describe other data.It is used to retrieve,deploy,create,update and delete customization information such as custom object definition and page layout for our organization. It is used to describe objects, their field and their properties.

Now take a example to create custom permission set using vf page and apex class:

Apex Class

Create a apex class 'PermissionSetClr' to get current host url to find your org you are using and create permission for this org.

public class PermissionSetClr{
    public String sHostUrl{get;set;}
    public PermissionSetClr()
    {
        sHostUrl= ApexPages.currentPage().getHeaders().get('Host'); //Get current Host url.
    }
}

Visualforce Page

Now create visualforce page for above controller and define Javascript function 'createPermissionSet()' in this create XML and provide contents like permission set activation when create in org like here I provide false and provide permission set name and provide page name and class name and set object permissions in permission set when create in org.

Now create XML Http Request to send data through API to create permission set. here data will be XML type which we create in 'sXML' variable and attach with metadata and send the request to create permission set.

<apex:page controller="PermissionSetClr">
     <script>
        function createPermissionSet()
        {
            var sXml = '';
            sXml +='<hasActivationRequired>false</hasActivationRequired>'; // default it shlould be false
            sXml +=' <fullName>salesforceadda_B</fullName><label>salesforceadda_B</label>'; // Permission Setting name 'salesforceadda_B' 
            sXml +='<pageAccesses><apexPage>PermissionSet</apexPage><enabled>true</enabled></pageAccesses>'; //Set Page name to access in permission set
            sXml +='<classAccesses><apexClass>PermissionSetClr</apexClass><enabled>true</enabled></classAccesses>'; //Set class name to access in permission set
            sXml +='<objectPermissions><allowCreate>true</allowCreate><allowDelete>false</allowDelete><allowEdit>true</allowEdit><allowRead>true</allowRead><viewAllRecords>true</viewAllRecords><modifyAllRecords>false</modifyAllRecords><object>Account</object></objectPermissions>';   //Set sObject permission in this permission set like create,delete,edit,read etc.         
          
            // Calls the Metdata API from JavaScript to create the PermissionSet to permit Apex callouts
            var binding = new XMLHttpRequest();
            var request =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'+
                    '<env:Header>' +
                        '<urn:SessionHeader xmlns:urn="http://soap.sforce.com/2006/04/metadata">' +
                            '<urn:sessionId>{!$Api.Session_ID}</urn:sessionId>' +
                        '</urn:SessionHeader>' +                       
                    '</env:Header>' +
                   
                    '<env:Body>' +                        
                       '<createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">' +
                          '<metadata xsi:type="PermissionSet">'+sXml+'</metadata>'+
                        '</createMetadata>' +                         
                    '</env:Body>' +
                '</env:Envelope>';  
            binding.open('POST', 'https://{!sHostUrl}/services/Soap/m/31.0');
            binding.setRequestHeader('SOAPAction','""');
            binding.setRequestHeader('Content-Type', 'text/xml');
            binding.onreadystatechange = function() {
                if(this.readyState==4) {
                    var parser = new DOMParser();
                    var doc  = parser.parseFromString(this.response, 'application/xml');
                    var errors = doc.getElementsByTagName('errors');
                    var messageText = '';
                }
            }
            binding.send(request);
        }  
        createPermissionSet();
    </script>
   <center> <h1 style="margin-top:30px;font-size:20px">successful created permission set salesforceadda_B</h1></center>
  </apex:page>

After create visualforce page and apex class class successfully then preview visualforce page then permission set will create automatically in your org.

lets look screenshots of permission set in my org below-


Now click on permission then 



Now go to visualforce page access and Apex class access you will find visualforce page and class which you provide name in <pageAccess> and in <classAccess> and these page name and class name should exist in org.





Sunday, 20 August 2017

Custom List View Of SObjects Using SOAP API In Lightning View

Custom List View Of SObjects

This is very useful article to create custom list view in lightning view of any object as defined in standard functionality.
Below is the example to create custom list view-

Now create Apex Class-

Apex Class

public with sharing class ListView
{
    public String sObjectName{get;set;}
    public String sListViewId{get;set;}
    public ListView()
    {
        sObjectName ='Account';  // Set any SObject name here
        sListViewId ='Defualt';     // Set as a default list view.
    }
    
    // Call function via action function from page
    public PageReference viewList()
    {
        return null;
    }
    
    // Get the object which has been selected in SObject in Constructor.
    public List<sObject> getObjectRecord()
    {
        try{
            String query ='Select Name,CreatedDate  from '+sObjectName;
            if(sListViewId !='Default')       // 'sListViewId' contains record Ids.
            {
               query +=' Where ID IN('+ sListViewId +')'; 
            }
            return Database.query(query +' Order by CreatedDate desc LIMIT 30');
        }
        catch(Exception ex)
        {
         System.debug('Error '+ex.getMessage());
        }
        return new List<sObject>();
    }
}

Visualforce Page


<apex:page controller="ListView" showHeader="false" standardStylesheets="false">
  <head>
       <!-- Call Lightning Desgin System(CSS).-->
      <apex:slds />
      <!-- Call jquery from static resource-->
      <apex:includeScript value="{!$Resource.jquery}" /> 
      <style>
        #sellistview {
            width: 375px;
            float: left;
            margin-bottom: 5px;
        }
        #SortView{
            width: 48%;
            float: right;
            margin-bottom: 5px;
            text-align: right;
            padding-right: 24px;

        }
      </style>
      <script>
        // Call the List View API to obtain a list of List Views for the selected object
        $.ajax({
            url : '/services/data/v32.0/sobjects/{!URLENCODE(sObjectName)}/listviews',
            headers : { 'Authorization' : 'Bearer {!$Api.Session_ID}' },
            datatype : 'json',
            success : function(data, textStatus, jqXHR) {
                $("#selectListView")
                        .append($("<option></option>")
                        .attr("value",'Default')
                        .text('Default'));
                $.each(data.listviews, function(index, obj) {
                    $("#selectListView")
                        .append($("<option></option>")
                        .attr("value",obj.id)
                        .text(obj.label));                 
                });
              
            }
        });     
      </script>
      <script>
            function getRecords(listViewId) 
            {
              $('#spinnerView').show();
                if(listViewId =='Default') {
                   getListViewRecords(listViewId);
            }
            else
           {
                 $.ajax({
                url : '/services/data/v32.0/sobjects/{!URLENCODE(sObjectName)}/listviews/' + listViewId + '/results',
                headers : { 'Authorization' : 'Bearer {!$Api.Session_ID}' },
                datatype : 'json',
                success : function(data, textStatus, jqXHR) {                  
                var recordId ='';
                    $.each(data.records, function(rowIndex, record) {
                       $.each(record.columns, function(colIndex, column) {
                            if(!data.columns[colIndex].hidden)
                                recordId = recordId+(recordId =='' ? '\''+record.columns[6].value+'\'':',\''+record.columns[6].value+'\'');
                        });
                    });
                  getListViewRecords(recordId);
                }
            });
       
          } 
        }
        </script>   
  </head>
  <body>
      <apex:form >
          <apex:actionFunction name="getListViewRecords" reRender="lstColumn" action="{!viewList}">
            <apex:param value="" name="sObjListRecordId" assignTo="{!sListViewId}"/>
          </apex:actionFunction>
       <!--Start Header-->
            <div class="slds-page-header" role="banner">
              <div class="slds-media">
                <div class="slds-media__figure">
                </div>
                <div class="slds-media__body">
                  <p class="slds-page-header__title slds-truncate slds-align-middle" title="{!sObjectName}">List View - {!sObjectName}</p>
                  <p class="slds-text-body--small slds-page-header__info">  <apex:outputText value="{0,date,MM/dd/yy}"> <apex:param value="{!Today()}" /> </apex:outputText></p>
                </div>
                <div class="slds-no-flex">
                    <div class="slds-button-group">
                     </div>
                    <div class="slds-media__body">
                      <p class="slds-text-body--small slds-page-header__info" style="font-weight: 600;float: right;" title="Object : {!sObjectName}"> Object : {!sObjectName}</p>
                     
                    </div>
                  </div>
              </div>
            </div>
            <div class="LObjName" id="HeaderDetail" style="margin-top: 10px;">      
            <div id="sellistview">
                View &nbsp;: &nbsp;
                <select id="selectListView" class="slds-select" onChange="getRecords(this.value);" style="width:80%;"></select>
            </div>
            <div id="SortView">  
               <!-- Provide object in select option to use that object functionality-->
               Object Name :<apex:selectList id="Limit" value="{!sObjectName}" size="1" styleClass="slds-select" style="width:20%">
                    <apex:selectOption itemValue="Account" itemLabel="Account"/>
                    <apex:selectOption itemValue="Contact" itemLabel="Contact"/>
                </apex:selectList>
               &nbsp; <apex:commandButton value="Search" StyleClass="slds-button slds-button--neutral slds-button--small"   />
            </div>
          </div>
        <hr></hr>
       <!-- End Header -->
       <!--Start Table records -->
       <apex:outputPanel id="lstColumn">
       <table class="slds-table slds-table_bordered slds-table_cell-buffer">
          <thead>
            <tr class="slds-text-title_caps">
              <th scope="col">
                <div class="slds-truncate" title="sObjectName Name">{!sObjectName} Name</div>
              </th>
              <th scope="col">
                <div class="slds-truncate" title="Close Date">Create Date</div>
              </th>
            </tr>
          </thead>
          <tbody>
           <apex:repeat value="{!ObjectRecord}" var="sObj" >
            <tr>
              <th scope="row" data-label="sObjectName Name">
                <div class="slds-truncate" title="name">{!sObj['Name']}</div>
              </th>
              <td data-label="Account Name">
                <div class="slds-truncate" title="createddate">{!sObj['CreatedDate']}</div>
              </td>
            </tr>
            </apex:repeat>
          </tbody>
        </table>
        </apex:outputPanel>
       <!-- End Table records-->
      </apex:form>
  </body>
</apex:page>



Now lets look on visualforce,
Firstly get the view list on load of page through AJAX of the SObject which you have defined in class like here SObject is Account. 

In Ajax , We get the list view data of sObject by the custom API URL. So
we pass the service api url as end point and then pass authentication in the header and define datatype that which type of data you are getting from end point url in response.

You can select object from the picklist and click 'Search' button then it will set the selected object configuration on page. Like I selected 'Contact ' object then it will populate list view drop down picklist of contact and select value from picklist then 'onChange' event fire and call Javascript function 'getRecord()' and pupulate the data in the table.