• Dritter
  • NEWBIE
  • 60 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 9
    Replies
I'm trying to query all lightning-input-fields and log one of the field values, but it keeps coming back as undefined. Anyone see what I'm doing wrong?
import { LightningElement, api, track} from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import saveCase from '@salesforce/apex/KapCloseCaseLightningController.saveCase';
import CASE_OBJECT from '@salesforce/schema/Case';
import CASE_NUMBER from '@salesforce/schema/Case.CaseNumber';
import CASE_STATUS from '@salesforce/schema/Case.Status';
import CASE_TYPE from '@salesforce/schema/Case.Type';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CloseCasePage extends LightningElement {

objectApiName = CASE_OBJECT;
@api recordId;
@track case;
@track error;
@track type;

saveAction(event) {
        const inputFields = this.template.querySelectorAll('lightning-input-field');
        if (inputFields) {
            inputFields.forEach(field => {
                if(field.name === "type") {
                    //this.type = event.target.value;
                    console.log('type == ' + event.target.value)
                }
            });
        }
}


 
<template>
    <lightning-record-edit-form
        object-api-name="Case"
        record-id={recordId}>
    <lightning-messages if:true={error}>errors={error}</lightning-messages>
    <div class="slds-grid slds-theme_default slds-p-around_small">
        <div class="slds-col slds-size_1-of-1">
            <div class="slds-box slds-box_xx-small slds-theme_shade">
                <p>Case Details</p>
            </div>
        </div>
    </div>
    <div class="slds-grid slds-theme_default slds-p-around_large">
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field name='type' field-name="Type" required="true" onchange={handleChange}></lightning-input-field>
        </div>
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name="CaseNumber"></lightning-input-field>
            <lightning-input-field name='productLine' field-name='Product_Line__c' required="true" onchange={handleChange}></lightning-input-field>
            <lightning-input-field name='status' field-name="Status" required="true" onchange={handleChange}></lightning-input-field>
        </div>
    </div>
<div class="slds-grid slds-theme_default slds-p-bottom_medium slds-p-right_medium slds-float_right">
        <div class="slds-col slds-size_1-of-1 slds-m-right_none">
            <div class="slds-m-top_medium slds-m-right_none">  
                <lightning-button 
                    variant="brand" 
                    label="Cancel" 
                    title="Primary action" 
                    onclick={closeAction} 
                    class="slds-m-left_x-small">
                </lightning-button>
                <lightning-button 
                    variant="brand" 
                    label="Submit" 
                    title="Primary action" 
                    onclick={saveAction} 
                    class="slds-m-left_x-small">
                </lightning-button>
              </div>
        </div>
    </div>

 
I have a class and I'm trying to call it in the Dev Console, but I'm getting an error:

Line: 1, Column: 39
Unexpected token 'calExpirationDate'.

Any ideas? 
ktp_util_CaseExpirationDateCalculator calExpirationDate = new ktp_util_CaseExpirationDateCalculator(2,40,2018-01-01);
                    Date newExpirationDate = calExpirationDate.getNewExpirationDate();
                    system.debug('The newExpirationDate is ' + newExpirationDate);
public with sharing class ktp_util_CaseExpirationDateCalculator {
    
    private Integer quantity { get; set; }
    private Integer duration { get; set; }
    private Integer totalDuration { get; set; }
    private Date currentExpirationDate { get; set; }
    private Date newExpirationDate { get; set; }  

    //Class constructor
    public ktp_util_CaseExpirationDateCalculator(Integer quantity, Integer duration, date currentExpirationDate){ 
    
        this.quantity = quantity;
        this.duration = duration;
        this.totalDuration = calculateLengthOfExtension();
        this.currentExpirationDate = currentExpirationDate;
        this.newExpirationDate = calculateNewExpirationDate ();

    }
    
    //Calculate length of extension by multiplying quantity by duration
    private Integer calculateLengthOfExtension() {
        
        Integer validQuantity = validateQuantity();
        Integer lengthOfExtension;
        
        lengthOfExtension = validQuantity * duration;
        
        return lengthOfExtension;
        
    }
    
    //Validate that quantity is greater than 0; otherwise return 1
    private Integer validateQuantity() {
        
        if(quantity == null) {
            return quantity = 1;
        } else {
        	return quantity;
       	}
    }
    
    //Calculate new expiration date by adding totalDuration to currentExpirationDate
    //expirationDateCheck checks to see if date is in the past and uses today if true; otherwise the enroll exp. date
    private Date calculateNewExpirationDate() {
        
        Date expirationDateCheck;
        expirationDateCheck = (currentExpirationDate < system.today()) ? system.today() : currentExpirationDate;
        Date calculatedNewExpirationDate;
        calculatedNewExpirationDate = expirationDateCheck + totalDuration;
       
        return calculatedNewExpirationDate;
    }
    
    //Get new expiration date
    public Date getNewExpirationDate() {
        
        return newExpirationDate;
        
    }
}

 
We use Salesforce and the Marketing Cloud. In SF, we're using the standard phone field which is formatting numbers as such (XXX) XXX-XXXX. To use SMS in the MC, I have to reformat the phone as follows 1-XXX-XXX-XXXX when the student is from the United States. I'm using the follow CASE function in SQL, but can't save the query without getting an error.

CASE WHEN a.Phone LIKE ('(%') THEN ('1'+'-'+ SUBSTRING(a.Phone,2,3) +'-'+ SUBSTRING(a.Phone,7,3)+'-'+ SUBSTRING(a.Phone,11,4)) as Phone
END

I'm trying to determine if the phone starts with a parenthesis and then format it correctly if it's true. Any ideas? a.Phone comes from a Data Extension that has the Salesforce phone in it.
I have the following method that finds an order along with it's order items (child object). 
 
public static ccrz__e_Order__c getOrderDetails (String orderId){
        
        ccrz__e_Order__c order = [SELECT id,
                                  name,
                                  ccrz__OriginatedCart__c,
                                  ccrz__Storefront__c,
                                  ccrz__OrderDate__c,
                                  Pay_In_Deposit__c,
                                  Do_not_send_confirmation_email__c,
                                  Activate_w_Balance_Due_c__c,
                                  SubTotalAmount2__c,
                                  ccrz__ShipAmount__c,
                                  ccrz__TotalAmount__c,
                                  ccrz__TotalSurcharge__c,
                                  Tuition_Fee__c,
                                  UpfrontCost__c,
                                  Amount_Charged__c,
                                  ccrz__Account__c,
                                  CreatedById,
                                  ccrz__BillTo__c,
                                  ccrz__ShipTo__c, (SELECT id,
                                                    ccrz__Product__c,
                                                    ccrz__Category__c,
                                                    Transaction_Code__c,
                                                    ccrz__StoreId__c,
                                                    ccrz__Subscription_Start_Date__c,
                                                    Flex_End_Date__c,
                                                    ccrz__ItemTotal__c,
                                                    ccrz__Price__c,
                                                    AmountPaid__c,
                                                    ccrz__SubAmount__c
                                                    FROM ccrz__e_orderitems__r)
                                  FROM ccrz__e_Order__c 
                                  WHERE id =: orderId
                                  LIMIT 1];
        return order;
    }
I'm trying to loop through the orderItems and call another method, but I'm getting the following error in the compiler. 

Error: A non-foreign key field cannot be referenced in a path expression: ccrz__E_OrderItems__r
} else if (order != NULL){
            for (ccrz__E_Orderitem__c orderItemProducts: order.ccrz__e_orderitems__r) {
                cc_kapmp_order_ProductDAO.getSpecForProductId (order.ccrz__e_orderitems__r.ccrz__Product__c, 'Free Trial Product Id');
            }
        }
Any thoughts on why is doesn't like ccrz__E_OrderItems__r?

 
I have an object called terms and conditions AND only one record can be active at a time by SBU. Therefore, create a trigger and services class. 

trigger
trigger TermsAndConditionTrigger on Terms_and_Conditions__c (before insert, after update) {
    
    if (trigger.isInsert) {
        
        for (Terms_and_Conditions__c newtermsAndCondRec : Trigger.new) {
            
            List <Terms_and_Conditions__c> ExistingTermsAndCond = EnrollmentAgreementServices.getActiveTermsAndConditionsBySBU(newtermsAndCondRec.SBU__c);
			EnrollmentAgreementServices.unCheckExistingActiveTermsAndCondBeforeInsert(ExistingTermsAndCond); 
        }
    }
}

Class methods
 
public static List<Terms_and_Conditions__c> getActiveTermsAndConditionsBySBU (String SBU) {
        
        List <Terms_and_Conditions__c> findIfActiveTermsAndCondExistList = [SELECT id, Active__c, SBU__c 
                                                                            FROM Terms_and_Conditions__c 
                                                                            WHERE SBU__c =: SBU 
                                                                            AND Active__c = TRUE];
        
        if(findIfActiveTermsAndCondExistList.isEmpty()) {
            return null;
    	} else {
            return findIfActiveTermsAndCondExistList;
    	}
    }
    
    public static void unCheckExistingActiveTermsAndCondBeforeInsert (List <Terms_and_Conditions__c> existTermsAndCond) {
        
        List<Terms_and_Conditions__c> oldActiveTermsAndCondToDeactivateList = new List<Terms_and_Conditions__c> ();
        
        for (Terms_and_Conditions__c tc :existTermsAndCond) {
            if (tc.Active__c == TRUE) {
                tc.Active__c = FALSE;
                oldActiveTermsAndCondToDeactivateList.add(tc);
            }
        } update oldActiveTermsAndCondToDeactivateList;
    }

My trigger throws an error if my first method getActiveTermsAndConditionsBySBU returns null. I could put a try catch around it to handle the error, but before I try that I have two questions: (1) should I be using List in the methods if the query is only going to return 1 record and (2) does anyone have any recommendations on how to make the code more efficient? 
I have been writing a little APEX, but I was told it would be a good idea to learn JAVA before I continue with APEX. I created a JAVA application and I have a MySQL server / database to connect to. I created an Order Class, OrderDAO Class, and a ConnectionPOOL class. The Order class is the pojo. I'm trying to write a getAllOrders () method in the OrderDAO class (and UPDATE and DELETE), but I can't seem to get it to work. Would anyone mind taking a look?
 
package com.douglas.myproject.pojo;

import java.sql.Date;
//import java.util.Date;

public class Order{
	
	private Integer id;
	private String name;
	private Date createdDate;
	
	
	public Order(){
		
	}
	//constructor
	public Order (Integer id, String name, Date createdDate) {
		id = this.id;
		name = this.name;
		createdDate = this.createdDate;
	}
	//Get Method for the id
	public Integer getOrderId(){
		return id;
	}
	//Set Method for the id
	public void setOrderId(Integer id){
		this.id = id;
	}	
	//Get Method for the Name
	public String getName() {
		return name;
	}
	//Set method for the Name
	public void setName(String name) {
		this.name = name;
	}
	//Get Method for the CreatedDate
	public Date getCreatedDate() {
		return createdDate;
	}
	//Get Method for the CreatedDate
	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}

}

ConnectionPool
package com.douglas.myproject.dao.driver;

import java.sql.Connection;
import java.sql.DriverManager;
//import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MyConnectionPool {

	private static String url = "jdbc:mysql://localhost:3306/Employee";
	private static String username = "root";
	private static String password = "kaplan";

	public static Connection getConn() throws SQLException {
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
	
	/***
	 public void getRecords() {
		ResultSet rs = null;
		try {
			Statement s = getConn().createStatement();
			rs = s.executeQuery("SELECT * FROM ORDER.order");

		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
	}
	**/
}



OrderDAO
package com.douglas.myproject.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.douglas.myproject.pojo.Order;
import com.mysql.jdbc.Statement;

public class OrderDAO {
	
	ResultSet myRs = null;
	Statement s = null;
	
	public List<Order> getAllOrders(){
		
		//Statement s = getConn().createStatement();
		
		List<Order> myRs = new ArrayList<Order>();
		//ResultSet myRs = s.executeQuery("SELECT * FROM ORDER.order");
		
		int i = 0;
		while (i < myRs.size()) {
			Order o = new Order();
			myRs.add(o);
			i++;
			//System.out.println(myRs.getString("id") + ", " + myRs.getString("name") + ", " + myRs.getString("createdDate"));
		}
		return myRs;
	}

	public Boolean save(Order o) {
		return null;
	}
	
	public Boolean update(Order o) {
		return null;
	}

	public void delete(Order o) {
	}

}
I have two fields on a visualforce page. The first allows a customer to check a box for installment billing. The second is a checkbox to accept the terms and condition of installment billing. I'm trying to write javascript that will alert the customer that they need to accept the installment billing terms and conditions if they checked the first box. This alert will happen when they hit the "Submit" button but failed to check the second box. 


I can't get it to work. Any ideas?
 
<!---Installment Billing Flag--->
                            <apex:inputField required="False" value="{!Case.Aoc_Installment_Billing__c}" label="Sign Up for Installment Billing" id="acceptInstallments_chk" >
                                <a href="#" class="tooltip">(See Terms and Conditions)<span>At Kaplan, you may select to pay for your enrollments in three installments. By selecting this option you agree: A $25 one-time, non-refundable Installment Billing Registration fee will be charged. Your first installment will be larger and will include 1/3 of tuition, the Registration fee, any applicable tax, Application fee if necessary and shipping and handling charges. Additionally you authorize that the remaining two installment payments (each 1/3 of the tuition) will be charged to the same credit card provided approximately 30 days and 60 days after the first payment. Please note that Installment Billing is not available for all products or services.</span></a>
                            </apex:inputField>
                            <!---Installment Billing Flag--->
                            <apex:inputField required="False" value="{!Case.Accept_IB_Terms__c}" label="Accept Installment Billing Terms and Conditions?" id="acceptInstallmentsTermsConditions_chk">
                                <a href="#" class="tooltip">(?)<span>At Kaplan, you may select to pay for your enrollments in three installments. By selecting this option you agree: A $25 one-time, non-refundable Installment Billing Registration fee will be charged. Your first installment will be larger and will include 1/3 of tuition, the Registration fee, any applicable tax, Application fee if necessary and shipping and handling charges. Additionally you authorize that the remaining two installment payments (each 1/3 of the tuition) will be charged to the same credit card provided approximately 30 days and 60 days after the first payment. Please note that Installment Billing is not available for all products or services.</span></a>
                            </apex:inputField>

Button 

​<apex:actionFunction name="validateInApex" action="{!ReadFile}"/>
                    <input type="button" onclick = "isIbBoxChecked();" value="Submit" id="theButton" style="width:100px;" />
                        </center>
                    </apex:outputPanel>
                </apex:pageBlock>

JavaScript

<script> 
            function isIbBoxChecked(){
                var myCheckBox = document.getElementById('{!acceptInstallments_chk.?})');
                alert('isIbBoxChecked: acceptInstallments_chk='+ myCheckBox);
                if (myCheckBox.checked){
                    alert('The Installment Billing Flag is checked'); 
                } else {
                    alert('Submitting');
                    ReadFile();
                }
            }
            //var myCheckBox = document.getElementById("acceptInstallments_chk");
            </script>

 
I'm trying to find accounts with a student school that has a school type of "med_us." However, when I add the WHERE statement to the inner select it times out. See below:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c WHERE school_type__c = 'med_us') AND Educational_Background__c = 'IMG'AND createddate = TODAY

If I remove the WHERE statement it runs fine, but it's not giving me what I'm looking for:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c ) AND Educational_Background__c = 'IMG'AND createddate = TODAY

When searching for records across child objects are we allowed to use WHERE statements in the inner select? 

I've also tried this:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c) AND Educational_Background__c = 'IMG'AND createddate = TODAY AND school_type__c.student_school__r ='med_us'
I'm trying to find accounts with a student schools that have a school type of "med_us." However, when I add the WHERE statement to the inner select it times out. See below:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c WHERE school_type__c = 'med_us') AND Educational_Background__c = 'IMG'AND createddate = TODAY

If I remove the WHERE statement it runs fine, but it's not giving me the info I need:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c ) AND Educational_Background__c = 'IMG'AND createddate = TODAY

When searching for records across child objects are we allowed to use WHERE statements? 

I've also tried this:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c) AND Educational_Background__c = 'IMG'AND createddate = TODAY AND school_type__c.student_school__r ='med_us'
I have a block with a VF page, and I want the red vertical bar to appear next to a field highlighting it is required. I've found a few suggestions online, but they don't seem to work. Any ideas? 
 
<apex:pageBlockSection title="Account Information" columns="2">
                
                <div class="reuqiredInput">
                    <div class="requiredBlock"></div>
                    <apex:inputText value="{!firstName}" label="First Name" required="true" />
                </div>
                
                <apex:inputField value="{!accountObject.PersonTitle}"/>
                <apex:inputText value="{!lastName}" label="Last Name *"/>
                <apex:inputField value="{!accountObject.Lead_Source__c}" label="Lead Source *"/>
                <apex:inputField value="{!accountObject.Hot_Flag__c}" label="Hot Lead"/>
                
            </apex:pageBlockSection>

 
  • September 28, 2015
  • Like
  • 0
We have a map which compares any updates on an account to what was previously there, and then returns true or false. During testing, I'm able to get to return true through the first If statement (line 31), but I can't see to get it to return anything for the Else If statement (line 37). Any ideas?
 
public without sharing class accountServices{
   Map <Id, Account> oldAccs;
   Map <Id, Account> newAccs;
   
	public accountServices (Map <Id, Account> newTriggerAccs, Map <Id, Account> oldTriggerAccs) {
           oldAccs = oldTriggerAccs;
           newAccs = newTriggerAccs;
       	   system.debug ('Old accounts' + ' ' + oldtriggerAccs);
           system.debug ('New accounts' + ' ' + newTriggerAccs);
   }
   
	public static boolean isChanged (account newacc, account oldacc) {
           Account oldAccs = oldacc;
           Boolean isChanged = (oldAcc.program_of_interest__c == null && newacc.program_of_interest__c != null) ||
               (oldAcc.program_of_interest__c != null && newacc.program_of_interest__c == null) ||
               !(oldAcc.program_of_interest__c.equals(newacc.program_of_interest__c));
			if (!ischanged) {
               isChanged = (oldacc.expected_test_date__c == null && newacc.expected_test_date__c != null) ||
                   (oldacc.expected_test_date__c != null && newacc.expected_test_date__c == null) ||
                   !(oldacc.expected_test_date__c == newacc.expected_test_date__c);
               system.debug ('Result 3' + ' ' + isChanged);
           }
           else if (!ischanged) {
               isChanged = (oldacc.expected_prep_start_date__c == null && newacc.expected_prep_start_date__c != null) ||
                   (oldacc.expected_prep_start_date__c != null && newacc.expected_prep_start_date__c == null) ||
                   !(oldacc.expected_prep_start_date__c == newacc.expected_prep_start_date__c);
               system.debug ('Result 4' + ' ' + isChanged);
           }
           
       return isChanged;
   }

........transformation code

 
I'm writing a test class for a trigger that is fired when our marketing cloud user updates an account. The test method passes, but the code coverage on the trigger remains 0%. Below is the code for the trigger and test class. In the test class, I'm using System.RunAs (line 46) to run it as the marketing cloud user. However, it doesn't appear to be activating the trigger. Any suggestions on how to correct it? 

TRIGGER
trigger Account on Account (after update){

    Id userId = userinfo.getUserId();
    Id RecordTypeId = [SELECT Id FROM RecordType WHERE Name = 'Person Account' LIMIT 1].Id;
    system.debug('PA RecordTypeId =' + ' ' + RecordTypeId);
    List<user> mcUser = [SELECT id from User WHERE username = 'mc.kapqa@kaplan.com.kapqa' ];
    system.debug('MC Users ='+ ' ' + mcUser);
      
    
    if (RecordTypeId == RecordTypeId && userId == mcUser[0].id){
        accountServices asp = new accountServices(trigger.newmap, trigger.oldmap);
        asp.process();
        system.debug ('The trigger fired');
    }
}
TEST CLASS
@isTest
public class AccountTest{

    static testMethod void validateAccount() {
    
    Test.startTest();
         
       Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@kaplan.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@kaplan.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
            System.debug ('Here is the user id ' + u.id);
        
        User u1 = [SELECT id from User WHERE username = 'mc.kapqa@kaplan.com.kapqa' LIMIT 1];
        system.debug('MC Users ='+ ' ' + u1);
        
        System.runas(u1) {
        
        //Create account
        Account a = new Account(
            Name = 'Test Account',
            OwnerId = u.Id,
            Program_Of_Interest__c = 'LSAT',
            Expected_test_date__c = tDate,
            Expected_Prep_Start_Date__c = tdate);
            insert a; 
            System.debug('Here is the account id ' + a.id);    
                
    Test.stopTest();  
     }
   } 
 }

 
Below is a scheduler that fires a batch class to deactivate portal users and licensed users that haven't logged in in the last 90 days. I want it to process the list of users in batches of 150 "database.executebatch ((ucu), 150);", but it seems to be doing it in batches of 1000. For example, my queue pulled back 1700 users that needed to be deactivated and in Salesforce it shows it was processed in 2 batches. Any ideas why it's not doing 150 per batch?

Scheduler:
global class KapUserCleanUpScheduler implements Schedulable{
    public static String CRON_EXP = '0 0 0 3 9 ? 2022';
        global void execute(SchedulableContext BC) {
            KapUserCleanUp ucu = new KapUserCleanUp ();
            database.executebatch ((ucu), 150);
        }
}

Batch Class: 
global class KapUserCleanUp implements Database.Batchable<sObject>{

    datetime myDateTime = datetime.now();
    //datetime newDateTime = myDateTime.addDays(-1);
    datetime inactiveDateTime = myDateTime.addDays(-90);

    //System.debug('current time: ' + myDateTime);
    //System.debug('newDateTime time: ' + newDateTime);
    //System.debug('inactiveDateTime time: ' + inactiveDateTime);

global Database.querylocator start(Database.BatchableContext BC){
            return Database.getQueryLocator([SELECT Email,Id,LastLoginDate FROM User WHERE (IsPortalEnabled = True AND IsActive = true AND CreatedDate = YESTERDAY) OR (IsPortalEnabled = false AND isActive = true AND lastLoginDate < :inactiveDateTime AND LastName != 'Site Guest User')]);}

global void execute(Database.BatchableContext BC, List<User> users){
   System.debug('Users retrieved ' + Users);
   
   for (User u : users) {
       u.isActive = false;
       System.debug(u.id + ' ' + u.email + ' will be deactivated' + u.lastLoginDate);
   }
       Database.SaveResult[] srList = Database.update(users, false);
          for (Database.SaveResult sr : srList){
             if (!sr.isSuccess()) {
             //Operation failed, so get all errors
                for(Database.Error err : sr.getErrors()){
                     System.debug('The following error has occurred.');
                     System.debug(err.getStatusCode() + ': ' + err.getMessage());
                } 
             }  
          }
    }
   global void finish(Database.BatchableContext BC){
       }
   }

 
I wrote the following batch apex but it keeps getting stuck in a queued status when I schedule it?
 
global class KapUserCleanUp implements Database.Batchable<sObject>{

    datetime myDateTime = datetime.now();
    datetime newDateTime = myDateTime.addDays(-1);
    datetime inactiveDateTime = myDateTime.addDays(-90);

    //System.debug('current time: ' + myDateTime);
    //System.debug('newDateTime time: ' + newDateTime);
    //System.debug('inactiveDateTime time: ' + inactiveDateTime);

global Database.querylocator start(Database.BatchableContext BC){
            return Database.getQueryLocator([SELECT Email,Id,LastLoginDate FROM User WHERE ((IsPortalEnabled = True AND IsActive = true AND CreatedDate = :newDateTime) OR (IsPortalEnabled = false AND isActive = true AND lastLoginDate < :inactiveDateTime AND LastName != 'Site Guest User'))]);}

global void execute(Database.BatchableContext BC, List<User> users){
   System.debug('Users retrieved ' + Users);
   
   for (User u : users) {
       u.isActive = false;
       System.debug(u.id + ' ' + u.email + ' will be deactivated' + u.lastLoginDate);
   }
       Database.SaveResult[] srList = Database.update(users, false);
          for (Database.SaveResult sr : srList){
             if (!sr.isSuccess()) {
             //Operation failed, so get all errors
                for(Database.Error err : sr.getErrors()){
                     System.debug('The following error has occurred.');
                     System.debug(err.getStatusCode() + ': ' + err.getMessage());
                } 
             }  
          }
    }
   global void finish(Database.BatchableContext BC){
       }
   }

 

My test class keeps getting this error when I push to production. I found the following article (https://help.salesforce.com/apex/HTViewSolution?id=000176562&language=en_US) and added the code to lines at the bottom. However, I keep getting a Compile Error: unexpected token: ')' at line 49 column 51. 

Is this the best way to resolve the original error? If so, any ideas on why I'm getting the Compile Error and how to overcome it? I've tried a few things but they all result in the same error. 

/************************************************************************************
** Module Name   : UserCleanUp 
**
** Description   : This class deactivates portal users setup by the website and
** irostering. It also deactivates Salesforce users that haven't logged in in the 
** last 90 days with the exception of Guest Site Users.
**
** Technial Info : <Batch Apex Class>
** 
** Author     : 
** Revision History:-
** Version  Date        Author 
** 1.0      1/6/15      
************************************************************************************/

global class KapUserCleanUp implements Database.Batchable<sObject>{

    datetime myDateTime = datetime.now();
    datetime newDateTime = myDateTime.addHours(-3);
    datetime inactiveDateTime = myDateTime.addDays(-90);

    //System.debug('current time: ' + myDateTime);
    //System.debug('newDateTime time: ' + newDateTime);
    //System.debug('inactiveDateTime time: ' + inactiveDateTime);

global Database.querylocator start(Database.BatchableContext BC){
            return Database.getQueryLocator([SELECT Email,Id,LastLoginDate FROM User WHERE (IsPortalEnabled = True AND IsActive = true AND (lastLoginDate < :newDateTime OR lastLoginDate = null)) OR (IsPortalEnabled = false AND isActive = true AND lastLoginDate < :inactiveDateTime AND LastName != 'Site Guest User')]);}

global void execute(Database.BatchableContext BC, List<User> users){
   System.debug('Users retrieved ' + Users);
   
   for (User u : users) {
       u.isActive = false;
       System.debug(u.id + ' ' + u.email + ' will be deactivated' + u.lastLoginDate);
   }
       Database.SaveResult[] srList = Database.update(users, false);
          for (Database.SaveResult sr : srList){
             if (!sr.isSuccess()) {
             //Operation failed, so get all errors
                for(Database.Error err : sr.getErrors()){
                     System.debug('The following error has occurred.');
                     System.debug(err.getStatusCode() + ': ' + err.getMessage());
                } 
             }  
          }
    }
   global void finish(Database.BatchableContext BC){
    if(!Test.isRunningTest)
         Database.executeBatch(new MySecondBatchJob));
       }
   }
I'm running batch apex to deactivate portal users every night, so we don't limit are limit on licenses. I'm getting this Exception on my test class when pushing the code to production. 

System.UnexpectedException: No more than one executeBatch can be called from within a testmethod

I found the following article which seems to have the solution, but I'm not sure where exactly to place the code block:

https://help.salesforce.com/apex/HTViewSolution?id=000176562&language=en_US

Here's the test class:

@isTest
private class KapUserCleanUpSchedulerTest {
public static testmethod void test() {
   
   Test.startTest();

   // Schedule the test job 
      String jobId = System.schedule('testMassScheduledApexonet', KapUserCleanUpScheduler.CRON_EXP, new KapUserCleanUpScheduler());
   // Get the information from the CronTrigger API object 
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];

   // Verify the expressions are the same 
      System.assertEquals(KapUserCleanUpScheduler.CRON_EXP, ct.CronExpression);
   // Verify the job has not run 
      System.assertEquals(0, ct.TimesTriggered);

   // Verify the next time the job will run 
      System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));

      public void finish(Database.BatchableContext);
         {
            if(!Test.isRunningTest)
               Database.executeBatch(new MySecondBatchJob));
         }
      
   Test.stopTest();
   
      }
   }

I'm new to coding, so any help is appreciated. Thanks!
I trying to write a scheduler to clean up our portal users accounts. I'm getting a Complie Error in line 6 (below are the first 8 lines), and I'm not sure why. Anyone have any suggestions? Thanks! 

public with sharing class KapUserCleanUpScheduler {

   public static Boolean runTestMethod = FALSE;
 
    public static void scheduleUserCleanUpJobs() {
        KapScheduledUserCleanUpBatch ucub = new KapScheduledUserCleanUpBatch();  - Line 6
        String cron_sched_01 = '00 00 1 * * ? *';
        String cron_sched_02 = '00 03 2 * * ? *';​​
We have an umlimited edition and I'm trying to create a new record called a "support ticket" off of a user's record (custom link). Below is the script, but when I click the button I get the following error:

A problem with the OnClick JavaScript for this button or link was encountered: Unexpected token ILLEGAL

-------Script-------

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
   
var st = new sforce.SObject('Support_Ticket__c');

    st.RecordType = 'Magic Ticket';
    st.On_Behalf_Of__c = {!User.Id};

var result = sforce.connection.create([st]);
    if(result[0].getBoolean("success")){
       window.location = "/" + result[0].id + "/e";
          }else{
             alert('Could not create record '+result);
}

When I add order.Paid__c = true to the trigger below, I get a Fatal Error. Can someone explain why and the best way to handle this issue? I'm trying to generate a new object for paid orders we take from the website. All of the amount fields are summary rollups or formulas, so I can use them. 

trigger TermsandConditionsFutureMP on ccrz__E_Order__c (after update) {
   System.debug('TC Start execution of trigger');
   
   if(trigger.isAfter){ 
   
   String myString1 = 'Website';
   
       for (ccrz__E_Order__c order:trigger.new){
           ccrz__E_Order__c orderUpdate = System.Trigger.oldMap.get(order.id);
           if (order.Paid__c = true && orderUpdate.origin1__c != order.origin1__c){
               if (myString1.equalsIgnoreCase(order.Origin1__c)){
                  System.debug('TC trigger is after');
                  TermsandConditionsFutureMP.createTermsandConditionsMP (Trigger.newMap.keySet());
               }
           }
       }
   }
   System.debug('TC trigger has been executed');
}
I created the trigger below, which is set to fire when this field ccrz__TotalAmount__c is greater than zero and the origin equals website. The ccrz__TotalAmount__c is a formula and the debug log shows it is greater than $0, but it's still not firing the method. The trigger is an after update, so I figure the formula field would work. Any ideas? 

The other problem is all of the currency fields are either summary roll ups or formulas, so no matter which one I use I face the same problem. 

trigger TermsandConditionsFutureMP on ccrz__E_Order__c (after update) {
   System.debug('TC Start execution of trigger');
   
   if(trigger.isAfter){ 
   
   String myString1 = 'Website'; 
   
       for (ccrz__E_Order__c order:trigger.new){
           ccrz__E_Order__c orderUpdate = System.Trigger.oldMap.get(order.id);
           if (orderUpdate.origin1__c != order.origin1__c){
               if (order.ccrz__TotalAmount__c > 0 && myString1.equalsIgnoreCase(order.Origin1__c)){
                  System.debug('TC trigger is after');
                  TermsandConditionsFutureMP.createTermsandConditionsMP (Trigger.newMap.keySet());
               }
           }
       }
   }
   System.debug('TC trigger has been executed');
}
We use Salesforce and the Marketing Cloud. In SF, we're using the standard phone field which is formatting numbers as such (XXX) XXX-XXXX. To use SMS in the MC, I have to reformat the phone as follows 1-XXX-XXX-XXXX when the student is from the United States. I'm using the follow CASE function in SQL, but can't save the query without getting an error.

CASE WHEN a.Phone LIKE ('(%') THEN ('1'+'-'+ SUBSTRING(a.Phone,2,3) +'-'+ SUBSTRING(a.Phone,7,3)+'-'+ SUBSTRING(a.Phone,11,4)) as Phone
END

I'm trying to determine if the phone starts with a parenthesis and then format it correctly if it's true. Any ideas? a.Phone comes from a Data Extension that has the Salesforce phone in it.
I'm trying to find accounts with a student school that has a school type of "med_us." However, when I add the WHERE statement to the inner select it times out. See below:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c WHERE school_type__c = 'med_us') AND Educational_Background__c = 'IMG'AND createddate = TODAY

If I remove the WHERE statement it runs fine, but it's not giving me what I'm looking for:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c ) AND Educational_Background__c = 'IMG'AND createddate = TODAY

When searching for records across child objects are we allowed to use WHERE statements in the inner select? 

I've also tried this:

SELECT id, Educational_Background__c FROM Account WHERE ID IN (SELECT Account__c FROM Student_School__c) AND Educational_Background__c = 'IMG'AND createddate = TODAY AND school_type__c.student_school__r ='med_us'
I have a block with a VF page, and I want the red vertical bar to appear next to a field highlighting it is required. I've found a few suggestions online, but they don't seem to work. Any ideas? 
 
<apex:pageBlockSection title="Account Information" columns="2">
                
                <div class="reuqiredInput">
                    <div class="requiredBlock"></div>
                    <apex:inputText value="{!firstName}" label="First Name" required="true" />
                </div>
                
                <apex:inputField value="{!accountObject.PersonTitle}"/>
                <apex:inputText value="{!lastName}" label="Last Name *"/>
                <apex:inputField value="{!accountObject.Lead_Source__c}" label="Lead Source *"/>
                <apex:inputField value="{!accountObject.Hot_Flag__c}" label="Hot Lead"/>
                
            </apex:pageBlockSection>

 
  • September 28, 2015
  • Like
  • 0
We have a map which compares any updates on an account to what was previously there, and then returns true or false. During testing, I'm able to get to return true through the first If statement (line 31), but I can't see to get it to return anything for the Else If statement (line 37). Any ideas?
 
public without sharing class accountServices{
   Map <Id, Account> oldAccs;
   Map <Id, Account> newAccs;
   
	public accountServices (Map <Id, Account> newTriggerAccs, Map <Id, Account> oldTriggerAccs) {
           oldAccs = oldTriggerAccs;
           newAccs = newTriggerAccs;
       	   system.debug ('Old accounts' + ' ' + oldtriggerAccs);
           system.debug ('New accounts' + ' ' + newTriggerAccs);
   }
   
	public static boolean isChanged (account newacc, account oldacc) {
           Account oldAccs = oldacc;
           Boolean isChanged = (oldAcc.program_of_interest__c == null && newacc.program_of_interest__c != null) ||
               (oldAcc.program_of_interest__c != null && newacc.program_of_interest__c == null) ||
               !(oldAcc.program_of_interest__c.equals(newacc.program_of_interest__c));
			if (!ischanged) {
               isChanged = (oldacc.expected_test_date__c == null && newacc.expected_test_date__c != null) ||
                   (oldacc.expected_test_date__c != null && newacc.expected_test_date__c == null) ||
                   !(oldacc.expected_test_date__c == newacc.expected_test_date__c);
               system.debug ('Result 3' + ' ' + isChanged);
           }
           else if (!ischanged) {
               isChanged = (oldacc.expected_prep_start_date__c == null && newacc.expected_prep_start_date__c != null) ||
                   (oldacc.expected_prep_start_date__c != null && newacc.expected_prep_start_date__c == null) ||
                   !(oldacc.expected_prep_start_date__c == newacc.expected_prep_start_date__c);
               system.debug ('Result 4' + ' ' + isChanged);
           }
           
       return isChanged;
   }

........transformation code

 

My test class keeps getting this error when I push to production. I found the following article (https://help.salesforce.com/apex/HTViewSolution?id=000176562&language=en_US) and added the code to lines at the bottom. However, I keep getting a Compile Error: unexpected token: ')' at line 49 column 51. 

Is this the best way to resolve the original error? If so, any ideas on why I'm getting the Compile Error and how to overcome it? I've tried a few things but they all result in the same error. 

/************************************************************************************
** Module Name   : UserCleanUp 
**
** Description   : This class deactivates portal users setup by the website and
** irostering. It also deactivates Salesforce users that haven't logged in in the 
** last 90 days with the exception of Guest Site Users.
**
** Technial Info : <Batch Apex Class>
** 
** Author     : 
** Revision History:-
** Version  Date        Author 
** 1.0      1/6/15      
************************************************************************************/

global class KapUserCleanUp implements Database.Batchable<sObject>{

    datetime myDateTime = datetime.now();
    datetime newDateTime = myDateTime.addHours(-3);
    datetime inactiveDateTime = myDateTime.addDays(-90);

    //System.debug('current time: ' + myDateTime);
    //System.debug('newDateTime time: ' + newDateTime);
    //System.debug('inactiveDateTime time: ' + inactiveDateTime);

global Database.querylocator start(Database.BatchableContext BC){
            return Database.getQueryLocator([SELECT Email,Id,LastLoginDate FROM User WHERE (IsPortalEnabled = True AND IsActive = true AND (lastLoginDate < :newDateTime OR lastLoginDate = null)) OR (IsPortalEnabled = false AND isActive = true AND lastLoginDate < :inactiveDateTime AND LastName != 'Site Guest User')]);}

global void execute(Database.BatchableContext BC, List<User> users){
   System.debug('Users retrieved ' + Users);
   
   for (User u : users) {
       u.isActive = false;
       System.debug(u.id + ' ' + u.email + ' will be deactivated' + u.lastLoginDate);
   }
       Database.SaveResult[] srList = Database.update(users, false);
          for (Database.SaveResult sr : srList){
             if (!sr.isSuccess()) {
             //Operation failed, so get all errors
                for(Database.Error err : sr.getErrors()){
                     System.debug('The following error has occurred.');
                     System.debug(err.getStatusCode() + ': ' + err.getMessage());
                } 
             }  
          }
    }
   global void finish(Database.BatchableContext BC){
    if(!Test.isRunningTest)
         Database.executeBatch(new MySecondBatchJob));
       }
   }
I'm running batch apex to deactivate portal users every night, so we don't limit are limit on licenses. I'm getting this Exception on my test class when pushing the code to production. 

System.UnexpectedException: No more than one executeBatch can be called from within a testmethod

I found the following article which seems to have the solution, but I'm not sure where exactly to place the code block:

https://help.salesforce.com/apex/HTViewSolution?id=000176562&language=en_US

Here's the test class:

@isTest
private class KapUserCleanUpSchedulerTest {
public static testmethod void test() {
   
   Test.startTest();

   // Schedule the test job 
      String jobId = System.schedule('testMassScheduledApexonet', KapUserCleanUpScheduler.CRON_EXP, new KapUserCleanUpScheduler());
   // Get the information from the CronTrigger API object 
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];

   // Verify the expressions are the same 
      System.assertEquals(KapUserCleanUpScheduler.CRON_EXP, ct.CronExpression);
   // Verify the job has not run 
      System.assertEquals(0, ct.TimesTriggered);

   // Verify the next time the job will run 
      System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));

      public void finish(Database.BatchableContext);
         {
            if(!Test.isRunningTest)
               Database.executeBatch(new MySecondBatchJob));
         }
      
   Test.stopTest();
   
      }
   }

I'm new to coding, so any help is appreciated. Thanks!
We have an umlimited edition and I'm trying to create a new record called a "support ticket" off of a user's record (custom link). Below is the script, but when I click the button I get the following error:

A problem with the OnClick JavaScript for this button or link was encountered: Unexpected token ILLEGAL

-------Script-------

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
   
var st = new sforce.SObject('Support_Ticket__c');

    st.RecordType = 'Magic Ticket';
    st.On_Behalf_Of__c = {!User.Id};

var result = sforce.connection.create([st]);
    if(result[0].getBoolean("success")){
       window.location = "/" + result[0].id + "/e";
          }else{
             alert('Could not create record '+result);
}
We have a class that deactivate two sets of users: (1) our portal customers and (2) salesforce license users that haven't logged in in the past 90 days. The problem I'm facing is I keep running into exceptions when the license user is part of escalation rule on cases or in a workflow rule email alert. I looked at the following article, but I'm not exactly sure where to place the exception handling code: https://developer.salesforce.com/page/An_Introduction_to_Exception_Handling.

Can anyone help? Thanks!

List<User> users = [SELECT Email,Id,LastLoginDate FROM User WHERE (IsPortalEnabled = True AND IsActive = true and (lastLoginDate < :newDateTime OR lastLoginDate = null)) OR (IsPortalEnabled = false AND isActive = true AND lastLoginDate < :inactiveDateTime AND LastName != 'Site Guest User') limit 150];
            soqlCount = soqlCount + 1;   
            if (users.isEmpty()) {
                System.debug('No users found');
                done = true;
            } else {
                System.debug (users.size() + ' user account(s) will be updated');
                for(User u : users) {
                    u.isActive = false;
                    //System.debug(u.id + ' ' + u.email + ' will be deactivated' + u.lastLoginDate);
                }
                update users;         
            }