• Avinash Barola
  • NEWBIE
  • 35 Points
  • Member since 2015
  • SFDC Developer
  • Metacube

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 12
    Replies
Hi,
Can I call a apex trigger when a google doc is inserted.
Thanks

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.JSONException;
 
public class OAuthConnectedApp {
    
    static final String USERNAME     = "avinash.barola@metacube.com";
    static final String PASSWORD     = "9782700490afo3GKfhFClkBKYoHAhtCTiQbs";
    static final String LOGINURL     = "https://login.salesforce.com";
    static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
    static final String CLIENTID     = "3MVG9ZL0ppGP5UrCJNszgnq4XwZ06OLxPHU3_A_EOVLtF0IOuvGzzq3hldpuBTAYp.kfNfqh2_PFVDMtGISGi";
    static final String CLIENTSECRET = "3825749946662741519";
 
    public static void main(String[] args) {
 
        HttpClient httpclient = HttpClientBuilder.create().build();
 
        // Assemble the login request URL
        String loginURL = LOGINURL +
                          GRANTSERVICE +
                          "&client_id=" + CLIENTID +
                          "&client_secret=" + CLIENTSECRET +
                          "&username=" + USERNAME +
                          "&password=" + PASSWORD;
 
        // Login requests must be POSTs
        HttpPost httpPost = new HttpPost(loginURL);
        HttpResponse response = null;
 
        try {
            // Execute the login POST request
            response = httpclient.execute(httpPost);
        } catch (ClientProtocolException cpException) {
            cpException.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
 
        // verify response is HTTP OK
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("Error authenticating to Force.com: "+statusCode);
            // Error is in EntityUtils.toString(response.getEntity())
            return;
        }
 
        String getResult = null;
        try {
            getResult = EntityUtils.toString(response.getEntity());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        JSONObject jsonObject = null;
        String loginAccessToken = null;
        String loginInstanceUrl = null;
        try {
            jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
            loginAccessToken = jsonObject.getString("access_token");
            loginInstanceUrl = jsonObject.getString("instance_url");
        } catch (JSONException jsonException) {
            jsonException.printStackTrace();
        }
        System.out.println(response.getStatusLine());
        System.out.println("Successful login");
        System.out.println("  instance URL: "+loginInstanceUrl);
        System.out.println("  access token/session ID: "+loginAccessToken);
 
        // release connection
        httpPost.releaseConnection();
    }
}
hello I create a site with only one page. when i run my site home page(siteHomePage) from preview its working well but when i run it from site url its not working properly.it initially shows a select list with correct options but when i select any option from list it not diving the detail of selected option.

Here is my vf page:-
<apex:page sidebar="false" showHeader="false" standardController="Student__c" extensions="SiteHomeController">
    <apex:pageBlock >
        <apex:form >
            <apex:pageBlockSection >
                <apex:selectList value="{!selectedValue}" size="1" label="Select Student Name" onchange="clickme()">
                    <apex:selectOptions value="{!selectList}"></apex:selectOptions>
                    <apex:actionFunction name="clickme" action="{!getStudent}" reRender="show" />
                </apex:selectList>
            </apex:pageBlockSection>
        </apex:form>
        <apex:pageBlock >
        <apex:pageBlockSection >Hii
            <apex:outputPanel id="show" >
            <apex:pageBlockTable value="{!student}" var="s" >
                <apex:column value="{!s.Id}" headerValue="Id" />
                <apex:column value="{!s.Name}" headerValue="Name" />
                <apex:column value="{!s.Age__c}" headerValue="Age" />
                <apex:column value="{!s.DOB__c}" headerValue="DOB" />
                <apex:column value="{!s.Class__c}" headerValue="Class" />
            </apex:pageBlockTable>
            </apex:outputPanel>
        </apex:pageBlockSection>
    
    </apex:pageBlock>
    </apex:pageBlock>
    
</apex:page>



and here is my controller:-

public class SiteHomeController {
    public List<Student__c> stdList{set ;get ;} 
    public List<Student__c> student{set ;get ;}
    public String selectedValue{set ;get ;}
    public ApexPages.StandardController controller;
    public SiteHomeController(ApexPages.StandardController con) {
        controller = con;
        student = new List<Student__c>();
    }
    
    public List<SelectOption> getselectList() {
        System.debug('hii');
        List<SelectOption> selectList = new List<SelectOption>();
        stdList = [select Name from Student__c];
        for(Student__c std : stdList) {
            selectList.add(new SelectOption(std.Id,std.Name));
        }
        return selectList;
    }
    
    public PageReference getStudent() {
        try{
            student = [select Id,Name,Age__c,Class__c,DOB__c from Student__c where id =:selectedValue limit 1] ;
            return null ;
        }
        catch(Exception e){
            System.debug('Catch');
            System.debug(e);
            return new PageReference('/apex/errorfinder');
        }
       
    }
}
<apex:page standardController="Account">
    <script src="/soap/ajax/11.0/connection.js"></script>
    <script src="/soap/ajax/11.0/apex.js"></script>
    <script src="{!$Resource.jQuery}"/>
    <script type="text/javascript">
        
        queryResult= null; 
    var flag=false;
   var table ="<table id='tab' border =' 1 solid black '></table>";    
    window.onload=function(){  
        sforce.connection.sessionId = "{!$Api.Session_ID}";
        queryResult= sforce.connection.query("select Id,Name,Owner.name,Phone from Account order by isActive__C desc,name"); 
        document.write(table);
        accountDetail(); 
    };
    function accountDetail()
    {   
        document.getElementById('tab').innerHTML = "";
        document.getElementById("tab").style.columnWidth = "100px";
         var str = "<tr><th>ID</th><th><a href ='#' onclick = 'accountDetail()'>Name</th><th>owner Name</th><th>Phone</th></tr>";
        try {   
            var count = 0;
            if(queryResult != null && queryResult.size >0){ 
                var crecords = queryResult.getArray("records");
                if(!flag)
                  {  flag=true;
                     for (var i=0; i<crecords.length; i++) { 
                         str = str + "<tr><td  width = '50px' style = 'text-overflow:ellipsis'>"+crecords[i].Id+"</td><td>"+crecords[i].Name+"</td><td>"+crecords[i].Owner.Name+"</td><td>"+crecords[i].Phone+"</td></tr>";
                    }
                }
             
                else
                { flag=false;
                    for (var i=crecords.length-1;i>=0; i--) { 
                         str = str + '<tr><td>'+crecords[i].Id+'</td><td>'+crecords[i].Name+'</td><td>'+crecords[i].Owner.Name+'</td><td>'+crecords[i].Phone+'</td></tr>';
                    }
                }
            }
           document.getElementById('tab').innerHTML=str;

        }
        catch(error){
            alert(error);
        }
    }
    
    </script>
</apex:page>
<apex:page standardController="Class__c">
    <script src="/soap/ajax/11.0/connection.js"></script>
    <script src="/soap/ajax/11.0/apex.js"></script>
    <script type = "text/javascript">
           function save(){  
            try{
                sforce.connection.sessionId = "{!$Api.Session_ID}";
                var t = new sforce.SObject("Class__c"); 
                var nameOfClass = document.getElementById('{!$Component.block1.block2.name}').value;
                t.Name = nameOfClass.value;
                alert(nameOfClass.value);
                 var result = sforce.connection.create([t]);
                alert(result);
            }
               catch(error) {
                alert(error.faultstring);
            }
            
           };
    </script>
   
        <apex:form>
            <apex:pageBlock id="block1">
                <apex:pageBlockSection id="block2">
                    <apex:inputText id="name" />
                </apex:pageBlockSection>
                <apex:commandButton onclick="save()" />
            </apex:pageBlock>
        </apex:form>
  
</apex:page>
<apex:page extensions="OnlinePurchaseController" showHeader="false" sidebar="false" standardController="Order__c">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:selectList value="{!selectedCategory}" label="Category" size="1">
                    <apex:actionSupport event="onchange" action="{!getProducts}" reRender="products"/>
                    <apex:selectOptions value="{!category}">
                    </apex:selectOptions>
                </apex:selectList>
             </apex:pageBlockSection>
            
            
             <apex:pageBlockSection >    
                <apex:pageBlockTable value="{!productList}" var="product" id="products">
                    <apex:column >
                        <apex:commandButton value="add" action="{!addToOrder}" reRender="orders,products">
                            <apex:param name="productID" value="{!product.ID}" assignTo="{!productID}"></apex:param>
                           </apex:commandButton>
                    </apex:column>
                    <apex:column value="{!product.Name}" />
                    <apex:column value="{!product.Price_Per_Item__c}" />
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
        <apex:pageBlockSection id="orders">    
                <apex:pageBlockTable value="{!orderList}" var="order" >
                    <apex:column value="{!order.Name}"  headerValue="Name" />
                    <apex:column value="{!order.Price_Per_Item__c}" headerValue="Price Per Item" />
                       <apex:column headerValue="Quantity">
                        <apex:outputField value="{!order.Quantity__c}"  >
                            <apex:inlineEditSupport showOnEdit="update" event="ondblclick" /> 
                        </apex:outputField>
                    </apex:column> 
                    <apex:column headerValue="Total">
                        <apex:inputField value="{!order.Total__c}" />
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
<apex:page extensions="OnlinePurchaseController" showHeader="false" sidebar="false" standardController="Order__c">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:selectList value="{!selectedCategory}" label="Category" size="1">
                    <apex:actionSupport event="onchange" action="{!getProducts}" reRender="products"/>
                    <apex:selectOptions value="{!category}">
                    </apex:selectOptions>
                </apex:selectList>
             </apex:pageBlockSection>
            
            
             <apex:pageBlockSection >    
                <apex:pageBlockTable value="{!productList}" var="product" id="products">
                    <apex:column >
                        <apex:commandButton value="add" action="{!addToOrder}" reRender="orders,products">
                            <apex:param name="productID" value="{!product.ID}" assignTo="{!productID}"></apex:param>
                           </apex:commandButton>
                    </apex:column>
                    <apex:column value="{!product.Name}" />
                    <apex:column value="{!product.Price_Per_Item__c}" />
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
        <apex:pageBlockSection id="orders">    
                <apex:pageBlockTable value="{!orderList}" var="order" >
                    <apex:column value="{!order.Name}"  headerValue="Name" />
                    <apex:column value="{!order.Price_Per_Item__c}" headerValue="Price Per Item" />
                       <apex:column headerValue="Quantity">
                        <apex:outputField value="{!order.Quantity__c}"  >
                            <apex:inlineEditSupport showOnEdit="update" event="ondblclick" /> 
                        </apex:outputField>
                    </apex:column> 
                    <apex:column headerValue="Total">
                        <apex:inputField value="{!order.Total__c}" />
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi,
What is the relationship between Account and Opportunity?


Thanks.
Hi

I need to cover below class. 

public class JWTDataAccess {
   
public static string getData(Query__c q, Map<string,string> FMD, Salesforce_Org__c org, String accessToken, String queryString, 

String QueryId, string TObject){
            HttpRequest req = new HttpRequest();
            req.setEndpoint(org.REST_endpoint__c +  queryString);
            req.setHeader('Authorization', 'OAuth ' + accessToken);
            req.setCompressed(true);    
            req.setMethod('GET');  
            Http http = new Http();  
            HTTPResponse res = http.send(req);  
            String input = res.getBody();
            //START ADDED DATA TO STAGING
                if (q.UseFieldMappings__c){
                    string TargetObject = TObject;
                    Map<string, string> fielddefinitionmap = FMD;
                    string s1 = input.substring(input.indexOf('['), 1 + input.indexOf(']'));
                    List<sobject> soblist = (List<sobject>)JSON.deserialize(s1, List<sobject>.class);
                    List<SObject> SobjRecords = new List<Sobject>(); 
                        for(SObject s: soblist){
                            Map<String, Object> fieldsToValue = s.getPopulatedFieldsAsMap();
                            sObject targetObj = Schema.getGlobalDescribe().get(TargetObject).newSObject() ;
                            for (String fieldName : fielddefinitionmap.keySet()){
                                string sourcefieldname = fieldName;
                                string targetfieldname = fielddefinitionmap.get(fieldName);
                                object o = fieldsToValue.get(fieldName);
                                if (o!=null)
                                {
                                string fieldvalue = fieldsToValue.get(fieldName).toString(); 
                                String x = (String)targetObj.put(targetfieldname, fieldvalue);
                                }
                                else
                                {
                                    String x = (String)targetObj.put(targetfieldname, fieldName);
                                }
                                }
                            SobjRecords.add(targetObj);}
                    String listType = 'List<' + TargetObject + '>';
                    List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
                    castRecords.addAll(SobjRecords);
                    upsert castRecords;}
            //END ADDED DATA TRANSFORM
            Map<String, object> o = (Map<String, object>) JSON.deserializeUntyped(input);
            string NewQS ='notrequired';
            if(o.get('nextRecordsUrl') != null){NewQS = o.get('nextRecordsUrl').tostring();}
            string resultsString =  input.substring(1, 1000);
            CallOut__c c = new CallOut__c(QueryName__c = QueryId, response__c ='Apex Job JWT Batch: ' + 'Call Out Result = ' + 

resultsString,nexturl__c = NewQS );
            insert c;
            Attachment attachment = new Attachment();
            attachment.Body = Blob.valueOf(input);
            attachment.Name = String.valueOf(q.Query_Name__c + '_'+ q.id + '_' + c.Id + '.txt');
            attachment.ParentId = c.Id;
            insert attachment;
            return NewQS;}}

Any kind of help would be appreciated.

Thanks!
I have looked at this JSON issue for hours and can't figure out what I am missing that creates this error on certain occasions. So sometimes it works and sometimes it fails with following message:"Malformed JSON: Expected '{' at the beginning of object"

Here is the CallOutClass
/*****************************************************************************/
global class AccountNsCalloutClass 
{
@future(callout=true)
 global static void callRemote(Map<ID,String> oid,String operation)
 {
     if(operation=='UPDATE'){     
         System.debug('*************Apex UPdate Execution Started***************** ');
         List<Account> opl= [SELECT AccountSource,isTaxable__c,VAT__c,Fax,Email__c,Client_Class__c,Client_Tier__c,Subsidiary__c,Owner.Name,BillingAddress,BillingCity,BillingCountry,BillingGeocodeAccuracy,BillingLatitude,BillingLongitude,BillingPostalCode,BillingState,BillingStreet,CreatedDate,Description,Id,Industry,IsDeleted,Jigsaw, JigsawCompanyId,LastActivityDate,LastModifiedById,LastModifiedDate,LastReferencedDate,LastViewedDate,MasterRecordId,Name,NSCustomerId__c,NSInternalId__c,NumberOfEmployees,ParentId,Phone,PhotoUrl,ShippingAddress,ShippingCity,ShippingCountry,ShippingGeocodeAccuracy,ShippingLatitude,ShippingLongitude,ShippingPostalCode,ShippingState,ShippingStreet,SicDesc,SystemModstamp,Type,Website,Client_Type__c FROM Account WHERE ID IN:oid.keySet()];  
         List<Account> acc=new List<Account>();
         for(Account op:opl)
         {
             HTTPResponse resp=AccountNsCalloutClass.makeCallout(op,operation);
             system.debug('response@'+resp.getBody());
             AccountToJSONRES jres=(AccountToJSONRES)JSON.deserialize(resp.getBody(),AccountToJSONRES.class);   
         }
         }         
      }
 }
/*****************************************************************************/
And here is the JSON Class:
/*****************************************************************************/
public class AccountToNSJson {
     public String operationType{get;set;}
     public String AccountSource{get;set;}
     public String OwnerName{get;set;}
     public String BillingAddress{get;set;}
     public String BillingCity{get;set;}
     public String BillingCountry{get;set;}
     public String BillingGeocodeAccuracy{get;set;}
     public String BillingLatitude{get;set;}
     public String BillingLongitude{get;set;}
     public String BillingPostalCode{get;set;}
     public String BillingState{get;set;}
     public String BillingStreet {get;set;}
     public String CreatedDate{get;set;}
     public String Description{get;set;}
     public String SFDCAccountId {get;set;}
     public String Industry{get;set;}
     public String IsDeleted{get;set;}
     public String Jigsaw{get;set;}
     public String LastModifiedDate{get;set;}
     public String Name{get;set;}
     public String Salutation{get;set;}
     public String FirstName{get;set;}
     public String LastName{get;set;}
     public String MiddleName{get;set;}
     public String NetsuiteId{get;set;}
     public String NumberOfEmployees {get;set;}
     public String ParentId {get;set;} 
     public String Phone {get;set;}   
     public String PhotoUrl {get;set;}    
     public String ShippingAddress {get;set;}  
     public String ShippingCity {get;set;}   
     public String ShippingCountry {get;set;}    
     public String ShippingGeocodeAccuracy {get;set;} 
     public String ShippingLatitude {get;set;}   
     public String ShippingLongitude {get;set;}    
     public String ShippingPostalCode {get;set;} 
     public String ShippingState {get;set;}   
     public String ShippingStreet {get;set;} 
     public String Fax{get;set;}
     public String Mobile{get;set;}
     public String Title{get;set;}
     public String Email{get;set;}
     public String Subsidiary {get;set;}
     public String SicDesc {get;set;} 
     public String SystemModstamp {get;set;} 
     public String AccountType {get;set;} 
     public String Website {get;set;} 
     public String ClientClass {get;set;} 
     public String ClientTier {get;set;}
     public String ClientType {get;set;} 
     public String CurrencyCode {get;set;}
     public String IsTaxable {get;set;} 
     //AD 20190618 - add VAT#
     public String VAT {get;set;} 
}
/*****************************************************************************/

Thank you for your help!
Hi Mates,

I need a help on integrating salesforce to jira and viceversa without any plugin/addon/third party tools in developer edition

i was trying to push case from salesforce to jira as issue, and it is done using Callout working fine
But also need to push issue from jira to salesforce as case for this i created a webhook and created apex rest api class in salesforce and made that class as public from site, see below class

@RestResource(urlMapping='/JiraToSFRestTest/*')
global class JiraTOSFRestTestController {
  @HttpPost
    global static String doPost(String issueId,String issueKey, String projectId, String projectKey) {
        Case CaseObj = new Case();
        CaseObj.Status = 'Working';
        CaseObj.Origin = 'Web';
        CaseObj.Subject = issueId+'->'+issueKey;
        CaseObj.Description = projectId+'->'+projectKey;
        insert CaseObj;
        return CaseObj.Id;
    }
}


webhook url look like this
https://SaleforceSiteURL/services/apexrest/JiraToSFRestTest?issueId=${issue.id}&issueKey=${issue.key}&projectId=${project.id}&projectKey=${project.key}

I am executing this rest class from workbench then it is working fine but how to call this rest api class directly without login into salesforce from jira webhook

Don't know how to impletement can any one help on this with step by step preocedure please

Awaiting your responce
Trigger is working for all profiles instead of only this profile id. Please how do I correct this

trigger accountdelet on Acount (before delete)
 {
String ProfileId = UserInfo.getProfileId(); 
for (Account a : Trigger.old)     
           
IF(ProfileId!='00721100046VB5L')
{
     a.addError('Not permitted');
    
            }
        }
  • August 30, 2018
  • Like
  • 0
Hi, 

 I am not sure what went wrong there is no changes made to the controller I am receiving below error from one of the controller 

Error: Compile Error: Entity is not org-accessible entity name: RevenueForecast at line 1 column 8

 I see there is no issue no one modified please suggest me what might be the issue what is causing this controller with this error. 

Thanks
Sudhir

 
Hello,

I am system admin , when i try to deploy something, i get below errors

A_test.mytest System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: this ID value isn't valid for the user: 012b0000000TmUJAA0: [RecordTypeId] 
A__test.mytest: line 18, column 1

B_delete_test.mytest1 System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: this ID value isn't valid for the user: 012b0000000TmUJAA0: [RecordTypeId] Class.B_delete_test.mytest1: line 17, column 1

I wonder what can be exact reason ?
  • May 30, 2016
  • Like
  • 0
<apex:page extensions="OnlinePurchaseController" showHeader="false" sidebar="false" standardController="Order__c">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:selectList value="{!selectedCategory}" label="Category" size="1">
                    <apex:actionSupport event="onchange" action="{!getProducts}" reRender="products"/>
                    <apex:selectOptions value="{!category}">
                    </apex:selectOptions>
                </apex:selectList>
             </apex:pageBlockSection>
            
            
             <apex:pageBlockSection >    
                <apex:pageBlockTable value="{!productList}" var="product" id="products">
                    <apex:column >
                        <apex:commandButton value="add" action="{!addToOrder}" reRender="orders,products">
                            <apex:param name="productID" value="{!product.ID}" assignTo="{!productID}"></apex:param>
                           </apex:commandButton>
                    </apex:column>
                    <apex:column value="{!product.Name}" />
                    <apex:column value="{!product.Price_Per_Item__c}" />
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
        <apex:pageBlockSection id="orders">    
                <apex:pageBlockTable value="{!orderList}" var="order" >
                    <apex:column value="{!order.Name}"  headerValue="Name" />
                    <apex:column value="{!order.Price_Per_Item__c}" headerValue="Price Per Item" />
                       <apex:column headerValue="Quantity">
                        <apex:outputField value="{!order.Quantity__c}"  >
                            <apex:inlineEditSupport showOnEdit="update" event="ondblclick" /> 
                        </apex:outputField>
                    </apex:column> 
                    <apex:column headerValue="Total">
                        <apex:inputField value="{!order.Total__c}" />
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hello  Everyone.
Could any one please suggest me how can i translate/Edit  "ERROR"  word on the page??? 
In the provided image you can see that ERROR word in Red color i need to change that to Plosih word.
RED colored Error Word need to be change to POLISH word.