• Nayana K
  • PRO
  • 4167 Points
  • Member since 2014
  • Senior Technology Associate
  • Trekbin


  • Chatter
    Feed
  • 129
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 5
    Questions
  • 717
    Replies
Hi all,

I am working through the Visualforce Mobile trailhead, and in the "Use the Salesforce Lightning Design System to Style Visualforce Pages" module, the first step of the exercise defines this class;
 
<apex:page showHeader="false" standardStylesheets="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0">

  <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en">
    <head>
      <meta charset="utf-8" />
        <meta http-equiv="x-ua-compatible" content="ie=edge" />
        <title>SLDS LatestAccounts Visualforce Page in Salesforce Mobile</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />

      <!-- Import the Design System style sheet -->
      <apex:slds />
    </head>     
    <body>

      <!-- REQUIRED SLDS WRAPPER -->
      <div class="slds-scope">

         <!-- PRIMARY CONTENT WRAPPER -->
         <div class="myapp">

         </div>
         <!-- / PRIMARY CONTENT WRAPPER -->

      </div>
      <!-- / REQUIRED SLDS WRAPPER -->

      <!-- JAVASCRIPT -->
      <!-- / JAVASCRIPT -->
    </body>
  </html>
</apex:page>
When the class is saved, an error is produced:
"The API version you've specified is lower than the minimum version of 39 for the apex:slds object"
This happens in both the developer console and mavensmate/sublime. 

Is there any way to fix this so I can continue the module?

Thanks
**Still Learning**
I am trying to create the Apex Controller that will then be used by the Visualforce page for layouts.  I only want to show the Current Fiscal Period based on Todays date on the Visualforce page.  

Period_FY__c is just a formula field that is a String:  Below is the code for the formula field.
CASE( 
Text(Month(TODAY() )) , 
"1","2", 
"2","3", 
"3","3", 
"4","3", 
"5","4", 
"6","4", 
"7","4", 
"8","1", 
"9","1", 
"10","1", 
"11","2", 
"12","2", 
"" 
)

The code where I am having an error.  If there is a different way this would be written better I am open. (learning)

public with sharing class QuotaRelatedListqtr {

public List <Quota__c> quotas {get;set;}
public List <Business_Plan__c> bp {get;set;}
public List <Period> period {get;set;}
    
Integer FiscalYearStartMonth = 
[select FiscalYearStartMonth from Organization where id=:Userinfo.getOrganizationId()].FiscalYearStartMonth;

String TodaysDate = date.today().format();
     
Public List <Period> Periods = [Select p.Number From Period p 
         Where (p.StartDate <= TODAY AND p.EndDate >= TODAY) and p.type = 'Quarter' Limit 1];


       // Get information about the Quota being worked on
       // Needs to be based on Business Plan per Person 
       // Need to get the correct FY and Correct Quarter based on todays date.    
       // 
public QuotaRelatedListqtr(ApexPages.StandardController controller) {
 quotas = [SELECT Actual_Sales__c, Actual_vs_Quota__c, Annual_Actual_Sales__c, Annual_Quota__c, 
                           Annual_Targeted_New_Business_Sales__c, Business_Plan__c, Fiscal_Period2__c,
                               Quota__c, Sales_Categories__c, Sales_Category_Name__c,  Sales_Needed_to_Hit_Quota__c,Sales_Product_Category__c,
                               Sales_Won__c, Targeted_New_Business__c,Target_vs_Quota__c,Targeted_New_Business_Sales__c
                               FROM Quota__c
                              WHERE Period_FY__c IN :Periods];    
                             
    }
              
}


Here is the Error Message:  Invalid bind expression type of Period for column of type String
I have bolded the line where it is saying the error is.

 
Hi all,

Looking for help on an issue with my controller and visualforce page.

The issue I am having is that the picklist value for 'Interested Technologies' is returning weird results vs. just the name of the account.
User-added image

Here is my controller:
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}
  // the collection of accounts to display
  public Id selectedAccId{get;set;}

  public Boolean IsEmpty {get; set;} 

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String technology = Apexpages.currentPage().getParameters().get('technology');

    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+ '%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+ '%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+ '%\'';  
    if (!technology.equals(''))
      soql += ' and interested_technologies__c includes (\''+technology+'\')';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> technologies {
    get {
      if (technologies == null) {

        technologies = new List<String>();
        Schema.DescribeFieldResult field = Contact.interested_technologies__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());

      }
      return technologies;          
    }
    set;
  }

  /*public List<String> options {
    get {
      if (options == null) {

        options = new List<String>();
        Schema.DescribeFieldResult field = Account.Name.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          options.add(f.getLabel());

      }
      return options;          
    }
    set;
  }*/
  
  //builds a picklist of account names based on their account id

  public List<selectOption> getaccts() {

      List<selectOption> options = new List<selectOption>(); 
  //new list for holding all of the picklist options
      options.add(new selectOption('', '- None -')); 
  //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
      for (Account account : [SELECT Id, Name FROM Account]) { 
  //query for Account records 
          options.add(new selectOption(account.Name, account.Name)); 
  //for all records found - add them to the picklist options
      }
      return options; //return the picklist options
  }

}
Here is my visualforce page:
<apex:page controller="ContactSearchController" sidebar="false">

  <apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Search Collaborative Wide Staff Directory" mode="edit">

  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">

      <apex:pageBlock title="Search Properties" mode="edit" id="criteria">

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementById("technology").options[document.getElementById("technology").selectedIndex].value
          );
      }
      </script> 

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="technology" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Interested Technologies<br/>
          <select id="technology" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!accts}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      <!--<apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions">
          <apex:selectList value="{!options}" multiselect="false" size="1">
                  <apex:selectOptions value="{!accts}"/>
          </apex:selectList>
      </apex:pageBlockSection>-->

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.firstName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.lastName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.name}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Technologies" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="interested_technologies__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.interested_technologies__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

    </td>
  </tr>
  </table>

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>    

  </apex:pageBlock>

  </apex:form>

</apex:page>
What am I missing?   Any help is much appreciated.

 
{"Message":"Number of Post office(s) found: 21","Status":"Success","PostOffice":[{"Name":"Baroda House","Description":"","BranchType":"Sub Post Office","DeliveryStatus":"Non-Delivery","Taluk":"New Delhi","Circle":"New Delhi","District":"Central Delhi","Division":"New Delhi Central","Region":"Delhi","State":"Delhi","Country":"India"}]}

The above is my json string.
I have written the following code deserialize it

global class wrapper{
global class parserr
    {
       global string Message{get;set;}
       global string Status{get;set;} 
       global list<postoffice>po{get;set;}
    }
    global class postoffice
    {
        global string name{get;set;}
        global string Description{get;set;}
        global string BranchType{get;set;}
        global string DeliveryStatus{get;set;}
        global string Taluk{get;set;}
        global string Circle{get;set;}
        global string District{get;set;}
        global string Division{get;set;}
        global string Region{get;set;}
        global string state{get;set;}
        global string country{get;set;}
    }
}

 p= (wrapper.paresrr)JSON.deserialize(JSONresponse, wrapper.parserr.class);
I'm getting the values of Message and status correctly. But list<postoffice> po is getting as null although values are coming into response.And also I want the values in postoffice class also.
Thanks
On an Opportunity, I have created a button to execute Javascript using sforce.apex.execute (I am calling an Apex Class).
The apex class creates a Contract record. I would like to get the record id (of the Contract just created) displayed on an alert after clicking on the button if creation is successful.
_______

{!RequireScript("/soap/ajax/34.0/connection.js")}
{!RequireScript("/soap/ajax/34.0/apex.js")}

function success() {
    // Indicate success
    var alertString="Success!"; 
    window.open('www.google.com');

    alert(alertString); 
}
function error() {
    // Indicate failure
    //window.open('www.yahoo.com');
    var alertString="Fail!"; 
    alert(alertString); 
}
sforce.connection.sessionId = "{!$Api.Session_ID}";
sforce.apex.execute("InsertContractAndPO", "createContractAndPOAsset",
{ accountId: "{!Opportunity.AccountId}", opportunityId: "{!Opportunity.Id}" }, 
{ onSuccess:success , onFailure: error});



 
component : - <aura:component controller="updatecaseowner" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
         
    <aura:attribute name="case" type="Case[]"/>
     <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="disabled" type="Boolean" default="False" />        
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
   
    <div class="slds-button-group" role="group">
    
    <ui:button aura:id="button" class="slds-button slds-button--brand slds-size--1-of-1"
           label="Change Owner" press="{!c.onclick}" />
        
    </div>
</aura:component>



controller :-
({    
init : function(component, event, helper) {
    var action = component.get("c.getCase");
    action.setParams({"recordId": component.get("v.recordId")});

       console.log(action);
    
    action.setCallback(this, function(response) {
        var state = response.getState();
 
        if( state == "SUCCESS"){
                        //component.set("v.disabled", "True");
                    component.set("v.case", response.getReturnValue()); }
                         
         else {
            console.log('There was a problem : '+response.getError());
        }
         $A.enqueueAction(action);
    });
   
},
    onclick : function(component, event, helper) {
    var result = confirm("Do you Really want to change the owner details");
     if(result)  { 
    var action = component.get("c.saveCase");
                        console.log(component.get("v.recordId"));
        action.setParams({"recordId": component.get("v.recordId")});
                          console.log('done');
                        console.log(component.get("v.recordId"));
     
        action.setCallback(this, function(response) {
        var state = response.getState();
          console.log(state);
        if(state === "SUCCESS") {
            //var caserec = component.get("v.case"); 
           // caserec.push(); 
            component.set("v.case",response.getReturnValue());
           console.log('here');
            console.log(response.getReturnValue());
        }
        else if(state === "ERROR")
        { alert("Case has no Related records");}
        });
          $A.enqueueAction(action);
    }
}
})

apex :- public class updatecaseowner {
    
@AuraEnabled
public static Case getCase(Id recordId){
   return [SELECT Id , ownerId, ParentID  FROM Case WHERE id =:recordId];

}

@AuraEnabled
public static Case saveCase(Id recordId){
    Case caseRec = [SELECT Id, ownerId, ParentID ,  Status FROM Case WHERE parentId=:recordId];
    Case caseP = [SELECT ID , ownerID from case where id= :recordId ];    
    if (caseRec!=null)
        
    {
     
            caseRec.ownerID= casep.OwnerId;
    

    update caseRec;
    return caseRec; 
    }
   
return caserec;
}}
I would like to write a Save URL for a Force.com Guest Site User who completes a small form and saves it to a custom object.

I'm emailing clients a link to the form with: 

http://corere1.force.com/bkmilestone1?id={!Bankruptcy__c.Id}

I wrote a small Force.com page that basically just says "Thank you" and nothing else for when they click save.

I tried: 

http://corere1.force.com/bkmilestone1?id={!Bankruptcy__c.Id}&SaveURL=http://corere1.force.com/thankyou

But it still tries to redirect to the record which gives them the Authentication Error.

Is there a way to write the URL directly into the Visualforce page?

Here's the end of the form:
</apex:pageBlockSection>
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

And I'd like it to end with http://corere1.force.com/thankyou.

Hello Everyone,

I am Unable to see the logs in the Developer console for the Force.com sites...!!

Does any one know how to solve this Problem

HI,
I am using a simple trigger in my application to fetch duplicate accounts based on the account name, city and street.
This trigger is working perfect while a new account is saved. If there is a match it is alerting the user and if no duplicates found, it is saved in SF.

But for edit account, it is working correct when there is a duplicate is present. If there is no duplicate account present in SF it is alerting an incorrect message followed with an error message to the user.
  • You cannot create a duplicate account here as the Name 'Test Acc1' and Phone '(000) 000-0000' already belongs to a different account.
  • The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 301j0000000bv9s. Flow error messages: <b>An unhandled fault has occurred in this flow</b><br>An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information. Contact your administrator for help
Could you please help me out on this..?
Below is the trigger code...

trigger AccountDuplicateTrigger on Account (before insert, before update)
{        
    for(Account a:Trigger.new)    
    {
        if(Trigger.isBefore)
        {       
            string dupItem = '';
             List<Account> acc= new List<Account>();      
            if(Trigger.isInsert)
            {                   
                if(a.Name !='')
                {                                                              
                       if((a.BillingStreet != null) && (acc.isEmpty()))
                       {
                            acc=[select ID from account where Name=:a.Name and BillingStreet=:a.BillingStreet];
                            if(acc.isEmpty()==False)                                                              
                                  dupItem='Name \''+ String.escapeSingleQuotes(a.Name)+'\' and Billing street \''+
                                  String.escapeSingleQuotes(a.BillingStreet)+'\'';
                      }
                      if((a.BillingCity != null) && (acc.isEmpty()))
                      {
                            acc=[select ID from account where Name=:a.Name and BillingCity=:a.BillingCity];    
                            if(acc.isEmpty()==False)
                                dupItem='Name \''+ String.escapeSingleQuotes(a.Name)+'\' and Billing city \''+
                                String.escapeSingleQuotes(a.BillingCity)+'\'';
                      }
                      //Alerts the user if any matching record present in the system and can't allows to save it.                       
                      if(acc.isEmpty()==False) {
                           if(!test.isRunningTest())
                           {
                                a.adderror('You cannot create a duplicate account here as the '+dupItem+' already belongs to a different account.');     
                           }
                     }   
             }
      } 
      else if(Trigger.isUpdate)
      {
            if(a.Name !='')
                {                                                                
                       if((a.BillingStreet != null) && (acc.isEmpty()))
                       {
                            acc=[select ID from account where Name=:a.Name and BillingStreet=:a.BillingStreet];
                            if(acc.isEmpty()==False)                                                              
                                  dupItem='Name \''+ String.escapeSingleQuotes(a.Name)+'\' and Billing street \''+
                                  String.escapeSingleQuotes(a.BillingStreet)+'\'';
                      }
                      if((a.BillingCity != null) && (acc.isEmpty()))
                      {
                            acc=[select ID from account where Name=:a.Name and BillingCity=:a.BillingCity];    
                            if(acc.isEmpty()==False)
                                dupItem='Name \''+ String.escapeSingleQuotes(a.Name)+'\' and Billing city \''+
                                String.escapeSingleQuotes(a.BillingCity)+'\'';
                      }
                      //Alerts the user if any matching record present in the system and can't allows to save it.                       
                      if(acc.isEmpty()==False) {
                           if(!test.isRunningTest())
                           {
                                a.adderror('You cannot create a duplicate account here as the '+dupItem+' already belongs to a different account.');     
                           }
                     }   
             }
      } 
}
}
}
Hello Awesome Developers! 

I am hoping one of you heroes out there can help me with a requirmeent I have.  Let me be up front, I have not been developing in apex for long and have not had any other developign experience with code in any other language or platform, so in other words a newbie. :)

So here is the deal, I have a need to have opportnities created every night based upon another object having records created the previous day. This object is a Zuora application object called Subscriptions and a record would be created whenever a customer of ours would use our self servic eportal (outside of Salesforce) to perform an upgrade or downgrade of thier services.  This action by the customer will create a Subscription record in Salesforce and when those get created I need every night to create an Upgrade or downgrade Opportunity from those subscription records created. Also we need to batch the same customer so if they do 3 upgrades, we take the amount from all three subscription records and sum them so that we only create one opportunity per customer for upgrades and an opportunity for downgrades and then have the Amoutn field on th enewly created opp be the total sum of the Upgrade subscription records and if there are downgrades, the same would need to happen to sum all of those downgrade record amounts into one opp and the amount would be that SUM.  

Please see my attempt at this code below, where I am setting the class as a scheduled class, and when I run this in the Dev console no opps are bneing created even though I have subscription records I manually created for this test.  That is issue number one, gettign this to create opps, but I havent gotten as far to test if the Aggregate function being used will do the magic of SUMing thw amounts and only creating one opportunity per account for all upgrades and one opp for all downgrades for that account. 

I hope this makes sense, I am just tryign to once a night, grab all subscriptions created for that day (Actually this will run at 2AM so createddate would be the day before) and then rn though those Subscription records and create one opp per account and have the amoutn be the sum for both types (Upgrades and downgrades) 

Thank you very much for your help! 

Shawn
 
global class CreateUpgradeDowngradeOpportunities Implements Schedulable
{
     global void execute(SchedulableContext sc)
      {
            CreateOpportunities();
      }
      
      public void CreateOpportunities()
      {
         Date d1 = system.today()-1;
         List<Zuora__Subscription__c> SubsCreated = [SELECT Id, Name, Zuora__Account__c, Zuora__MRR__c, Zuora__Status__c FROM Zuora__Subscription__c WHERE CreatedDate =: d1];
          
          For(Zuora__Subscription__c z : SubsCreated){
              If(z.Zuora__Status__c == 'Cancelled'){
                  AggregateResult[] groupedResultsDown = [SELECT Zuora__Account__c , SUM(Zuora__MRR__C) FROM Zuora__Subscription__c WHERE ID IN: SubsCreated GROUP BY Zuora__Account__c];
                 //Create Downgrade Opp 
                 
                  List<Opportunity> downgradeOpps = new List<Opportunity>();
                 
                  For(AggregateResult ard : groupedResultsDown){
                   
                      Opportunity od = new Opportunity();
                      	od.RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Downgrade').getRecordTypeId();
                      	od.OwnerId = z.Zuora__Account__r.OwnerId;
                      	od.Name = z.Zuora__Account__r.Name + ' - AMP';
                      	od.AccountId = z.Zuora__Account__r.Id;
                      	//od.Armor_Product_Category__c
                      	//od.Armor_Product__c	
                      	//od.Armor_Anywhere_Location__c
                      	od.Opportunity_Source__c = 'Portal';
                      	od.Type = 'Downgrade';
                      	od.Amount = z.Zuora__MRR__c * -1;
                      	od.CurrencyIsoCode = z.CurrencyIsoCode;
                      	od.CloseDate = d1;
                      	od.StageName = 'Cancelled';
                      
                      downgradeOpps.add(od);
                      //End of Creating Downgrade Opp
                  } // End of GroupedResultDown For Loop
                  
                  insert downgradeOpps;
                  
              }
              Else If(z.Zuora__Status__c == 'Active'){
                  AggregateResult[] groupedResultsUp = [SELECT Zuora__Account__c , SUM(Zuora__MRR__C) FROM Zuora__Subscription__c WHERE ID IN: SubsCreated GROUP BY Zuora__Account__c];
                 //Create Upgrade Opp 
                 
                 List<Opportunity> upgradeOpps = new List<Opportunity>();
                  For(AggregateResult aru : groupedResultsUp){
                    
                        
                      Opportunity ou = new Opportunity();
                     	ou.RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Upgrade').getRecordTypeId();
                      	ou.OwnerId = z.Zuora__Account__r.OwnerId;
                      	ou.Name = z.Zuora__Account__r.Name + ' - AMP';
                      	ou.AccountId = z.Zuora__Account__r.Id;
                      	//ou.Armor_Product_Category__c
                      	//ou.Armor_Product__c	
                      	//ou.Armor_Anywhere_Location__c
                      	ou.Opportunity_Source__c = 'Portal';
                      	ou.Type = 'Existing Business';
                      	ou.Amount = z.Zuora__MRR__c;
                      	ou.CurrencyIsoCode = z.CurrencyIsoCode;
                      	ou.CloseDate = d1;
                      	ou.StageName = 'Closed Won';
                      
                      upgradeOpps.add(ou);
                      //End of Creating Upgrade Opp

                  } // End of GroupedResultUp For Loop
                 
                 insert upgradeOpps;
              }
              
          } // End of SubsCreated For Loop
         
          
      } //End of CreateOpportunities Method
} // End Of Class

 
Hi,

  I wrote below trigger and helper class which is working fine need your suggestion how to modify the code to handle bulk transaction please suggest me.
Trigger

trigger CtapAssessmentTrigger on CTAP_Assessment__c (before Insert, before Update) {

     if(Trigger.isBefore) {
       if(Trigger.isInsert) {
            CtapAssessmentTriggerUtils.processInsert(Trigger.new);
        } else if(Trigger.isUpdate) {
            CtapAssessmentTriggerUtils.processUpdate(Trigger.newMap, Trigger.oldMap);                     
        }
} 


Helper Class

public class CtapAssessmentTriggerUtils {
  
   
    public static void processInsert(List<CTAP_Assessment__c> newLst) {
       for(CTAP_Assessment__c  ctap : newLst){
              ctap.Contact__c = CtapAssessmentTriggerUtils.GetContact(ctap.Partner_email__c);
              ctap.Lead__c = CtapAssessmentTriggerUtils.GetLead(ctap.Partner_email__c);
              }  
       
    }
    
    public static void processUpdate(Map<id,CTAP_Assessment__c> newMap, Map<id,CTAP_Assessment__c> oldMap) {
    
      for(CTAP_Assessment__c  ctap : newMap.values()){
              ctap.Contact__c = CtapAssessmentTriggerUtils.GetContact(ctap.Partner_email__c);
              ctap.Lead__c = CtapAssessmentTriggerUtils.GetLead(ctap.Partner_email__c);
              }  
    
    }
    
   
   public static String GetContact(String partneremail){
    
    String ContID;   
    list<Contact> con = [select id,email from contact where email = :partneremail];  
     
      if( con.size()>0){
        ContID = con[0].id;
       }
     
     return ContID; 
   }
   
   public static String GetLead(String partneremail){
     String LedID;
     list<Lead> led = [select id, email from lead where email = :partneremail];  
     
      if (led.size() > 0){
        LedID = led[0].id;
       }
     
     return LedID;
   }
    
    
}

Thanks
Sudhir
Hi all, I am new to Visualforce and is trying to create an export button for a custom object related list; I am getting an error when trying to save;  

Error: Unknown property 'OnePlace__Function__cStandardController.OnePlace__Function'

<apex:page standardController ="OnePlace__Function__c" contentType="application/vnd.ms-excel">
    <apex:pageBlock title="Invitees">
        <apex:pageBlockTable value="{!OnePlace__Function.OnePlace__Invitee__r}" var="item"> 
            <apex:column value="{!item.Name}"/> 
            <apex:column value="{!item.Initial_Contact__c}"/>
            <apex:column value="{!item.Investor_Contact__c"/>
            <apex:column value="{!item.NDA_Sent__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>                          
</apex:page>

Thank you for your helping a noob!

Hi,

I am trying to deploy a Change Set from my Sandbox to PROD Org however when I select to "Upload" the Change Set I receive the following error:
"This organization isn't authorized to upload change sets to other organizations. For authorization, contact the deployment connections administrators on the organizations where you want to upload changes.".

My profile is set up as a System Administrator for my Org.

Is anyone able to assist?

Thanks
 
This might be really simple, but I'm banging my head over this Test Class for an custom controller Apex Class.

A snippet of the Apex Class:
public class GoalChart {
    public Integer getAryCalls(){return (Integer) [SELECT count() FROM Task WHERE skyplatform__Is_Call_Record__c = TRUE And CreatedDate = THIS_MONTH And CreatedById = '0056A000001IVgU'];} 

}

Is this close to the right markup for the TestClass? I'm getting so many "variable does not exist" errors that I can't even know if I'm headed in the right direction.
@isTest
public class GoalChartTest{
    
    GoalChart gc = new GoalChart();
    
    static TestMethod TestAryCalls{
    system.assert(0,gc.AryCalls)
    }
 }
Any help would be greatly appreciated. Thank you.

 
Hi , I am also facing some problem with salesforce Trailhead SOQL injection Challenge, I tried many ways but still i am getting error .
can you suggest me where i am going wrong ?
​Thank you 

SOQL_Injection_Challenge:

public class SOQL_Injection_Challenge {
    public string textual {get; set;}
    public List<Supply__c> whereclause_records {get; set;}
//SELECT Id,Name,Quantity__c,Storage_Location__c,Type__c FROM Supply__c
    public PageReference whereclause_search(){
        string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';
        string whereClause = '';
        if(textual != null && textual!=''){
                whereClause += 'name like  \'%'+textual+'%\' ';
        }
        if(whereClause != ''){
            whereclause_records = database.query(query+' where '+whereClause+' Limit 10');
            validate(whereClause,whereclause_records.size());
        }
        return null;
    }
    public void validate(string s, integer i){
      if(s.contains('\'%') && s.containsIgnoreCase('Nobles_Only__c') && s.contains('%\'') && i<10){
        cvcs__c  v = cvcs__c.getInstance('sic1');
        if(v==null){
          v = new  cvcs__c(name='sic1',c1__c = 1);
        } else {
            v.c1__c += 1;
        }
        upsert v;
      }
    } 

}
  • September 25, 2017
  • Like
  • 0
Hi,
I have a custom object, with one checkbox field as "Record Used". I want to know that if the remaining Record Used with checkbox not ticked ( false) become less than or equal to 100, it should send us the email alert, so that we can add more records to be used .
I am trying to create a formula field for this but i think its not going to work, can anyone plz suggest me a solution for this ? its within the same object and there is no cross object involved.Thnx
,
Hi,
I have a Lightning Component that display a simple value and need a conditional formating depending of the value. The component display the correct value but my if statement to set the color is not working. Could you please tell me what is wrong with my code? Thanks in advance for your help.

Result (should be green)
User-added image
Component
<aura:component controller="MyCPDPointsThisYearAPEXController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
 
    <aura:attribute name="status" type="String" /> 
    <aura:attribute name="myPoints" type="CPD_Points_Total__c" />
    <aura:attribute name="ID" type="String" />      
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <lightning:card title="{! 'My CPD Points for ' + v.myPoints.CPD_Year__c}" >    
        <p class="slds-p-horizontal--small slds-align_absolute-center" >
             <div aura:id="chart" >
                <lightning:layout >
                    <lightning:layoutitem class="{! 'points-block ' + v.status}" >
                        <div class="points">{!v.myPoints.Total_Points__c}</div>points  
                    </lightning:layoutitem>                                    
                </lightning:layout>
             </div> 
            </p>  
    </lightning:card>
</aura:component>

Javascript Controller
({
    doInit : function(component) {       
        
        var action = component.get("c.getMyPoints");    
        action.setParams ({
            ID :component.get("v.ID")                         
        })         
        action.setCallback(this, function(actionResult) {    
            component.set("v.myPoints", actionResult.getReturnValue());
            
        var status ;
            var totalpoints = "Total_Points__c";
            if (totalpoints > 25){
                status = "green";
            } else {
                status = "orange";
            }            
            component.set("v.status", status);

        });        
        
        $A.enqueueAction(action);     
    }
})
Style
.THIS .points-block {
	text-align: center;
    margin-right: 8px;
    padding: 8px 12px;
    border-radius: 0.25rem;
    border: solid 1px rgb(216, 221, 230);
} 
.THIS .points-block.green {
	color: #008000;
    border: solid 3px #008000;
} 
.THIS .points-block.orange {
	color: #ff6633;
    border: solid 3px #ff6633;
} 
.THIS .points {
	font-size: 32px;
	line-height: 32px;
	font-weight: 500;
    margin-right: 12px;
    margin: 0;
    padding: 0;
} 
.THIS .chart {
    position: relative;
    height: 40px;
}
APEX Controller
public class MyCPDPointsThisYearAPEXController {
     
   @AuraEnabled
    public static CPD_Points_Total__c  getMyPoints(Id ID){        
        
        if (ID ==null){
        return [select Id, CPD_Year__c, Total_Points__c from CPD_Points_Total__c where (Contact_ID_Test__c = 1 or Contact_ID_HO_Test__c = 1) and (CreatedDate = THIS_YEAR) LIMIT 1] ;     
        }
        
        List<CPD_Points_Total__c> points = [select Id, CPD_Year__c, Total_Points__c from CPD_Points_Total__c where (Id = :ID) and  (Contact_ID_Test__c = 1 or Contact_ID_HO_Test__c = 1) and (CreatedDate = THIS_YEAR) LIMIT 1] ;     
       
        if (points.size() ==0){
            return [select Id, CPD_Year__c, Total_Points__c from CPD_Points_Total__c where (Contact_ID_Test__c = 1 or Contact_ID_HO_Test__c = 1) and (CreatedDate = THIS_YEAR) LIMIT 1] ;     
        }else {            
            return points[0];
        }         
    }     
}

 
Hey Folks,

I am writing my first non-tutorial trigger and could use some help. What is supposed to happen is that when an RFI record of record type A is created and child Submittal record should also be created. I need to set a bunch of field values but I am comfortable with that, just trying to get the skeleton to work. However, when I create an RFI with record type A no Submittal record is created. This is my trigger. Issue_Tracker__c is the lookup on the Submittal to the RFI

trigger NewSubmittal on Request_for_Information_RFI__c (after insert) {
    
    for ( Request_for_Information_RFI__c ss : trigger.new) {
        
        if( ss.RecordTypeId == '012800000007gsp' )
        
            continue;
        
        Submittal_1__c s = new Submittal_1__c();
        s.Issue_Tracker__c = ss.Id;
        
        insert s;
        
    }

}
I have OnClick Javascript code on a custom Convert button on a Lead page that I'm trying to modify by adding another check, but I got this error.  What am I doing wrong?

***************************
if((ISPICKVAL( Check_Box_c=false))) 

alert('Checkbox must be checked before proceeding'); 


if('{!Lead.Status}'!='Qualified') 

alert('Status should be Qualified to convert the Lead'); 


else 

window.location.href='/lead/leadconvert.jsp?retURL={!Lead.Id}&id={!Lead.Id}' 
}
Hello

We have a custom object (QuoteOrder__c) which is the child in a master-detail relationship with Opportunity.

On my visualforce page my intention is to have it display the Contacts on the Opportunity (via OpportunityContactRole) once you have selected an opportunity from the lookup dialog. I've tried this and it works fine until you change the text in the opportunity field and click or tab out of the field (and therefore clear the underlying Opportunity Id) at which point the page reloads and just gives me the error "SObject row does not allow errors".


For simplicity, I've reduced my page down to just this:
<apex:page controller="QuoteOrder">
    <apex:form >
        <apex:pageBlock>
            <apex:pageBlockSection columns="1"> 
                <apex:inputField value="{!quoteOrder.OpportunityLink__c}" id="opportunity" label="Opportunity">
                    <apex:actionSupport event="onchange" rerender="details" />
                </apex:inputField>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection columns="1" id="details">
                <!-- Other stuff will go here when an opportunity is selected -->
                <apex:messages></apex:messages>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

And I've reduced my controller down to just this:
public with sharing class QuoteOrder {
    public QuoteOrder__c quoteOrder { get; set; }

    public QuoteOrder() {
        this.quoteOrder = (QuoteOrder__c)QuoteOrder__c.SObjectType.newSObject(null, true);
    }
}

I assume it's upset because in the master-detail relationship the opportunity is a compulsory field and the page is submitting with no value. To this end, I have used jquery to check the value of the underlying Id when the blur event is activated, and then if the Id is undefined I have used event.preventDefault() but the page still submits and presents me with the error message. Can anybody suggest how I can stop it submitting in this situation please?

Thank you
Richard
Hi All,

I have reached the last unit of the https://trailhead.salesforce.com/modules/sfdx_app_dev/units/sfdx_app_dev_setup_dx module yesterday and thought of continuing today. But unfortunately, force:org:open -u TempUnmanaged command is throwing an error. This command was working properly yesterday.

Please guide me.
 
D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:list --verbose
	=== Orgs
		 ALIAS   USERNAME              ORG ID              CONNECTED STATUS
	───  ──────  ────────────────────  ──────────────────  ────────────────
	(D)  DevHub  devhub@trailhead.com  00D7F000002ZgNYUA0  Connected


	  ALIAS          SCRATCH ORG NAME  USERNAME                            ORG ID
			   STATUS  DEV HUB             CREATED DATE                  INSTANCE UR
	L                                              EXPIRATION DATE
	  ─────────────  ────────────────  ──────────────────────────────────  ─────────
	─────────  ──────  ──────────────────  ────────────────────────────  ───────────
	─────────────────────────────────────────────  ───────────────
					 Demo Company      test-jm9x2pkl2h0s@demo_company.net  00D0l0000
	000XA6EAM  Active  00D7F000002ZgNYUA0  2017-10-13T10:52:15.000+0000  https://jav
	a-data-5232-dev-ed.cs58.my.salesforce.com      2017-10-20
	  GeoAppScratch  Demo Company      test-ty4lfw6cokgv@demo_company.net  00D0l0000
	000XHrEAM  Active  00D7F000002ZgNYUA0  2017-10-16T11:24:11.000+0000  https://pag
	e-data-2087-dev-ed.cs58.my.salesforce.com      2017-10-23
	  GeoTestOrg     Demo Company      test-plhfjartzy94@demo_company.net  00D0l0000
	000XIFEA2  Active  00D7F000002ZgNYUA0  2017-10-16T12:59:28.000+0000  https://cus
	tomer-ruby-9006-dev-ed.cs58.my.salesforce.com  2017-10-23
	  TempUnmanaged  Demo Company      test-eflatimr9jvm@demo_company.net  00D0l0000
	000XHqEAM  Active  00D7F000002ZgNYUA0  2017-10-16T13:28:46.000+0000  https://dat
	a-force-9071-dev-ed.cs58.my.salesforce.com     2017-10-23



	D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:open -u TempUnmanaged
	ERROR:  Failed to decipher auth data. reason: Unsupported state or unable to aut
	henticate data.

	D:\Nayana D Drive\Nayana\Trailhead Stuff\SFDX Trail\MutualFundExplorer>sfdx forc
	e:org:open -u TempUnmanaged --json
	{"message":"Failed to decipher auth data. reason: Unsupported state or unable to
	 authenticate data.","status":1,"stack":"authDecryptFailed: Failed to decipher a
	uth data. reason: Unsupported state or unable to authenticate data.\n    at ALME
	rror (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\salesforce
	-alm\\dist\\lib\\almError.js:35:19)\n    at Crypto.decrypt (C:\\Users\\Nayana\\A
	ppData\\Local\\sfdx\\plugins\\node_modules\\salesforce-alm\\dist\\lib\\crypto.js
	:157:19)\n    at Object.keys.forEach (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\p
	lugins\\node_modules\\salesforce-alm\\dist\\lib\\configValidator.js:61:36)\n
	at Array.forEach (<anonymous>)\n    at crypto.init.then (C:\\Users\\Nayana\\AppD
	ata\\Local\\sfdx\\plugins\\node_modules\\salesforce-alm\\dist\\lib\\configValida
	tor.js:51:37)\n    at tryCatcher (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugi
	ns\\node_modules\\bluebird\\js\\release\\util.js:16:23)\n    at Promise._settleP
	romiseFromHandler (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_module
	s\\bluebird\\js\\release\\promise.js:510:31)\n    at Promise._settlePromise (C:\
	\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\relea
	se\\promise.js:567:18)\n    at Promise._settlePromise0 (C:\\Users\\Nayana\\AppDa
	ta\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\release\\promise.js:612:10
	)\n    at Promise._settlePromises (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plug
	ins\\node_modules\\bluebird\\js\\release\\promise.js:691:18)\n    at Async._drai
	nQueue (C:\\Users\\Nayana\\AppData\\Local\\sfdx\\plugins\\node_modules\\bluebird
	\\js\\release\\async.js:138:16)\n    at Async._drainQueues (C:\\Users\\Nayana\\A
	ppData\\Local\\sfdx\\plugins\\node_modules\\bluebird\\js\\release\\async.js:148:
	10)\n    at Immediate.Async.drainQueues (C:\\Users\\Nayana\\AppData\\Local\\sfdx
	\\plugins\\node_modules\\bluebird\\js\\release\\async.js:17:14)\n    at runCallb
	ack (timers.js:781:20)\n    at tryOnImmediate (timers.js:743:5)\n    at processI
	mmediate [as _immediateCallback] (timers.js:714:5)","name":"authDecryptFailed","
	warnings":[]}

I followed https://salesforce.stackexchange.com/questions/188735/im-unable-to-use-sfdx-forceorgopen-command-after-authorizing-an-org-via-the-s link's answer, still no luck.
 

 
DateTime dtOrigin = DateTime.newInstance(2017, 03, 12, 2, 3, 0);
DateTime startDateOfSchedule = dtOrigin;
String timeVal = ' 02:03';
Date startDate = date.newinstance(startDateOfSchedule.year(), startDateOfSchedule.month(), startDateOfSchedule.day());

system.debug('=dtOrigin=='+dtOrigin);
system.debug('=startDateOfSchedule=='+startDateOfSchedule);
system.debug('=timeVal=='+timeVal);
system.debug('=startDate=='+startDate);
system.debug('=Formatted startDate=='+startDate.format());
DateTime dtVal = DateTime.parse(startDate.format()+''+timeVal);
system.debug('=dtVal=='+dtVal);

I have a problem in VF page for particular date time in apex controller. Above is snippet which I ran in dev console and got same error like appeared in VF.
In the above code, I am getting 'Invalid date/time: 12/03/2017 02:03'

If I change DateTime dtOrigin = DateTime.newInstance(2017, 03, 12, 2, 3, 0); to DateTime dtOrigin = DateTime.newInstance(2017, 03, 13, 2, 3, 0);, I won't get error of invalid datetime while parsing DT and assining into dtVal variable. I wonder, why this behaviour only for this specific date and that too for 2hours:some minutes.  

For other date and time combo, there is no error. I find hard time in understanding this.

Please help.
Hi All,

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 0032800000VuJdTAAV; first error: DELETE_FAILED, Your attempt to delete Sam the ninja could not be completed because it is associated with the following adventure packages.: null, null : []

I am stuck with this error from long time.

I checked with debug logs when challenge tries to test our work. It is :
 
Execute Anonymous: Contact sam = new Contact(firstname='Sam', lastname='the ninja');
Execute Anonymous: insert sam;
Execute Anonymous: Opportunity opp = new Opportunity(name='Make Kite to Fly', stagename='New', closedate=date.today());
Execute Anonymous: insert opp;
Execute Anonymous: // insert product
Execute Anonymous: Product2 product = new Product2(name='Butterfly Net', isActive=true);
Execute Anonymous: insert product;
Execute Anonymous: // insert the pricebookentry
Execute Anonymous: Pricebook2 stdPrice = [Select id from Pricebook2 where isStandard=true limit 1];
Execute Anonymous: PricebookEntry pbe = new PricebookEntry( IsActive = true, Product2Id = product.id, UnitPrice = 2.00, Pricebook2Id = stdPrice.Id);
Execute Anonymous: insert pbe;
Execute Anonymous: // create the opp line item
Execute Anonymous: OpportunityLineItem oli1 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2050, 1, 1), explorer__c = sam.id);
Execute Anonymous: OpportunityLineItem oli2 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2010, 1, 1), explorer__c = sam.id);
Execute Anonymous: insert oli1;
Execute Anonymous: insert oli2;
Execute Anonymous: // this will create a fulfillment record
Execute Anonymous: // find the fulfillment -- by AdventurePackageId__c which is the opp line item
Execute Anonymous: Fulfillment__c f1 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli1.Id];
Execute Anonymous: Fulfillment__c f2 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli2.Id];
Execute Anonymous: // update the fulfillment and set to cancelled
Execute Anonymous: f1.Status__c = 'Cancelled';
Execute Anonymous: update f1;
Execute Anonymous: f2.Status__c = 'Cancelled';
Execute Anonymous: update f2;
Execute Anonymous: // get the fulfillment again to check the values
Execute Anonymous: oli1 = [select id, unitprice from OpportunityLineItem where Id = :oli1.Id];
Execute Anonymous: oli2 = [select id, unitprice from OpportunityLineItem where Id = :oli2.Id];
Execute Anonymous: // make sure the deposit matches the unit price
Execute Anonymous: System.assertEquals(f1.deposit__c, oli1.unitprice); // one way in the future
Execute Anonymous: System.assertNotEquals(f2.deposit__c, oli2.unitprice); // one way in the past
Execute Anonymous: // clean up
Execute Anonymous: delete opp;
Execute Anonymous: delete f1;
Execute Anonymous: delete f2;
Execute Anonymous: delete product;
Execute Anonymous: delete sam;

I tiried the same in anonymous window except the code of deleting records and there is no error. It means challenge is actually passed. But deleting test records causing error :
User-added image


Please help.
 
Hi Developers,

TREKBIN is hiring 2-5 years of experienced salesforce developers.

Interested candidates, please mail your updated resume to nayana.kashigowda@trekbin.com.

Location : Mumbai, Bangalore.
Here is my code below:

<ul id="insideScroller" class="scrollable-menu scrollbar list-group" style="-webkit-overflow-scrolling: touch;" >
<aura:iteration var="sobj" items="{!v.SobjectRecords}">
<!-- Navigation to record detail page works only SF1-->
<li class="list-group-item" id="{!sobj.SId}" onclick="{!c.navigateToRecord}" >
<aura:renderIf isTrue="{!0 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[0]} : {!sobj.f1}<br/>
</aura:renderIf>
<aura:renderIf isTrue="{!1 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[1]} : {!sobj.f2}<br/>
</aura:renderIf>
<aura:renderIf isTrue="{!2 lt v.fieldsToDisplayCount}"> {!v.lstFldDisp[2]} : {!sobj.f3}<br/>
</aura:renderIf> </li>
</aura:iteration>
</ul>
I am using bootstrapcss in which I am able to see scrollbar in SF1 and even on the desktop.But when I load the same page in mobile the scrollbar disappears.

Any workarounds over this?
Hi All,

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 0032800000VuJdTAAV; first error: DELETE_FAILED, Your attempt to delete Sam the ninja could not be completed because it is associated with the following adventure packages.: null, null : []

I am stuck with this error from long time.

I checked with debug logs when challenge tries to test our work. It is :
 
Execute Anonymous: Contact sam = new Contact(firstname='Sam', lastname='the ninja');
Execute Anonymous: insert sam;
Execute Anonymous: Opportunity opp = new Opportunity(name='Make Kite to Fly', stagename='New', closedate=date.today());
Execute Anonymous: insert opp;
Execute Anonymous: // insert product
Execute Anonymous: Product2 product = new Product2(name='Butterfly Net', isActive=true);
Execute Anonymous: insert product;
Execute Anonymous: // insert the pricebookentry
Execute Anonymous: Pricebook2 stdPrice = [Select id from Pricebook2 where isStandard=true limit 1];
Execute Anonymous: PricebookEntry pbe = new PricebookEntry( IsActive = true, Product2Id = product.id, UnitPrice = 2.00, Pricebook2Id = stdPrice.Id);
Execute Anonymous: insert pbe;
Execute Anonymous: // create the opp line item
Execute Anonymous: OpportunityLineItem oli1 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2050, 1, 1), explorer__c = sam.id);
Execute Anonymous: OpportunityLineItem oli2 = new OpportunityLineItem(OpportunityId=opp.Id, UnitPrice=2, quantity=1,pricebookentryid=pbe.Id, servicedate = date.newInstance(2010, 1, 1), explorer__c = sam.id);
Execute Anonymous: insert oli1;
Execute Anonymous: insert oli2;
Execute Anonymous: // this will create a fulfillment record
Execute Anonymous: // find the fulfillment -- by AdventurePackageId__c which is the opp line item
Execute Anonymous: Fulfillment__c f1 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli1.Id];
Execute Anonymous: Fulfillment__c f2 = [select id, deposit__c from Fulfillment__c where AdventurePackageId__c = :oli2.Id];
Execute Anonymous: // update the fulfillment and set to cancelled
Execute Anonymous: f1.Status__c = 'Cancelled';
Execute Anonymous: update f1;
Execute Anonymous: f2.Status__c = 'Cancelled';
Execute Anonymous: update f2;
Execute Anonymous: // get the fulfillment again to check the values
Execute Anonymous: oli1 = [select id, unitprice from OpportunityLineItem where Id = :oli1.Id];
Execute Anonymous: oli2 = [select id, unitprice from OpportunityLineItem where Id = :oli2.Id];
Execute Anonymous: // make sure the deposit matches the unit price
Execute Anonymous: System.assertEquals(f1.deposit__c, oli1.unitprice); // one way in the future
Execute Anonymous: System.assertNotEquals(f2.deposit__c, oli2.unitprice); // one way in the past
Execute Anonymous: // clean up
Execute Anonymous: delete opp;
Execute Anonymous: delete f1;
Execute Anonymous: delete f2;
Execute Anonymous: delete product;
Execute Anonymous: delete sam;

I tiried the same in anonymous window except the code of deleting records and there is no error. It means challenge is actually passed. But deleting test records causing error :
User-added image


Please help.
 
It is in Curl for makign Api calout for post method 

curl -H 'Accept: application/xml' -H 'Content-Type:application/xml' \
-u api_key:api_token -d '<message><data><result>
<id>123</id>
<address>cc</address>
<value>5</value>
</result></data></hl7message>'\
'https://example.com/customers/2342/messages

But How do make callout in Apex calss forthe above 
Specially for authentication  -u api_key:api_token
I have api key and token 
  • January 17, 2018
  • Like
  • 0
I am in the Create a Lightning App trial and I am not seeing the Warehouses, Deliveries, Merchandise components to add to utility bar.  The Warehouse was a classic app package installed in the previous module. When I go into the Warehouse App, I an see all the tabs for Warehouses, Deliveries, Merchandise components and they all have data. Why am I not able to add them to the utility bar? Any help?
 
Hi all,

I am working through the Visualforce Mobile trailhead, and in the "Use the Salesforce Lightning Design System to Style Visualforce Pages" module, the first step of the exercise defines this class;
 
<apex:page showHeader="false" standardStylesheets="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0">

  <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en">
    <head>
      <meta charset="utf-8" />
        <meta http-equiv="x-ua-compatible" content="ie=edge" />
        <title>SLDS LatestAccounts Visualforce Page in Salesforce Mobile</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />

      <!-- Import the Design System style sheet -->
      <apex:slds />
    </head>     
    <body>

      <!-- REQUIRED SLDS WRAPPER -->
      <div class="slds-scope">

         <!-- PRIMARY CONTENT WRAPPER -->
         <div class="myapp">

         </div>
         <!-- / PRIMARY CONTENT WRAPPER -->

      </div>
      <!-- / REQUIRED SLDS WRAPPER -->

      <!-- JAVASCRIPT -->
      <!-- / JAVASCRIPT -->
    </body>
  </html>
</apex:page>
When the class is saved, an error is produced:
"The API version you've specified is lower than the minimum version of 39 for the apex:slds object"
This happens in both the developer console and mavensmate/sublime. 

Is there any way to fix this so I can continue the module?

Thanks
I started to build out a simple trigger from the  to prevent a File record from being deleted from SalesForce Files | Triggers. These file records can be deleted from a related list on a visualforce page. The trigger is active but I can still delete an uploaded File . Any ideas ? 
 
trigger CREContentDocVersion on ContentVersion (before delete) {
for(ContentVersion cv : trigger.old){
        cv.adderror('Document Cannot be deleted');
    }
}

 
Hi Experts,

I have written a test class , test method does not passed and i got cobut i am getting  below error. how to i will fix , kindly suggest me.

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Body]: [Body].


public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;} 
public Blob fileBody{get;set;}

    public caseattachment(Apexpages.standardcontroller controller)
    {
        objcase = new case();
        myAttachment =new Attachment();
    }
    public pagereference save()
    {
        insert objcase;
        System.debug('@@@@@fileBody'+fileBody);     
        myAttachment  = new Attachment();
              Integer i=0;
              myAttachment .clear();
              myAttachment.Body = fileBody; 
              myAttachment.Name = 'Logo_'+objcase.id+'.jpeg' ; 
              myAttachment.ParentId = objcase.id;             
              insert myAttachment;                 
        pagereference pr = new pagereference('/'+objcase.id);                           
        return pr;
    }
}

Please see attached the my screen shot User-added image
@isTest
private class caseattachment1{

    static testMethod void testCaseExt() {
        // Create the Case Record.
        Case cas = new Case( Priority = 'Medium',Status= 'Working',Origin= 'Phone'); 
        insert cas;
        Attachment attach=new Attachment();     
        attach.Name='Unit Test Attachment';
        Blob fileBody=Blob.valueOf('Unit Test Attachment Body');
        attach.body=fileBody;
        attach.parentId=cas.id;
        insert attach;
        
        
         ApexPages.StandardController sc = new ApexPages.StandardController(cas);
        caseattachment cec= new caseattachment(sc);
        
         
        cec.save();
       
    }
}

 
  • October 14, 2017
  • Like
  • 0
Hi I want to delete custom object records and also case records when account is deleted using trigger. Undelete the child records if account is undeleted the trigger works only for custome objects but case records are not deleted and undelted .Below is the trigger code.

trigger OrderDeletion on Account (before delete,after undelete) {
    
    List<Id> AccIds= new List<Id>();
   
    if(trigger.isbefore && trigger.isdelete){  
        for(Account acc: trigger.old){
            AccIds.add(acc.id);
        }
        List<AccountOrder__c> ordlist=[select id,name,AccountOrder__c from AccountOrder__c WHERE AccountOrder__c in:AccIds];
        if(ordlist.size()>0){
            delete ordlist;
        }
        
        List<Case> caselist = [select id from Case where Account.Id in:AccIds];
        if(caselist.size()>0){
            delete caselist;
        }
    }
    
    if(trigger.isAfter && trigger.isUndelete){
        for(Account acc: trigger.new){
            AccIds.add(acc.id);
        }
        
        List<AccountOrder__c> ordlist2=[select id,name,AccountOrder__c from AccountOrder__c WHERE AccountOrder__c in:AccIds AND isDeleted = true ALL ROWS];
        if(ordlist2.size()>0){
            undelete ordlist2;
        }
        
         List<Case> caselist1 = [select id from Case where Account.Id in:AccIds AND isDeleted = true ALL ROWS];
        if(caselist1.size()>0){
            delete caselist1;
        }
    }
}

I am trying to create a validation rule on case that checks that the related account has a true value in the 'isprimarymember' field (its a check box) and that accound has a certain record type. I also want to make sure that type is set to a specific value as well. However, this is not working. Its allowing me to save with accounts that are not primary and have a different record type.

Any help would be appreciated.

AND( 
Account.IsPrimaryMember__c = TRUE, 
$RecordType.Name = "Individual", 
ISPICKVAL(Type, "Member Reassignment") 
)
**Still Learning**
I am trying to create the Apex Controller that will then be used by the Visualforce page for layouts.  I only want to show the Current Fiscal Period based on Todays date on the Visualforce page.  

Period_FY__c is just a formula field that is a String:  Below is the code for the formula field.
CASE( 
Text(Month(TODAY() )) , 
"1","2", 
"2","3", 
"3","3", 
"4","3", 
"5","4", 
"6","4", 
"7","4", 
"8","1", 
"9","1", 
"10","1", 
"11","2", 
"12","2", 
"" 
)

The code where I am having an error.  If there is a different way this would be written better I am open. (learning)

public with sharing class QuotaRelatedListqtr {

public List <Quota__c> quotas {get;set;}
public List <Business_Plan__c> bp {get;set;}
public List <Period> period {get;set;}
    
Integer FiscalYearStartMonth = 
[select FiscalYearStartMonth from Organization where id=:Userinfo.getOrganizationId()].FiscalYearStartMonth;

String TodaysDate = date.today().format();
     
Public List <Period> Periods = [Select p.Number From Period p 
         Where (p.StartDate <= TODAY AND p.EndDate >= TODAY) and p.type = 'Quarter' Limit 1];


       // Get information about the Quota being worked on
       // Needs to be based on Business Plan per Person 
       // Need to get the correct FY and Correct Quarter based on todays date.    
       // 
public QuotaRelatedListqtr(ApexPages.StandardController controller) {
 quotas = [SELECT Actual_Sales__c, Actual_vs_Quota__c, Annual_Actual_Sales__c, Annual_Quota__c, 
                           Annual_Targeted_New_Business_Sales__c, Business_Plan__c, Fiscal_Period2__c,
                               Quota__c, Sales_Categories__c, Sales_Category_Name__c,  Sales_Needed_to_Hit_Quota__c,Sales_Product_Category__c,
                               Sales_Won__c, Targeted_New_Business__c,Target_vs_Quota__c,Targeted_New_Business_Sales__c
                               FROM Quota__c
                              WHERE Period_FY__c IN :Periods];    
                             
    }
              
}


Here is the Error Message:  Invalid bind expression type of Period for column of type String
I have bolded the line where it is saying the error is.

 
I have used dataloader app and dataloader.io to map everything out and can see all the information that different posts say that i should have mapped out on my org and still i still get this error
Challenge Not yet complete... here's what's wrong: 
Please check that all of the relationships are maintained for Opportunity Contacts and Adventure Packages that you upload from the spreadsheet.
ive even manually mapped the contact roles and adventure package with the data loader app and still Got the same error
even though through that way I still got the same error
I have no idea what i am doing wrong
I would like to pass the variable 'company' to the second repeat function so i can use the variable in the second query of the controller. Is that possible?

<apex:repeat value="{!company }" var="co" >
   <apex:variable value="{!co.Name__c}" var="comp" />
      <apex:repeat value="{!customer}" var="cu"  >
      

Class:
comp = ApexPages.currentPage().getParameters().get('comp'); 
company = [Select Name  FROM Company];
customer = [Select Name FROM Customer where Company =:comp];
Hi all,

Looking for help on an issue with my controller and visualforce page.

The issue I am having is that the picklist value for 'Interested Technologies' is returning weird results vs. just the name of the account.
User-added image

Here is my controller:
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}
  // the collection of accounts to display
  public Id selectedAccId{get;set;}

  public Boolean IsEmpty {get; set;} 

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String technology = Apexpages.currentPage().getParameters().get('technology');

    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+ '%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+ '%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+ '%\'';  
    if (!technology.equals(''))
      soql += ' and interested_technologies__c includes (\''+technology+'\')';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> technologies {
    get {
      if (technologies == null) {

        technologies = new List<String>();
        Schema.DescribeFieldResult field = Contact.interested_technologies__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());

      }
      return technologies;          
    }
    set;
  }

  /*public List<String> options {
    get {
      if (options == null) {

        options = new List<String>();
        Schema.DescribeFieldResult field = Account.Name.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          options.add(f.getLabel());

      }
      return options;          
    }
    set;
  }*/
  
  //builds a picklist of account names based on their account id

  public List<selectOption> getaccts() {

      List<selectOption> options = new List<selectOption>(); 
  //new list for holding all of the picklist options
      options.add(new selectOption('', '- None -')); 
  //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
      for (Account account : [SELECT Id, Name FROM Account]) { 
  //query for Account records 
          options.add(new selectOption(account.Name, account.Name)); 
  //for all records found - add them to the picklist options
      }
      return options; //return the picklist options
  }

}
Here is my visualforce page:
<apex:page controller="ContactSearchController" sidebar="false">

  <apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Search Collaborative Wide Staff Directory" mode="edit">

  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">

      <apex:pageBlock title="Search Properties" mode="edit" id="criteria">

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementById("technology").options[document.getElementById("technology").selectedIndex].value
          );
      }
      </script> 

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="technology" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Interested Technologies<br/>
          <select id="technology" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!accts}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      <!--<apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions">
          <apex:selectList value="{!options}" multiselect="false" size="1">
                  <apex:selectOptions value="{!accts}"/>
          </apex:selectList>
      </apex:pageBlockSection>-->

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.firstName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.lastName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.name}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Technologies" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="interested_technologies__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.interested_technologies__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

    </td>
  </tr>
  </table>

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>    

  </apex:pageBlock>

  </apex:form>

</apex:page>
What am I missing?   Any help is much appreciated.

 
{"Message":"Number of Post office(s) found: 21","Status":"Success","PostOffice":[{"Name":"Baroda House","Description":"","BranchType":"Sub Post Office","DeliveryStatus":"Non-Delivery","Taluk":"New Delhi","Circle":"New Delhi","District":"Central Delhi","Division":"New Delhi Central","Region":"Delhi","State":"Delhi","Country":"India"}]}

The above is my json string.
I have written the following code deserialize it

global class wrapper{
global class parserr
    {
       global string Message{get;set;}
       global string Status{get;set;} 
       global list<postoffice>po{get;set;}
    }
    global class postoffice
    {
        global string name{get;set;}
        global string Description{get;set;}
        global string BranchType{get;set;}
        global string DeliveryStatus{get;set;}
        global string Taluk{get;set;}
        global string Circle{get;set;}
        global string District{get;set;}
        global string Division{get;set;}
        global string Region{get;set;}
        global string state{get;set;}
        global string country{get;set;}
    }
}

 p= (wrapper.paresrr)JSON.deserialize(JSONresponse, wrapper.parserr.class);
I'm getting the values of Message and status correctly. But list<postoffice> po is getting as null although values are coming into response.And also I want the values in postoffice class also.
Thanks
Hello Devs,

I want to access data from below child parent dependencies:

Object tnw_invoice__InvoiceItem__c connected with Object OrderItem and OrderItems connected with Orders

I'm trying to add WHERE condition like Order.Status != 'Closed Lost' in below query:

SELECT Id, tnw_invoice__Order_Item__c FROM tnw_invoice__InvoiceItem__c WHERE tnw_invoice__Product_Code__c = 'xxxxxxxxx8989'

But it's give me error of "Didn't understand relationship......." on developer console query editor.

Thanks for help :)

Kapil
Hello All,
I am making a call from my c# rest service to try and get Salesforce latest version number, but SF is not retuning a parsable Json stirng.
HttpClient apiCallClient = new HttpClient();
            //String restCallURL = ServiceURL + "/services/data/v40.0/sobjects";                
            String restCallURL = ServiceURL + "/services/data/";
            
            HttpRequestMessage apirequest = new HttpRequestMessage(HttpMethod.Get, restCallURL);
            apirequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            apirequest.Headers.Add("authorization", "Bearer " + authToken);
            HttpResponseMessage apiCallResponse = await apiCallClient.SendAsync(apirequest);

            String requestresponse = await apiCallResponse.Content.ReadAsStringAsync();

           // String jsonResult = requestresponse.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

            List<String> sObjLst = new List<String>();
            return requestresponse.ToString();
            
            if (apiCallResponse.IsSuccessStatusCode)
            {

                JObject sObjJObj = JObject.Parse(requestresponse);
                return sObjJObj.ToString();

            }
In the above code requestresponse equals, below but newtonsoft_Json is not able to parse it, and if I try and parse it with online parsers they also return errors.

[{\"label\":\"Winter '11\",\"url\":\"/services/data/v20.0\",\"version\":\"20.0\"},{\"label\":\"Spring '11\",\"url\":\"/services/data/v21.0\",\"version\":\"21.0\"},{\"label\":\"Summer '11\",\"url\":\"/services/data/v22.0\",\"version\":\"22.0\"},{\"label\":\"Winter '12\",\"url\":\"/services/data/v23.0\",\"version\":\"23.0\"},{\"label\":\"Spring '12\",\"url\":\"/services/data/v24.0\",\"version\":\"24.0\"},{\"label\":\"Summer '12\",\"url\":\"/services/data/v25.0\",\"version\":\"25.0\"},{\"label\":\"Winter '13\",\"url\":\"/services/data/v26.0\",\"version\":\"26.0\"},{\"label\":\"Spring '13\",\"url\":\"/services/data/v27.0\",\"version\":\"27.0\"},{\"label\":\"Summer '13\",\"url\":\"/services/data/v28.0\",\"version\":\"28.0\"},{\"label\":\"Winter '14\",\"url\":\"/services/data/v29.0\",\"version\":\"29.0\"},{\"label\":\"Spring '14\",\"url\":\"/services/data/v30.0\",\"version\":\"30.0\"},{\"label\":\"Summer '14\",\"url\":\"/services/data/v31.0\",\"version\":\"31.0\"},{\"label\":\"Winter '15\",\"url\":\"/services/data/v32.0\",\"version\":\"32.0\"},{\"label\":\"Spring '15\",\"url\":\"/services/data/v33.0\",\"version\":\"33.0\"},{\"label\":\"Summer '15\",\"url\":\"/services/data/v34.0\",\"version\":\"34.0\"},{\"label\":\"Winter '16\",\"url\":\"/services/data/v35.0\",\"version\":\"35.0\"},{\"label\":\"Spring '16\",\"url\":\"/services/data/v36.0\",\"version\":\"36.0\"},{\"label\":\"Summer '16\",\"url\":\"/services/data/v37.0\",\"version\":\"37.0\"},{\"label\":\"Winter '17\",\"url\":\"/services/data/v38.0\",\"version\":\"38.0\"},{\"label\":\"Spring '17\",\"url\":\"/services/data/v39.0\",\"version\":\"39.0\"},{\"label\":\"Summer '17\",\"url\":\"/services/data/v40.0\",\"version\":\"40.0\"},{\"label\":\"Winter '18\",\"url\":\"/services/data/v41.0\",\"version\":\"41.0\"}]

Thanks for any help or advice.
Keith.
On an Opportunity, I have created a button to execute Javascript using sforce.apex.execute (I am calling an Apex Class).
The apex class creates a Contract record. I would like to get the record id (of the Contract just created) displayed on an alert after clicking on the button if creation is successful.
_______

{!RequireScript("/soap/ajax/34.0/connection.js")}
{!RequireScript("/soap/ajax/34.0/apex.js")}

function success() {
    // Indicate success
    var alertString="Success!"; 
    window.open('www.google.com');

    alert(alertString); 
}
function error() {
    // Indicate failure
    //window.open('www.yahoo.com');
    var alertString="Fail!"; 
    alert(alertString); 
}
sforce.connection.sessionId = "{!$Api.Session_ID}";
sforce.apex.execute("InsertContractAndPO", "createContractAndPOAsset",
{ accountId: "{!Opportunity.AccountId}", opportunityId: "{!Opportunity.Id}" }, 
{ onSuccess:success , onFailure: error});



 
My code does not have any problems.But  data is not being displayed in the preview window except the lables.Challenge has been passed.



<apex:page standardController="Opportunity">
   <apex:pageBlock title="Opportunity  Details">
    <apex:pageBlockSection>
        <apex:outputField value="{!Opportunity .Name }"/>
        <apex:outputField value="{! Opportunity.Amount }"/>
        <apex:outputField value="{! Opportunity.CloseDate }"/>
        <apex:outputField value="{! Opportunity.Account.Name }"/>
    </apex:pageBlockSection>
       </apex:pageBlock>
  
</apex:page> 
User-added image
I am new to visualforce and am having trouble getting sorting working on my page. My page has two pageblocktables on it that pull data from two different object dynamically based on fields that users input into a custom setting. I would like both tables to be sortable independently. The solution I have is working for one table, but not the other. As far as I can tell the code for both tables is identical. Not sure why there is a difference in behavior.

The table that works is pulling data from an object called Timesheet__c. It is the second table on the page. The table that doesn't is the first and is pulling from an object called Expense_Line__c.

Any help would be much appreciated!

Here is my page:
 
<apex:page controller="invoicePickerClass" lightningStylesheets="TRUE">
  <apex:form>

    <!-- Output panel to make the buttons live side-by-side -->
    <apex:outputPanel id="thePanel" layout="block">

      <!-- Button to get Save changes and stay on form -->
      <apex:commandButton action="{!getSelected}" value="Save" id="Save"/>

      <!-- Button to Save changes and return to Invoice -->
      <apex:commandButton action="{!getSelectedandLeave}" value="Save and Done" id="SaveAndDone"/>
    </apex:outputPanel>
    
    <!--Panel grid that holds the two tables  -->
    <!-- <apex:panelGrid columns="1" width="100%" columnClasses="pgCol"> -->
    
      <!-- Expense Line Table -->
      <apex:pageBlock title="Expense Line List" id="expenseLines">
        <apex:pageBlockSection columns="1">
            
            <!-- ExpenseLine List -->
          <apex:pageBlockTable value="{! ExpenseLines }" var="el" rendered="{!(expenseLines.size != 0)}" cellpadding="5">
            
            <!-- Checkbox Column -->
            <apex:column >
              <apex:facet name="header">
                <apex:inputCheckbox styleClass="checkEL" value="{!el.isSelectedEL}" onclick="checkAll(this,'checkEL')"/>
              </apex:facet>
                <apex:inputCheckbox styleClass="checkEL" value="{!el.isSelectedEL}" id="checkedone">
                </apex:inputCheckbox>
            </apex:column>

            <!-- Dynamic Table Columns -->
            <apex:repeat value="{!ELCol}" var="elCol">
            <apex:column> 
              <apex:facet name="header">
                <apex:commandLink action="{!elSortDir}" immediate="true" reRender="expenseLines" value="{!$ObjectType.Expense_Line__c.Fields[elCol].Label }">
                  <apex:param name="sortParam" assignTo="{!elSort}" value="{!elCol}"/>
                  <apex:outputPanel>
                    <apex:image value="{!IF(elSort = elCol,$Resource[elSortIMG], $Resource.Sortable)}"/>
                  </apex:outputPanel>
                </apex:commandLink>
              </apex:facet>
              <apex:outputField value="{! el.exp[elCol] }"/> 
            </apex:column>
            </apex:repeat>

            <!-- Make table inline editable -->
            <apex:inlineEditSupport event="ondblClick"/>
          </apex:pageBlockTable>

          <!-- Text to display if no data in the table -->
          <apex:outputText rendered="{!(expenseLines.size = 0)}" value="There are no Expenses to display." />
        </apex:pageBlockSection>            
      </apex:pageBlock>


      <!-- Timesheets Table -->
      <apex:pageBlock title="TimeSheet List" id="timeSheets">
        <apex:pageBlockSection columns="1">
            
          <!-- TimeSheet List -->
          <apex:pageBlockTable value="{! TimeSheets }" var="ts" rendered="{!(TimeSheets.size != 0)}" cellpadding="5">
                
            <!-- Checkbox Column -->
            <apex:column>
              <apex:facet name="header">
                <apex:inputCheckbox styleClass="checkTS" value="{!ts.isSelectedTS}" onclick="checkAll(this,'checkTS')"/>
              </apex:facet>
                <apex:inputCheckbox styleClass="checkTS" value="{!ts.isSelectedTS}" id="checkedone">
                </apex:inputCheckbox>
            </apex:column>

            <!-- Dynamic table column -->
            <apex:repeat value="{!TSCol}" var="tsCol">
            <apex:column>
              <apex:facet name="header">
                <apex:commandLink action="{!tsSortDir}" immediate="true" reRender="timeSheets" value="{!$ObjectType.Timesheet__c.Fields[tsCol].Label }">
                  <apex:param name="sortParam" assignTo="{!tsSort}" value="{!tsCol}"/>
                  <apex:outputPanel>
                    <apex:image value="{!IF(tsSort = tsCol,$Resource[tsSortIMG], $Resource.Sortable)}"/>
                  </apex:outputPanel>
                </apex:commandLink>
              </apex:facet>
              <apex:outputField value="{! ts.tsh[tsCol] }"/> 
            </apex:column>
            </apex:repeat>

            <!-- Make table inline editable -->
            <apex:inlineEditSupport event="ondblClick"/>
          </apex:pageBlockTable>

          <!-- Text to display if no data for table -->
          <apex:outputText rendered="{!(TimeSheets.size = 0)}" value="There are no TimeSheets to display."/>
        </apex:pageBlockSection>
      </apex:pageBlock>
   
      
    <!-- </apex:panelGrid> -->
  </apex:form>

  <!-- Script that runs when check all is selected -->
  <script>
    function checkAll(cb, check)
    {
        var inputElem = document.getElementsByClassName(check);
        for(var i=0; i<inputElem.length; i++)
        {
            if(inputElem[i].id.indexOf("checkedone")!=-1)
            inputElem[i].checked = cb.checked;
        }
    }
  </script>
  
  <!-- Style needed if the tables are moved side-by-side -->
  <style type="text/css">
    .pgCol{
      width:50%;
    }
  </style>
</apex:page>

Here is my apex code:
 
public with sharing class invoicePickerClass {

	//URL and other Parameters 
	public String invId {get; set;}
	public String projId {get; set;}
	public static String recId {get; set;}

	//Sort Variables
	public String tsSort {get; set;}
	public String tsSortLast {get; set;}
	transient String tsSortDir {get; set;}
	public String tsSortDirLast {get; set;}
	
	public String elSort {get; set;}
	public String elSortLast {get; set;}
	transient String elSortDir {get; set;}
	public String elSortDirLast {get; set;}

	//Sort images
    public String tsSortIMG {get;set;}
    public String elSortIMG {get;set;}
	
	//Lists for synamic columns
	List<String> tsCol = new List<string>();
	List<String> elCol = new List<string>();

    //Wrapper class data
    public List<tsWrapper> tsList {get; set;}
    List<Timesheet__c> selectedTimeSheets = new List<Timesheet__c>();
    List<Timesheet__c> unSelectedTimeSheets = new List<Timesheet__c>();
    public List<elWrapper> elList {get; set;}
    List<Expense_Line__c> selectedExpenseLines = new List<Expense_Line__c>();
    List<Expense_Line__c> unSelectedExpenseLines = new List<Expense_Line__c>();

    //method to populate time sheet table using wrapper class
    public  List<tsWrapper> getTimeSheets() {

    		invId = Apexpages.currentPage().getparameters().get('invId');

    		projId = Apexpages.currentPage().getparameters().get('projId');

    		system.debug(tsSort+tsSortLast+tsSortDir+tsSortDirLast+tsSortIMG);

    		if(tsSort == NULL){tsSort = 'Date__c'; tsSortDir = 'DESC';}

    		system.debug(tsSort+tsSortLast+tsSortDir+tsSortDirLast+tsSortIMG);

    		tsSortDir();
    		tsSortLast = tsSort;

    		system.debug(tsSort+tsSortLast+tsSortDir+tsSortDirLast+tsSortIMG);

    		List<string> columns = getColumns('Timesheet__c');

    		String qry = 'select Id, Invoice__c, Project__c, '+String.join(columns, ',')+' FROM Timesheet__c WHERE Project__c = :projId AND (Invoice__c = \'\' OR Invoice__c = :invId) ORDER BY '+tsSort+' '+tsSortDir;
            
           // if(tsList == NULL){
            	tsList = new List<tsWrapper>();
            	for(Timesheet__c tsh : Database.query(qry)){
            		tsList.add(new tsWrapper(tsh));
            			
            	}
           // }

            return tsList;
    }

    
    //method to populate expense line table using wrapper class
    public  List<elWrapper> getExpenseLines() {

    		invId = Apexpages.currentPage().getparameters().get('invId');

    		projId = Apexpages.currentPage().getparameters().get('projId');

    		system.debug(elSort+elSortLast+elSortDir+elSortDirLast+elSortIMG);

    		if(elSort == NULL){elSort = 'Date__c'; elSortDir = 'DESC';}

    		system.debug(elSort+elSortLast+elSortDir+elSortDirLast+elSortIMG);

    		elSortDir();
    		elSortLast = elSort;

    		system.debug(elSort+elSortLast+elSortDir+elSortDirLast+elSortIMG);

    		List<string> columns = getColumns('Expense_Line__c');

    		String qry = 'select Id, Invoice__c, Project__c, '+String.join(columns, ',')+' FROM Expense_Line__c WHERE Project__c = :projId AND (Invoice__c = \'\' OR Invoice__c = :invId) ORDER BY '+elSort+' DESC';

            //if(elList == NULL){
            elList = new List<elWrapper>();
            	for(Expense_Line__c exp : Database.query(qry)){
            		elList.add(new elWrapper(exp));	
            	}
            //}

            return elList;
    }

    public List<String> getColumns(string obj){
    	List<InvoicePicker__c> ipCol = new List<InvoicePicker__c>();
    	List<String> columns = new List<String>();
    	if(obj=='Timesheet__c'){
    		ipCol = [select Field__c FROM InvoicePicker__c WHERE Object__c = :obj ORDER BY Column_Order__c ASC];
    	}
    	else if(obj=='Expense_Line__c'){
    		ipCol = [select Field__c FROM InvoicePicker__c WHERE Object__c = :obj ORDER BY Column_Order__c ASC];
    	}
    	for(InvoicePicker__c ip : ipCol){
    		columns.add(ip.Field__c);
    	}
    	return columns;
    }

    //method for dynamic columns for Timesheets
    public List<String> getTSCol(){
    	tsCol.clear();
    	tsCol.addAll(getColumns('Timesheet__c'));
    	return tsCol;

    }

    //method for dynamic columns for Expense Lines
    public List<String> getELCol(){
    	elCol.clear();
    	elCol.addAll(getColumns('Expense_Line__c'));
    	return elCol;

    }


    //Sort data table action
    public void tsSortDir() {
		
		if(tsSortLast == tsSort && tsSortDirLast == 'DESC'){tsSortDir = 'ASC';}
		else if(tsSortLast == tsSort && tsSortDirLast == 'ASC'){tsSortDir = 'DESC';}
		else{tsSortDir = 'DESC';}

		tsSortDirLast = tsSortDir;
		tsSortIMG = tsSortDir;
    }

    public void elSortDir() {
		
		if(elSortLast == elSort && elSortDirLast == 'DESC'){elSortDir = 'ASC';}
		else if(elSortLast == elSort && elSortDirLast == 'ASC'){elSortDir = 'DESC';}
		else{elSortDir = 'DESC';}

		elSortDirLast = elSortDir;
		elSortIMG = elSortDir;
    }

	//timesheet wrapper class
    public class tsWrapper{
        public Timesheet__c tsh {get; set;}
        public Boolean isSelectedTS {get; set;}
        public tsWrapper(Timesheet__c ts){
            tsh = ts;
            if(tsh.Invoice__c != NULL){
            	isSelectedTS = true;
            }
            else{isSelectedTS = false;}
        }
    }

    //Expense Line Wrapper
    public class elWrapper{
        public Expense_Line__c exp{get; set;}
        public Boolean isSelectedEL {get; set;}
        public elWrapper(Expense_Line__c el){
            exp = el;
            if(exp.Invoice__c != NULL){
            	isSelectedEL = true;
            }
            else{isSelectedEL = false;}
        }
    }


    //Original Processing of selected items
    public PageReference getSelectedEL(){
        selectedExpenseLines.clear();
        unSelectedExpenseLines.clear();
        for(elWrapper elWrapper : this.elList){
	        if(elWrapper.isSelectedEL == true) {
		        selectedExpenseLines.add(elWrapper.exp);
	    	}
	    	if(elWrapper.isSelectedEL == false){
	    		unSelectedExpenseLines.add(elWrapper.exp);
	    	}
	    }
       	return null;
    }

	public PageReference getSelectedTS(){
        selectedTimeSheets.clear();
        unSelectedTimeSheets.clear();

        for(tsWrapper tsWrapper : this.tsList){
	        if(tsWrapper.isSelectedTS == true) {
		        selectedTimeSheets.add(tsWrapper.tsh);
	    	}
	    	if(tsWrapper.isSelectedTS == false){
	    		unSelectedTimeSheets.add(tsWrapper.tsh);
	    	}
	    }
       	return null;
    }

     //wrapper class for Comparable Interface
    
    //public class sortN implements Comparable {
    //    public String sortValue {get;set;}    
        
    //    public sortN(String sortName) {
    //        sortValue = sortName;
    //    }
        
    //    public Integer compareTo(Object ObjToCompare) {
    //        return sortValue.CompareTo(((sortN)ObjToCompare).sortValue);
    //    }
    //}
     
    


    //Button method

    public PageReference getSelected(){
    	//get all selected and unselected records
		getSelectedEL();
    	getSelectedTS();
    	
    	//process and update all selected and unselected records
    	processTimeSheets();
    	processExpenseLines();
    	

    	
    	return NULL;
    }

     public PageReference getSelectedandLeave(){
    	//get all selected and unselected records
    	getSelectedEL();
    	getSelectedTS();
    	
    	//process and update all selected and unselected records
    	processTimeSheets();
    	processExpenseLines();
    	
    	//navigate back to invoice record
    	PageReference pr = new PageReference('/'+invId);
        system.debug(pr);
        pr.setRedirect(true);
    	
    	return pr;
    }

    public void processTimeSheets(){

    	List<Timesheet__c> processedTimeSheets = new List<Timesheet__c>();

    	for(Timesheet__c t : selectedTimeSheets){
    		Timesheet__c newTimeSheet = new Timesheet__c(id=t.Id);
    		newTimeSheet.Invoice__c = invId;
    		Map<String, SObjectField> m = Timesheet__c.SObjectType.getDescribe().fields.getMap();
    		for(String f : tsCol){
    			DescribeFieldResult r = m.get(f).getDescribe();
		      	if(r.isUpdateable()){
    				newTimeSheet.put(f, t.get(f));
		      	}	
    		}
    		processedTimeSheets.add(newTimeSheet);
    	}

    	for(Timesheet__c t : unSelectedTimeSheets){
    		Timesheet__c newTimeSheet = new Timesheet__c(id=t.Id);
    		newTimeSheet.Invoice__c = null;
    		Map<String, SObjectField> m = Timesheet__c.SObjectType.getDescribe().fields.getMap();
    		for(String f : tsCol){
    			DescribeFieldResult r = m.get(f).getDescribe();
		      	if(r.isUpdateable()){
    				newTimeSheet.put(f, t.get(f));
		      	}	
    		}
    		processedTimeSheets.add(newTimeSheet);
    	}

    	update processedTimeSheets;
    }

    public void processExpenseLines(){

    	List<Expense_Line__c> processedExpenseLines = new List<Expense_Line__c>();

    	for(Expense_Line__c e : selectedExpenseLines){
    		Expense_Line__c newExpenseLines = new Expense_Line__c(id=e.Id);
    		newExpenseLines.Invoice__c = invId;
    		Map<String, SObjectField> m = Expense_Line__c.SObjectType.getDescribe().fields.getMap();
    		for(String f : elCol){
    			DescribeFieldResult r = m.get(f).getDescribe();
		      	if(r.isUpdateable()){
    				newExpenseLines.put(f, e.get(f));
		      	}
    			
    		}

    		processedExpenseLines.add(newExpenseLines);
    	}

    	for(Expense_Line__c e : unSelectedExpenseLines){
    		Expense_Line__c newExpenseLines = new Expense_Line__c(id=e.Id);
    		newExpenseLines.Invoice__c = null;
    		Map<String, SObjectField> m = Expense_Line__c.SObjectType.getDescribe().fields.getMap();
    		for(String f : elCol){
    			DescribeFieldResult r = m.get(f).getDescribe();
		      	if(r.isUpdateable()){
    				newExpenseLines.put(f, e.get(f));
    			}
    		}

    		processedExpenseLines.add(newExpenseLines);
    	}
    	update processedExpenseLines;
    }

}

 

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.