• Daniel B Probert
  • NEWBIE
  • 395 Points
  • Member since 2013
  • Head of IT Innovation
  • Camfed Internation


  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 25
    Questions
  • 159
    Replies
Hello everyone,

I am getting the error below when trying to make changes to my test class in Sandbox. 
Has anyone seen this before. Do you know how to fix it.

Thanks
Deployment Error
How to created an email alert if total amount of opened cases reaches lets say 100 per day?

Hello,

I have a test class that creates and Account (below).  In this class, I have included actual User IDs, which is not ideal, especially when users are de-activated.  How do I create dummy User IDs with specific profiles that I can use in this Class rather than the actual IDs?


public class TestStatusAcctCreate {

        // create and insert a new Account record that has an arbitrary value for Type and users assigned to the 3 custom fields.
    public static Account createAcct(Integer i){ 
        Account acct = new Account();
            acct.Name = 'Test' + i;
            acct.Type= 'Employer';
            acct.Client_Advisor__c = '00570000001LlBD';
            acct.Industry_Manager__c = '00570000001JKVQ';
            acct.Market_Director__c = '00570000001r5xs';
            
        return acct;
        
    }
}


  • June 06, 2014
  • Like
  • 0
Hello, I've created a VisualForce page and made it public. The page is to enter the Custom Object fields. One of them is a Lookup to another Custom Object. The problem is that for some reason when I click in the Lookup icon is not showing any information, and only showing:
•There are no records of this type
•You don't have permission to see any of the records
•Records do not fit the filter criteria set by your administrator
•One or more controlling fields are blank or invalid (Controlling fields: myCustomObject)

The thing is that when I'm logged in as an admin, the Lookup works perfectly.
I set up the Object Permissions under both custom objects, but still having the same result.
Any thoughts?
I'm trying to learn about triggers in SF - and am working on my first task: a trigger that will set an Opportunity price book based on two Account field values.

GPO__c is a text field
GPO_Tier__c is a number

I'm trying to set the Opportunity Price Book based on these field values. Example - if the Account GPO is "GPO A" and the GPO Tier is 1, it should match a price book with the name of "GPO A Tier 1".

Here's some code I've put together so far:

trigger SetOppPriceBook4 on Opportunity (before insert) {
	for(Opportunity o : trigger.new){
        
        List<Account> acct = [SELECT GPO__c, GPO_Tier__c, Id FROM Account WHERE ID = :o.AccountId]; 
        List<Pricebook2> pb = [SELECT id from Pricebook2 WHERE Name = :acct[0].GPO__c + ' Tier ' + :acct[0].GPO_Tier__c];
    
        if(!pb.isEmpty()){
        	o.PriceBook2Id = pb[0].id;
        }
     
        else {o.Pricebook2Id = NULL;
        
        }
    }

}
I think I'm running into some problems with concatenating within the select statement. What do I need to change
Hi,

I'm currently working on an Apex test class. However, the controller I'm trying to test is divided into several sections, each meant to be for diffferent profiles.
As a result, I've to test each profile using a single runAs() method for each profile users, but those were only able to test parts of the controller and not completely.
My test class has different methods for each profiles and they cover roughly 25-30 % of the code, so it is nowhere near 75% (let alone 100%).

I've tried to club different runAs() method calls in a single test method, but I'm hitting the maximum number of SOQL limit of 100.

Right now I'm stuck with 40% code coverage of my controller. Any help/suggestion will be very welcome..!!

Thanks,
~Ayan
Hi Guys,

I have created 1 trigger and one class in sandbox, I have written 2 test classes for this, one test for the trigger and one test for the class.

When I run the 'test run' in Sandbox it say Class have 100% coverage, however when trying to deploy the code in prod I get errors saying coverage is only 50%

Code Below

Trigger :
trigger myTrigger on Opportunity (after update) {
    string prams;
	
    // partner portal auth details
    prams = 'userkey=salesforce';
    prams = prams + '&passkey=password';
    
    // action occured in saledforce
    prams = prams + '&action=OpportunityUpdated';
    
    for (Opportunity op: trigger.new) {
        Opportunity oldOpportunity = Trigger.oldMap.get(op.Id);
        
        prams = prams + '&id[]=' + op.Id; // Opportunity ID
        prams = prams + '&name[]=' + op.Name;
        prams = prams + '&oldName[]=' + oldOpportunity.Name; // previous Name
        prams = prams + '&stageName[]=' + op.StageName;
        prams = prams + '&oldStageName[]=' + oldOpportunity.StageName; // previous stage
        prams = prams + '&closeDate[]=' + op.CloseDate;
        prams = prams + '&oldCloseDate[]=' + oldOpportunity.CloseDate; // previous close date
        prams = prams + '&closeLostReason[]=' + op.Closed_Lost_Reason__c;
        prams = prams + '&ownerId[]=' + op.OwnerId;
       	
    }
    
    Sync.invokeUrlWithPost('http://myurl.com', prams); 
}

My class 
public class Sync{
    
    //Future annotation to mark the method as async.
    @Future(callout=true)
    public static void invokeUrlWithPost(string url, string prams){ 
        if(url.length() > 0 && prams.length() > 0){
            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setEndpoint(url);
            req.setHeader('Content-Type', 'application/x-www-form-urlencoded'); 
            req.setBody(prams);
        
            Http http = new Http();
        
            try {
                HttpResponse res = http.send(req);
                system.debug('B:STATUS:'+res.getStatus());
            } catch(system.Exception e) {
                system.debug('B:Callout error:'+e);
            }
        }
        
    }
}

TEST CLASSES

testSync()
@isTest
public class testSync{

    static testMethod void testInvokeUrlWithPost(){
		String url = 'http://myurl.com';
        String prams;
            
        // partner portal auth details
        prams = 'userkey=salesforce';
        prams = prams + '&passkey=password';
        
        // action occured in saledforce
        prams = prams + '&action=testInvokeUrlWithPost&Name=test';
        
        test.startTest();
        System.assertEquals(url, 'http://myurl.com');
        
        Sync.invokeUrlWithPost(url, prams); 
        test.stopTest();
    }
    
    static testMethod void testInvokeUrlWithPost_noPrams(){
		String url = 'http://myurl.com';
        String prams = '';
                 
        test.startTest();
        Sync.invokeUrlWithPost(url, prams); 
        test.stopTest();
    }
    
    static testMethod void testInvokeUrlWithPost_invalidUrl(){
		String url = '';
        String prams;
        
        // partner portal auth details
        prams = 'userkey=salesforce';
        prams = prams + '&passkey=password';
        
        // action occured in saledforce
        prams = prams + '&action=testInvokeUrlWithPost&Name=test';
        
        test.startTest();
        Sync.invokeUrlWithPost(url, prams); 
        test.stopTest();
    }
    
}

test for my trigger
@isTest
public class testMyTrigger{

    static testMethod void testPurplePortalUpdate(){
		// create a new Opportunity
        Opportunity testOpp = new Opportunity( Name = 'My Test Opp', StageName = 'Qualification', CloseDate = System.today().addDays(4));
      	// insert it to the db
        insert  testOpp;
        
        // get the inserted Opportunity to edit it
        Opportunity oldOpp = [SELECT Name, StageName, CloseDate FROM Opportunity WHERE id = :testOpp.Id];
		
        // error if the Opportunity did not add
        System.assert(testOpp.Id != null, 'The Test opportunities did not insert properly, please check validation rules and other mechanisms');
        
        // change its name
        oldOpp.Name = 'Updated';
        System.assertEquals(oldOpp.Name, 'Updated');
        System.assertEquals(oldOpp.StageName, 'Qualification');

        // Start the test, this changes governor limit context to
    	// that of trigger rather than test.
        test.startTest();
        
        // update the Opportunity
        update oldOpp;

        // Stop the test, this changes limit context back to test from trigger
        test.stopTest();

    }   
    
    
}




I have a visualforce page to submit support requests, that has a workflow rule that sends it to the appropriate rep when it is submitted. 

When it is completed the rep enters the completion date.  What I want to do is set up a workflow rule that will send an email out to the requester when the completion date is added.  In this email I need to display the body of any notes that are attached to the record.

I know how to setup the workflow but how would I add the notes to the email template.
Using the example here:
http://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_dataTable.htm

I'm trying to get the following code to work:


Now, I this is only the first step.  I also have Opportunity_SubGroup__c that exist under Opportunity_Group__c
Apex page:
<apex:page controller="oppHierarchy" id="thePage">
	<apex:dataTable value="{!OGs}" var="Opportunity" id="theTable" rowClasses="odd,even" styleClass="tableClass">
		<apex:facet name="caption">table caption</apex:facet>
		<apex:facet name="header">table header</apex:facet>
		<apex:facet name="footer">table footer</apex:facet>
		<apex:column>
		        <apex:facet name="header">Name</apex:facet>
			<apex:facet name="footer">column footer</apex:facet>
			<apex:outputText value="{!OGs.name}"/>
		</apex:column>
		<apex:column>
			<apex:facet name="header">Quantity</apex:facet>
			<apex:facet name="footer">column footer</apex:facet>
			<apex:outputText value="{!OGs.Quantity__c}"/>
		</apex:column>
	</apex:dataTable>
</apex:page>
Class:
public class oppHierarchy {
	List<Opportunity_Group__c> OGs;
	public List<Opportunity_Group__c> getOGs() {
		if(OGs == null) OGs = [select name, Quantity__c from Opportunity_Group__c limit 10];
		return OGs;
	}
}


Ideally, I'll need to list related groups and subgroups on the opportunity page.

Maybe something like these will be needed in my Class?
public List<Task> getRelatedTasks() {
        return [select Id, Subject, ActivityDate, Status, Owner.Name, What.Name, Account.name, Type, CallType from Task where AccountId in :AllIds Order By ActivityDate Desc];
         
    
    }
    public List<Event> getRelatedEvents() {
        return [select Id, Legacy_Calltype__c, Subject, Type, Event_Status__c, Owner.Name, What.Name, ActivityDate from Event where WhatId in :AllIds Order By ActivityDate Desc];
    }

Instead of Tasks and Events I'd need Opportunity_Groups__c and Opportunity_Subgroups__c


Any help?


Hi,
Is it possible to have some kind of counter field on object which is updated and added whenever workflow is triggered on that object.

Example we want to know how many times workflow sent email when case status field was set to closed.
We have workflow on case object which sends survey email alert when case status is closed. We wish to count how many such emails were sent or rather how many times workflow was called to send email.

Thanks

I am trying to build a simple live notification lightning component for when a new private message is received. That way when you're on the community you don't rely on having to click into messages to see there is a new message.

My problem is that always returns a value of 0

Class:
 
public class CAMAComm_Notifications {
	
    @AuraEnabled
    public static integer getUnreadCount(){
        ConnectApi.UnreadConversationCount unreadMessageCount = ConnectApi.ChatterMessages.getUnreadCount();
		Integer numberOfUnreadMessages = unreadMessageCount.unreadCount;
        return numberOfUnreadMessages;
	}
}

my lightning cmp:
 
<aura:component implements="forceCommunity:availableForAllPageTypes" controller="CAMAComm_Notifications" access="global" >
    <aura:attribute name="unreadmessagecount" type="Integer"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    		<div class="slds-notify_container">
  				<div class="slds-notify slds-notify--alert slds-theme--success" role="alert" style="position: inherit !important;">
	    			<span class="slds-assistive-text">Success</span>
    				<p>{!v.unreadmessagecount} unread messages</p>
				</div>
			</div>    
	
</aura:component>

my controller js
 
({
    doInit : function(component, event, helper) {
        helper.messageCountpoller(component, event, helper);
    }
})

my helper js
 
({
    messageCountpoller : function(component, event, helper) { 
        helper.callApexMethod(component,helper);
        
        //execute callApexMethod() again after 5 sec each
        window.setInterval(
            $A.getCallback(function() { 
                helper.callApexMethod(component,helper);
            }), 5000
        );      
    },
    handleResponse : function (response, component){
        var retVal = response.getReturnValue();
        console.log('Number of Messages: ' + retVal);
        component.set("v.unreadmessagecount",retVal); 
    },
    callApexMethod : function (component,helper){    
        var action = component.get("c.getUnreadCount");        
        action.setCallback(this, function(response) {
            this.handleResponse(response, component);
        });
        $A.enqueueAction(action); 
    } 
})
from everything i can see this is in line with the documentation for the getUnreadCount() however it will never display anything but 0.

are private messages not supported using this method? If not how else can I do it?

cheers
dan

 
Hi all can anyone point me in the right direction for URL passing of cross filters within reports?

i've followed this guide and can't get it to work - i can get salesforce to recognise the cross filter but my filters within don't work

http://www.verticalcoder.com/2014/06/03/url-hacking-cross-filter-reports/

so basically my problem is that this works for my custom object

ptable0=072C0000002ezuA&ocond0=w&rtable0=01IC0000000qeCG&rtablecol0=00NC0000006DEAg

but adding in my filter within this doesn't work

&sfpc0_0=00NC0000006DEDY&sfpn0_0=eq&sfpv0_0=Term+1

has anyone managed to get url hacking for cross filters working and if so how - or whats another way around it?

thanks
dan

 
i've confused myself

i have an object with 2 fields

Form Name (external reference and unique name that is stored within the form_id field within a different custom object)
ObjectName__c (formula field that based on name enter the correct custom object mycustomobject__c)
Salesforce_Record_Count__c (i want to put the number of records that match my search critera in here)

i then want to create a batch process that will do something like this:

global class UpdateMonitoringForms implements Database.Batchable<sObject>{

    string query;
    global Database.querylocator start(Database.BatchableContext BC){
      Query = 'Select ID,Form_Name__c,Salesforce_Record_Count__c From Monitoring_Form__c';
      return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monitoring_Form__c> scope){
      List<Monitoring_Form__c> lstmforms = new List<Monitoring_Form__c>();  
       for (Monitoring_Form__c mf:scope) {
        string object = mf.ObjectName__c;
        IF(mf.ObjectName__c!= 'DO NOT PROCESS'){
          mf.Salesforce_Record_Count__c = [select count() from object where Form_ID__c =:mf.Form_Name__c];
        }
        lstmforms.add(mf)
        }
        update lstmforms;       
    }

    global void finish(Database.BatchableContext BC){

    }
}

so basically my challenge is how can I build my select count to use potentially a different customobject__c each time it runs.

I plan to limit this batch to only updating 20 records at time.

any thoughts or betters ways of doing this, please do as for clarification.

dan


Hi All,

I've recenrtly started working with some batch apex and have generally found it pretty simple to deal with but have now hit a problem that I can't get round.

Setup:

One object Entitlement__c which I need to provide a button to force update records that match a criteria.
I've create a second object Entitlement_Updates__c which allows them to set the criteria Year__c, Term__c

I then have a custom VF page that based on their criteria tells them how many records match and if the number is greater than 0 they get a button to press that is supposed to invoke a batch apex - all of this I've managed to get working relatively easily.

my problem is that I am unable to pass my soql query from my apex class to my batch apex.

Apex Class: 

public with sharing class FPS_ManualIntervention {
    public FPS_Update__c FPS { get; set; }
     // Class Constructor
    public FPS_ManualIntervention(ApexPages.StandardController controller){
        FPS =  (FPS_Update__c)controller.getRecord();  
      }
    // button page for firing of apex batch class
    public PageReference updaterecords() {
        string fpyear = fps.year__c;
        string fpterm = fps.term__c;
        string fpcountry = fps.country__c;
        string fpstudenttype = fps.student_type__c;
        Database.executeBatch(new BatchEntitlementUpdate('SELECT ID, Year__c, Term__c, StudentType__c, Student__r.Country__c ' +
                ' FROM Entitlement__c ' +
                ' WHERE Year__c =:\'' + fpyear + '\'' +
                ' AND Term__c =:\'' + fpterm + '\'' +
                ' AND StudentType__c=:\'' + fpstudenttype + '\''+
                ' AND Country__c=:\'' + fpcountry + '\''), 10);
        PageReference redirect  = new PageReference('/apex/FPSManageRunning?id=' + fps.id);
        redirect.setRedirect(true);
        return redirect;
        return null;
    }
 }

the button on this page is then firing this batch apex:

global class BatchEntitlementUpdate implements Database.Batchable<sObject>{

   global final String Query;

   global BatchEntitlementUpdate(String q){
             Query=q;
   }
   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
    global void execute (Database.Batchablecontext BC, list<Entitlement__c> scope){
        List<Entitlement__c> lsttoupdate = new List<Entitlement__c>();
        for(Entitlement__c ent:scope){
            ent.BatchProcess__c = 10;
            lsttoupdate.add(ent);
        }
        update lsttoupdate;
    }
    global void finish(Database.Batchablecontext BC){
    }
}

i've been reading so many docs that i've kind of lost the plot on how this should or could look now so any guidance appreicated.

the code as it is brings back: First error: Only variable references are allowed in dynamic SOQL/SOSL.


Hi All,

I have a subquery statement and I'm trying to make sure that parent records don't display if they have no child records available.

Query:

List<Training_Module__c> trainingmod;
    public List<Training_Module__c> gettrainingmod() {
        if(trainingmod == null) {
            trainingmod = [SELECT id, Name, Introduction__c,
                (SELECT id, Name, Introduction__c
                    FROM Training_Lessons__r
                    WHERE (Applicable_Country__c includes (:empcountry) and Applicable_Teams__c includes (:empteam) and Status__c=:'Online'))
                FROM Training_Module__c
                WHERE Training_Course__c =:currentpage and Applicable_Country__c includes (:empcountry) and Applicable_Teams__c includes (:empteam) and Status__c=:'Online'];
            }
            return trainingmod;
        }

Now I am displaying this on a page in a repeat 

<apex:repeat var="tm" value="{!trainingmod}" rendered="{!trainingmod.size>0}">
        <table border="0" width="100%">
            <tr>
                <th>Module</th>
                <th>Introduction</th>
            </tr>
            <tr>
                <td width="15%"><apex:outputfield value="{!tm.Name}" /></td>            
                <td colspan="3">{!tm.Introduction__c}</td>           
            </tr>
            <tr>
                <th></th>
                <th>Lesson</th>
                <th>Introduction</th>
            </tr>
            <apex:repeat var="tmsg" value="{!tm.Training_Lessons__r}">
                <tr>
                    <td>&nbsp;</td>
                    <td width="15%"><apex:outputfield value="{!tmsg.Name}" /></td>
                    <td width="55%">{!tmsg.Introduction__c}</td>
                    <td><a href="/apex/TrainingLesson?id={!tmsg.id}"><button type="button">Take Lesson</button></a></td>
                </tr>
            </apex:repeat>

my query is where i have: rendered="{!trainingmod.size>0}" in my apex:repeat

how can i make it only display if training_lesson__r.size>0 i tried rendered="{trainingmod.training_lesson__r.size>0 but get an error

Error: Unknown property 'VisualforceArrayList.training_lesson__r'

any ideas do i have to do this in the apex?

any guidance appreciated.

dan
Hi,

I have a VF page that is loaded on my contact page:

<apex:page showHeader="false" sidebar="false" standardController="Contact" extensions="GivingSummaryContactExtension">

	<c:GivingSummary SourceObject="{!objId}" FilterField="Donor__c" />
	
</apex:page>
the extensions for this is:

public with sharing class GivingSummaryContactExtension {
  public Id objId {get; set;}

  public GivingSummaryContactExtension(ApexPages.StandardController con) {
    objId = con.getId();
  }
}

the page you'll notice calls a custom component code here:

<apex:component controller="GivingSummaryComponentController">

	<apex:attribute name="SourceObject" type="String" assignTo="{!ObjectId}" description="Contact or Account Id"/>
	<apex:attribute name="FilterField" type="String" assignTo="{!FieldName}" description="Field on donation to filter against"/>

	<apex:pageBlock >
		<apex:pageBlockTable value="{!Values}" var="item">
			<apex:column value="{!Values[item].DonationType}" headerValue="Donation Type"/> 
			<apex:column headerValue="Total">
				<apex:outputText value="{!CurrencySymbol}{!Values[item].Total}" />
			</apex:column> 
			<apex:column headerValue="Year To Date">
				<apex:outputText value="{!CurrencySymbol}{!Values[item].YearToDate}" />
			</apex:column> 
			<apex:column headerValue="Last Year">
				<apex:outputText value="{!CurrencySymbol}{!Values[item].LastYear}" />
			</apex:column> 
		</apex:PageBlockTable>
	</apex:pageBlock>

this is the bit that i haven't been able to figure out how to test - this controller:

public with sharing class GivingSummaryComponentController {

  public String FieldName {get; set;}
  public String ObjectId {get; set;}

  private Map<Id, GivingAmounts> theValues;

  public GivingSummaryComponentController() {


  }

  private string getISOCOde(){

    String qry = 'SELECT CurrencyIsoCode FROM ' + ((Id)ObjectId).getSObjectType().getDescribe().getName() + ' WHERE Id = \'' + objectId + '\'';
    List<sObject> objs = database.query(qry);

    if(!objs.isEmpty())
      return (String)objs[0].get('CurrencyIsoCode');
    else
      return 'GBP';
  }

  public String getCurrencySymbol(){

    String code = getISOCode();
    String currencySymbol = 'x';
    if(code == 'GBP')
      currencySymbol = '£';
    else if(code == 'USD')
      currencySymbol = '$';
    

    return currencySymbol;
  }

  public Map<Id, GivingAmounts> getValues(){

    if(theValues == null){
      theValues = new Map<Id, GivingAmounts>();
      for(RecordType rt : [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Opportunity'])
        theValues.put(rt.Id, new GivingAmounts(rt.Name));
    }else 
      return theValues;


    // Total
    String qry = 'SELECT RecordTypeId, Amount FROM Opportunity WHERE IsWon = TRUE AND ' + FieldName + ' = \'' + ObjectId + '\'';
    for(Opportunity opp : database.query(qry))
      theValues.get(opp.RecordTypeId).Total += opp.Amount;

    // YTD
    qry = 'SELECT RecordTypeId, Amount FROM Opportunity WHERE CloseDate = THIS_YEAR AND IsWon = TRUE AND ' + FieldName + ' = \'' + ObjectId + '\'';
    for(Opportunity opp : database.query(qry))
      theValues.get(opp.RecordTypeId).YearToDate += opp.Amount;
    
    // Last Year
    qry = 'SELECT RecordTypeId, Amount FROM Opportunity WHERE CloseDate = LAST_YEAR AND IsWon = TRUE AND ' + FieldName + ' = \'' + ObjectId + '\'';
    for(Opportunity opp : database.query(qry))
      theValues.get(opp.RecordTypeId).LastYear += opp.Amount;

    return theValues;
  }

  public class GivingAmounts{

    public String DonationType {get; set;}
    public Decimal YearToDate {get; set;}
    public Decimal LastYear {get; set;}
    public Decimal Total {get; set;}

    public GivingAmounts(String name){
      this.DonationType = name;
      this.YearToDate = 0.00;
      this.LastYear = 0.00;
      this.Total = 0.00;
    }

  }
}

i've got a test that is 100% for the extensions but I can only get 9% on the component controller - this is what i've got so far - any ideas?

@isTest
public class Test_GivingSummary{
    public static testMethod void Contact(){
        ID HAcc = [select Id from RecordType where Name = 'Household' and SobjectType = 'Account'].id;
        ID HCon = [select Id from RecordType where Name = 'Household Contact' and SobjectType = 'contact'].id;
        Account acc = new Account(RecordTypeID=HAcc,Name='Tests');
        insert acc;
        Contact con = new Contact(RecordTypeID=HCon,LastName='Demo',FirstName='Demo',AccountID=acc.id);
        insert con;
        Campaign camp = new Campaign(Name='Demo');
        insert camp;
        Opportunity opp = new Opportunity(Name='DEMO',Amount=10.00,CurrencyISOCode='GBP',Donor__c=con.id,AccountID=acc.id,CampaignID=camp.id,StageName='Received',CloseDate=system.today());
        insert opp;
        
        ApexPages.Standardcontroller sc1 = New ApexPages.StandardController(con);
        GivingSummaryContactExtension   ext = new GivingSummaryContactExtension(sc1 );
        PageReference pageRef = Page.GivingSummary;
        Test.setCurrentPageReference(pageRef);

    

    }
   
    public static testMethod void ContactAccountController(){
        ID HAcc = [select Id from RecordType where Name = 'Household' and SobjectType = 'Account'].id;
        ID HCon = [select Id from RecordType where Name = 'Household Contact' and SobjectType = 'contact'].id;
        Account acc = new Account(RecordTypeID=HAcc,Name='Tests');
        insert acc;
        Contact con = new Contact(RecordTypeID=HCon,LastName='Demo',FirstName='Demo',AccountID=acc.id);
        insert con;
        Campaign camp = new Campaign(Name='Demo');
        insert camp;
        Opportunity opp = new Opportunity(Name='DEMO',Amount=10.00,CurrencyISOCode='GBP',Donor__c=con.id,AccountID=acc.id,CampaignID=camp.id,StageName='Received',CloseDate=system.today());
        insert opp;
        


        GivingSummaryComponentController myACController = new GivingSummaryComponentController();
        
        
        PageReference myPage = new Pagereference('/apex/GivingSummaryContact');
        Test.setCurrentPage(myPage);        


        
        

    }
}

any one able to point me in the right direction for getting closer to 100% on the controller.

cheers
dan

Hi All,

I have a simple holiday leave app in salesforce that i have added a trigger to that will create an event. I wanted to create the event in a public calender so that they are all viewable from one location.

This is what i have so far which works:

trigger Trg_Employee_Leave_Event on Leave__c (after insert, after update) {
if(Trigger.isInsert || Trigger.isUpdate)
    {
        List<Event> events = new List<Event>();
        ID UKCAL =  '023C0000002UQsP';
        List<Leave__c> Opps = Trigger.new;
        for (Leave__c Opp : Opps)
        {
            if(opp.Status__c=='Approved'){
                Event evt = new Event();
                if(opp.Country__c=='United Kingdom'){
                evt.Ownerid = UKCAL;
                }
                if(opp.Country__c!='United Kingdom'){
                evt.Ownerid = UserInfo.getUserID();
                }
                evt.Subject = opp.Leave_Type__c;      
                evt.StartDateTime = Opp.Start_Date__c;
                evt.EndDateTime = Opp.Return_Date__c;  
                evt.isAllDayEvent = true;
                evt.WhatID = opp.Employee__c;
                evt.LeaveID__c = opp.ID;
            Events.add(evt);
          
        }
        }
        insert events;
    }
}

now my only problem with this is the line:

ID UKCAL =  '023C0000002UQsP';

I would prefer if this was a select id from ??? where name = 'UK Leave Calendar'

but i can't for the life of my find what i do the select from to get said ID.

I keep reading that it's not possible as it's kind of hidden but hoping that's not true as hard coding ID is bad practice.

Any guidance appreciated.

Dan
Hi,

I'm having a really annoying issue with the test class that I'm putting together that I can't figure out what I'm getting an error on so hoping someone in the community can point me in the right direction.

I have an Object Leave__c that I use to log holidays(nothing special just a link to employee records/start/return dates)
I have created a simple VF Page for adding leave:

<apex:page standardcontroller="Leave__c" extensions="employee_leave_controller" showheader="false" sidebar="false">
<apex:stylesheet value="{!URLFOR($Resource.myStyles, 'employee.css')}"/>
    <div style="width:100%; height:100%">
        <a href="/apex/my_leave?"><button type="button">Back to My Leave List</button></a>
    </div>
    <apex:form >
        <apex:pageBlock title="Submit Leave for {!$User.FirstName}">
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Leave Information">
                <apex:inputField value="{!Leave__c.Leave_Type__c}" required="true"/>
                    <span>Select your leave type</span>
                <apex:inputField value="{!Leave__c.Employee__c}" required="true"/>
                    <span>Is this you? If not contact IT</span>
                <apex:inputField value="{!Leave__c.Start_Date__c}" required="true"/>
                    <span>Enter the first day of your holiday</span>
                <apex:inputField value="{!Leave__c.Return_Date__c}" required="true"/>
                    <span>Enter the day before your return to work</span>
                <apex:inputField value="{!Leave__c.No_Of_Days__c}" onfocus="true" required="true"/>
                    <span>{!$ObjectType.Leave__c.fields.No_Of_Days__c.InlineHelpText}</span>               
                <apex:inputField value="{!Leave__c.Notes__c}"/>
                    <span>Any additional information about your abscense that will help your line manager quickly approve.</span>
            </apex:pageBlockSection>
       </apex:pageBlock>
    </apex:form>
</apex:page>

This is my apex extension:

public class employee_leave_controller { 
    private Leave__c leave;
    private ApexPages.StandardController stdController;
    public employee_leave_controller (ApexPages.StandardController controller) {
       
        //pre-populate Lost notes on load
        this.leave = (Leave__c)controller.getRecord();
        leave.Employee__c = [select id from employee__c where Salesforce_Account__r.id =: UserInfo.getUserID()].id;
        stdcontroller=controller;
       
    }
   
   
    public PageReference save()
    {
        //Custom Save Code
        upsert leave;
        PageReference pageRef=Page.my_leave;
        return pageRef;
     }
}

and this is my test class(note the system administrator i've only added now to check the error wasn't permissions related):

@isTest
public class Test_Employee_Portal{
public static testMethod void TestMyLeaveRequest(){
        // set up user and manager
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u1 = new User(Alias = 'standt1', Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u1;
        User u2 = new User(Alias = 'standt2', Email='demo2@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo2@camfed.org', ManagerID=u1.Id);
        insert u2;
        //add employee
        Employee__c emp=new Employee__C(Name='Demo Demo',First_Name__c='Demo',Last_Name__c='Demo',Salesforce_Account__c=u2.id);
        insert emp;
//add employee holiday allowance        
Employee_Holiday_Entitlement__c empent=new Employee_Holiday_Entitlement__c(Allowance__c=10,Employee__c=emp.id,Year__c='2014');
        insert empent;
       //test creating a new page
        System.runAs(u2){
            PageReference pageRef = Page.my_leave_request;
            Test.setCurrentPage(pageRef); 
             // leave details 
            Leave__c leav = new Leave__c(Employee__c=emp.id,Start_Date__c=system.today(),Return_Date__c=system.today(),No_of_days__c=5,Leave_Type__c='Holiday');
            insert leav;
       
            ApexPages.standardController controller = new ApexPages.standardController(leav);
           
            employee_leave_controller pag = new employee_leave_controller(controller);         
            pag.save();
        }
    }

the error that i'm getting is:

System.SObjectException: Field is not writeable: Leave__c.Employee__c
Class.employee_leave_controller.<init>: line 8, column 1
Class.Test_Employee_Portal.TestMyLeaveRequest: line 23, column 1

Anyone able to give me a steer on what i've got wrong.

many thanks
dan

hi all, i'm unable to get my test class above 63% for this wrapper.

 

here is the class

public class SMSSendBulk {
    
    public List<cContact> contactList {get; set;}
    public List<cContact> getContacts() {
        if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c: [select Id, Name, Email, country__r.Name, district__r.name,sms_enabled__c, mobilePhone from Contact where SMS_Enabled__c = true]) {
                contactList.add(new cContact(c));
            }
        }
        return contactList;
    }
   public SMSSendBulk() {
    }
   public SMS_Message__c smss;
    public SMSSendBulk(ApexPages.StandardController controller) {
        smss = (SMS_Message__c) controller.getRecord();
        system.debug(smss);
    }
   public PageReference processSelected() {
        
    
        List<Contact> selectedContacts = new List<Contact>();
        
        for(cContact cCon: getContacts()) {
            if(cCon.selected == true) {
                selectedContacts.add(cCon.con);
            }
        }
        for(Contact con: selectedContacts) {
            sms_message__c newSMS = new SMS_Message__c();
            newSMS.Contact__c = con.ID;
            newSMS.Message__c = smss.Message__c;
            newSMS.status__c = 'Sent';
            newSMS.direction__c = 'Outbound';
            newSMS.bulksms__c = true;
            newSMS.date_sent__c = system.Now();
            newSMS.recordtypeid = [select Id from RecordType where Name = 'Outbound' and SobjectType = 'SMS_Message__c'].Id;
            insert newSMS;  
        }
        contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
        return null;
    }

    public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
    public cContact(Contact c) {
            con = c;
            selected = false;
        }
    }
}

 this is the vf incase it's needed or wanted:

 

<apex:page standardController="SMS_Message__c" extensions="SMSSendBulk">
<apex:form id="frmSubmitMassTask">         
        <apex:messages />
        <apex:pageBlock title="New Bulk SMS Service" mode="Edit" id="field_section">      
            <apex:pageBlockSection title="SMS Message" columns="1">
                <apex:inputField value="{!SMS_Message__c.Message__c}" styleClass="smsMessage" required="true" />  
                <p class="countdown"> Characters remaining <span id="count"> 160</span></p>
                <apex:pageBlockSectionItem />                                   
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="Send SMS" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>

            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column ><apex:facet name="header">
                        <apex:inputCheckbox onclick="checkAll(this,'checkedone')"/>
                </apex:facet>
                    <apex:inputCheckbox value="{!c.selected}" id="checkedone"/></apex:column>
                
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.MobilePhone}" />
                <apex:column value="{!c.con.Country__r.name}" />
                <apex:column value="{!c.con.District__r.name}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"/>
    <script>
        var j$ = jQuery.noConflict();
        
        j$(document).ready(function(){
            updateRemaining();
            j$(".smsMessage").bind('input keyup paste', function(){ 
                updateRemaining();
            });
        });
       
        function updateRemaining(){
            var count = j$("#count")
            var length = j$(".smsMessage").val().length;
            var remaining = 160 - length;
            count.text(remaining);
            
            if(remaining < 0){
                count.addClass('red');
            }else{
                count.removeClass('red');
            }
        }
    </script>
    <script type="text/javascript">
    function checkAll(cb,cbid)
        {
            var inputElem = document.getElementsByTagName("input");                     
            for(var i=0; i<inputElem.length; i++)
            {             
                 if(inputElem[i].id.indexOf(cbid)!=-1){                                        
                    inputElem[i].checked = cb.checked;
                }
            }
        }
</script>
    <style>
        .smsMessage{
            width: 135px;
            height: 100px;
        }
        .countdown{
        margin-left: 18%;
        margin-top: -4px;
        }
        .red{
            color: #CC0000;
            font-weight: bold;
        }
    
    </style>
</apex:page>

 this is my test class so far:

 

@isTest
public class Test_SMSSendBulk {
    static testMethod void myUnitTest() {     
        
        Country__c count=new country__c(Name='test');
        insert count;
        district__c dist=new district__c(Name='test',country__c=count.id);
        insert dist;
        contact con=new contact(lastname='test',mobilephone='+44717417554',district__c=dist.id,sms_enabled__c=true);
        insert con;
        List<Contact> contactlist = [select LastName from contact limit 1];
        // Instantiate the controller
        PageReference pageRef = Page.SendBulkSMS;
        Test.setCurrentPage(pageRef);
               
        SMSSendBulk sc = new SMSSendBulk();      
        Pagereference S = sc.processSelected();
 
        sc.contactList=sc.getContacts();  
        sc.contactList[0].selected=true;
             
        }
}

 the last line in here:

 

sc.contactList[0].selected=true; doesn't seem to be selecting the contact on the page and so it's not showing as having tested that line, also when i add in:

 

sc.smss.message__c = 'test';

as an attempt to include the message i want sending i get a null reference error.

 

any guidance the selected=true is driving me crazy if i change it to [1] i get an error(list out of bounds).

 

cheers

dan

hi all anyone able to help me with a test class that i'm working on.

 

I have a trigger on an object that when a new record is created it calls an external website and imports an xml file(this works)

 

trigger:

trigger MonitoringUpdater on Monitoring_Update__c (after insert) {

  for (Monitoring_Update__c mformupdate : Trigger.New) {
    MonitoringFormsUpdaterManual.updateMF();
  }

}

 the apex is:

 

public class MonitoringFormsUpdaterManual {
  @Future(callout=true)
  public static void updateMF() {
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://magpi.com/api/surveys?username=username&accesstoken=authtoken');
    req.setMethod('POST'); 
    HTTPResponse res = http.send(req);
    System.debug(res.getBody());
    List<Monitoring_Form__c> newforms = new List<Monitoring_Form__c> ();
    set<string> existingmFormSetId = new set<string>();
 //iterate thru the existing mforms and add allthe form_id__c in a set. And then use this set to later check for duplicates
 for(monitoring_form__c mform: [SELECT Id, Form_id__c FROM Monitoring_Form__c]){
    existingmFormSetId.add(mform.Form_id__c);
 }
    string s = res.getBody();
    Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement();
        dom.XmlNode [] xrec = xroot.getchildelements(); //Get all Record Elements
        for(Dom.XMLNode child : xrec) //Loop Through Records
            {
            Monitoring_Form__c mf = new Monitoring_Form__c();
            for(dom.XmlNode magpi : child.getchildren() ) {
               if (magpi.getname() == 'SurveyId') {
                     mf.form_id__c = magpi.gettext();
                 }
               if (magpi.getname() == 'SurveyName') {
                       mf.name = magpi.gettext();
                }
            }
            if(!existingmFormSetId.contains(mf.form_id__c)){
            newforms.add(mf);}
        }
        upsert newforms;
  }
        
  }

 now my test class that currently on has 24% coverage on the class and 100% on the trigger looks like this:

 

@isTest
global class Test_MFUpdateManualClass {
    public void myMonitoringManTest() {

// create a contact
Monitoring_Update__c monup = new Monitoring_Update__c();    
    monup.reason__c = 'test to fire of trigger';
insert monup;
Monitoring_Form__c mf = new Monitoring_Form__c();
    mf.form_id__c = '123';
    mf.name = 'Demo survey';
insert mf;
}
global class MockMagpiGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('https://magpi.com/api/surveys', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/xml');
        res.setBody('<Surveys><Survey><SurveyID>123</SurveyID><SurveyName>Demo survey</SurveyName></Survey></Surveys>');
        res.setStatusCode(200);
        return res;
    }
}}

 can anyone guide me in the right direction i know that i have testing the callout it's the reading of the data part so this bit that I haven't tested:

 

List<Monitoring_Form__c> newforms = new List<Monitoring_Form__c> ();
    set<string> existingmFormSetId = new set<string>();
 //iterate thru the existing mforms and add allthe form_id__c in a set. And then use this set to later check for duplicates
 for(monitoring_form__c mform: [SELECT Id, Form_id__c FROM Monitoring_Form__c]){
    existingmFormSetId.add(mform.Form_id__c);
 }
    string s = res.getBody();
    Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement();
        dom.XmlNode [] xrec = xroot.getchildelements(); //Get all Record Elements
        for(Dom.XMLNode child : xrec) //Loop Through Records
            {
            Monitoring_Form__c mf = new Monitoring_Form__c();
            for(dom.XmlNode magpi : child.getchildren() ) {
               if (magpi.getname() == 'SurveyId') {
                     mf.form_id__c = magpi.gettext();
                 }
               if (magpi.getname() == 'SurveyName') {
                       mf.name = magpi.gettext();
                }
            }
            if(!existingmFormSetId.contains(mf.form_id__c)){
            newforms.add(mf);}
        }
        upsert newforms;
  }
        

 

any guidance appreciated.

 

dan

 

 

Hi Anyone able to tell me what's wrong with my test class.

 

here is my schedule:

global class MFHourlyScheduler implements Schedulable{
    global MFHourlyScheduler (){}
    
    public static void start(){
    String mfsch = '0 0 13 * * ?';
        System.schedule('Forms Update', mfsch, New MFHourlyScheduler());
    }

    global void execute(SchedulableContext ctx){
        MFUpdateBatch b = new MFUpdateBatch();
        database.executebatch(b);    
    }
}

 and here is my test class:

 

@istest
class TestMFSchedule {
   static testmethod void test() {
   Test.startTest();
   String mfsch = '0 0 13 * * ?'; 
    system.schedule('Forms Update', mfsch, New MFHourlyScheduler());

   Test.stopTest();
   }
}

 i get it to 57% with this being marked as now being tested:

public static void start(){
String mfsch = '0 0 13 * * ?';
System.schedule('Forms Update', mfsch, New MFHourlyScheduler());

 any ideas appreciated.

 

dan

Hi,

 

Can anyone provide an example of creating a picklist of fields within an object.

 

I have an object call forms that has a field - Mapping_Object__c - within this I am storing the name of a custom object

 

i need to then for a child record display the field associated with the mapping object within a selectlist as a single select option.

 

i have found some examples but none that are doing anything like what I need.

 

I'm guessing in my class i need to query the parent object to get the mapping_object__c - i then need to use that value to get the fieldnames related to the object.

 

any ideas or examples of how to do this would be appreciated.

 

cheers

dan

Hi, i'm trying to find an example of something similar to this so I can see how to do it.

 

I have a custom object called Forms__c - one of the fields on this page is called Mapping_Object__c which is a picklist of custom objects in salesforce(hardcoded as we only want to display 5)

I have created a new override vf page that displays the form details and has a tab called questions.

On the questions page i would like to display a list of questions with a field call question_binding__c(text field) that is a picklist of all salesforce fields that are in the object referenced in Mapping_Object__c

 

i hope there is an example of this somewhere that can help me acheive this.

 

thanks

dan

 

Hi,

 

I'm doing a HTTP Callout from a trigger on a specific object. The trigger basically runs when a record is updated and checks online for related records.

 

I thought I had worked it out but I'm getting an error of:

 

System.ListException: Before Insert or Upsert list must not have two identically equal elements

here is my code basically it should go off to an external site - then grab the xml response - then go through an create a new record for each child element based on my if statements and also fill in the a lookup field with the record id the the trigger was initiated from.

 

i think it's because of how i'm grabbing the recordid and formid at the beginning but am not sure.

 

public class MonitoringQuestionsUpdater {
  @Future(callout=true)
  public static void updateMQ() {
    List<Monitoring_Form__c> mfcs = [SELECT Id, Form_Id__c FROM Monitoring_Form__c]; 
    for(Monitoring_Form__c a:mfcs){
    string formid = a.form_id__c;
    string recordid = a.id;
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://magpi.com/api/questions?username=myusername&accesstoken=mytoken&surveyid='+formid);
    req.setMethod('POST'); 
    HTTPResponse res = http.send(req);
    System.debug(res.getBody());
    List<Monitoring_Questions__c> newquestions = new List<Monitoring_Questions__c>();
    set<string> existingmQuestSetId = new set<string>();
 //iterate thru the existing mforms and add allthe form_id__c in a set. And then use this set to later check for duplicates
 for(monitoring_questions__c mquest: [SELECT Id, questionid__c FROM Monitoring_Questions__c]){
    existingmQuestSetId.add(mquest.questionid__c);
 }
    string s = res.getBody();
    Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement();
        dom.XmlNode [] xrec = xroot.getchildelements(); //Get all Record Elements
        for(Dom.XMLNode child : xrec)
            {
        for(dom.XmlNode magpi : child.getchildren() ) {
           Monitoring_Questions__c mq = new Monitoring_Questions__c();
           if (magpi.getname() == 'Id') {
           System.debug(magpi.getname() == 'Id');
                   mq.QuestionID__c = magpi.gettext();
             }
           if (magpi.getname() == 'Prompt') {
           System.debug(magpi.getname() == 'Prompt');
                   mq.Question_Prompt__c = magpi.gettext();
             }
           if (magpi.getname() == 'Name'){
           System.debug(magpi.getname() == 'Name');
                  mq.Question_Name__c = magpi.gettext();  
         }
         mq.monitoring_form__c = recordid;
        if(!existingmQuestSetId.contains(mq.questionid__c)){
            Newquestions.add(mq);
                }
            }
        }
        insert newquestions;
      }
    }
}

 

any help is appreciated.

 

dan

 

hi all,

 

i've been triyng to pull data from a remote service and have managed to get connected and can see in the logs that my child items are being read - my only issue is that the new records that I want creating aren't being created.

 

here is my code can anyone see what this isn't created montioring forms - the apex is triggered when we create a new form, basically it will then go off and check the remote service for any new forms on the server.

 

cheers

dan

 

public class MonitoringFormsUpdater {
  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateMF() {
    //construct an HTTP request
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://magpi.com/api/surveys?username=myusername&accesstoken=myaccesstoken');
    req.setMethod('POST'); 
    //send the request
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
    // list object ready for insert 
    List<Monitoring_Form__c> newforms = new List<Monitoring_Form__c> ();
    string s = res.getBody();
    Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement();
        dom.XmlNode [] xrec = xroot.getchildelements(); //Get all Record Elements
        for(Dom.XMLNode child : xrec) //Loop Through Records
            {
            Monitoring_Form__c mf = new Monitoring_Form__c();
        for(dom.XmlNode magpi : child.getchildren() ) {
           if (magpi.getname() == 'SurveyId') {
                   mf.form_id__c = magpi.gettext();
             }
           if (magpi.getname() == 'SurveyName') {
                   mf.name = magpi.gettext();
             }  
         }
        newforms.add(mf);
        }
  }
}

 the remote service returns this xml file.

 

<Surveys>
<Survey>
<SurveyId>7471</SurveyId>
<SurveyName>Bole_ASD_JHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7450</SurveyId>
<SurveyName>Bole_ASD_Pri</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7493</SurveyId>
<SurveyName>Bole_ASD_SHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7474</SurveyId>
<SurveyName>Bongo_ASD_JHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
<Survey>
<SurveyId>7494</SurveyId>
<SurveyName>Bongo_ASD_SHS</SurveyName>
<Owner>episurveyor@camfed.org</Owner>
</Survey>
</Surveys>

Hi All,

 

I have an external webservice that I am looking to pull data from in salesforce as a batch process. 

 

at the moment if I run the following command I get an xml response

 

curl -X POST -d "username=test@test.com&accesstoken=djkfdjfdkfjdklfjdlk" https://webserver/api/surveys

 

this will give me an output of

 

<Surveys>

<Survey><SurveyID>62</surveyid><SurveyName>Test</SurveyName><owner>test@test.com</owner></survey>

</surveys>

 

Ideally I would want to take this xml file and then populate an object called forms with the surveyid and the surveyname, with the surveyid being the unique reference.

 

any guidance would be appreciated.

 

cheers

dan

 

 

hey, i'm getting a dml 151 error with the below trigger when we bulk upload:

 

trigger AR_ContactUpdate on Academic_Record__c(after update){

Map<String, String> ARIDMap = new Map<String, String>();
for(Academic_Record__c e: trigger.new) {
     ARIDMap.put(e.ID, null);
    }

List<Contact> ContactsToUpdate = [select id,current_academic_record__c from contact where current_academic_record__c in: ARIDMap.KeySet()];
    for (Academic_Record__c ar: Trigger.New){
        if (ar.parentarmatch__c==true){
            Contact c = new Contact(Id=ar.Person__c);
                c.Accommodation__c=ar.Accommodation__c;
                c.Donor__c=ar.Donor__c;
                c.Form__c=ar.Form__c;
                update c;
        }
    }
}

 i've tried updating the code to this but then the trigger doesn't seem to work:

 

trigger AR_ContactUpdate on Academic_Record__c(after update){

Map<String, String> ARIDMap = new Map<String, String>();
for(Academic_Record__c e: trigger.new) {
     ARIDMap.put(e.ID, null);
    }
public void sav(){
List<Contact> ContactsToUpdate = [select id,current_academic_record__c from contact where current_academic_record__c in: ARIDMap.KeySet()];
    for (Academic_Record__c ar: Trigger.New){
        if (ar.parentarmatch__c==true){
            Contact c = new Contact(Id=ar.Person__c);
                c.Accommodation__c=ar.Accommodation__c;
                c.Donor__c=ar.Donor__c;
                c.Form__c=ar.Form__c;
                ContactsToUpdate.add(c);
        }
        if(ContactsToUpdate.size() > 0)
        insert ContactsToUpdate;
        }
    }
}

 any ideas what i'm missing?

 

cheers

dan

Hi All,

 

Anyone able to help me fill a gap.

 

I have the below VF page and Apex code that allow me to filter current information within a custom object.

 

What I need and I can't find an example of how to do this is the ability to press my clone button and have it clone any records that I have checked.

 

At the moment the below will display a list that match the criteria as well as provide 3 additional columns - one for year & term and checkbox for you to select. Once you have done this I would like to be able to press the clone button then all the records checked will be cloned and the year and term updated based on what I've selected.

 

VF Page:

<apex:page controller="DESCloningController">
 <apex:form > 
  <apex:pageBlock >
  <apex:pageBlockSection >
          <apex:inputField value="{!SearchCriteria.Sheet_Type__c}"/>   
          <apex:inputField value="{!SearchCriteria.Year__c}"/>
          <apex:inputField value="{!SearchCriteria.Term__c}"/>
          <apex:commandButton value="Search" action="{!Des}" reRender="applicantTbl,error"/>
          <apex:commandButton value="Clone" action="{!cloneDes}" />
  </apex:pageBlockSection>
  <apex:pageBlockSection id="applicantTbl"  >
            <apex:pageBlockTable value="{!DESs}" var="des" columns="7">
                <apex:column headerValue="Clone">
                    <apex:inputCheckbox value="{!clone}"/>
                </apex:column>
                <apex:column headerValue="Year"> 
                    <apex:selectList size="1" value="{!termoptions}" >
                        <apex:selectOptions value="{!items1}"/>
                    </apex:selectList>
                </apex:column>
                <apex:column headerValue="Term"> 
                    <apex:selectList size="1" value="{!yearoptions}" >
                        <apex:selectOptions value="{!items}"/>
                    </apex:selectList>
                </apex:column>
                <apex:column value="{!des.District__c}" headerValue="District"></apex:column>
                <apex:column value="{!des.Year__c}" headerValue="Year"></apex:column>
                <apex:column value="{!des.Term__c}" headerValue="Term"></apex:column>
                <apex:column value="{!des.Sheet_Type__c}" headerValue="Sheet Type"></apex:column>
            </apex:pageBlockTable>
        </apex:pageBlockSection>
      <apex:pageMessages id="error"></apex:pageMessages>
  </apex:pageBlock>
  
    </apex:form>
</apex:page>

 Apex Class

 

public with sharing class DESCloningController {

    public PageReference cloneDes() {
        return null;
    }

    public String termoptions { get; set; }
    public String clone { get; set; }
    public String yearoptions { get; set;}
    public List<District_Entitlement_Sheet__c> DESs{get;set;}
    public String SelectedValue1{get;set;}
    public String SelectedValue2{get;set;}
    public String SelectedValue3{get;set;}
    public District_Entitlement_Sheet__c SearchCriteria{get;set;}
    
    public DESCloningController ()
    {
        SearchCriteria = new District_Entitlement_Sheet__c();
    }
    public List<SelectOption> getItems() {
                List<SelectOption> yearoptions = new List<SelectOption>();
                    yearoptions.add(new SelectOption('2013','2013'));
                    yearoptions.add(new SelectOption('2014','2014'));
                    yearoptions.add(new SelectOption('2015','2015'));
        return yearoptions;
    }
    public List<SelectOption> getItems1() {
                List<SelectOption> termoptions = new List<SelectOption>();
                    termoptions.add(new SelectOption('Term 1','Term 1'));
                    termoptions.add(new SelectOption('Term 2','Term 2'));
                    termoptions.add(new SelectOption('Term 3','Term 3'));
        return termoptions;
    } 
    public void DES()    
    {
        DESs = new List<District_Entitlement_Sheet__c>();
        DESs = [SELECT Id,
                                     Country__c,
                                     District__c,
                                     Year__c,
                                     Term__c,
                                     Sheet_Type__c,
                                     Form_1_Bata_shoes__c,
                                     Form_1_Bed_Sheets__c,
                                     Form_1_Blanket__c,
                                     Form_1_Blouse__c,
                                     Form_1_Calculator__c,
                                     Form_1_Counter_Books__c,
                                     Form_1_Dress__c,
                                     Form_1_Exercise_Books__c,
                                     Form_1_Hardcover_books__c,
                                     Form_1_Maths_set__c,
                                     Form_1_Pens__c,
                                     Form_1_Pocket_money__c,
                                     Form_1_Safe_Term_Time_Accommodation__c,
                                     Form_1_Sanitary_Wear__c,
                                     Form_1_School_Bag__c,
                                     Form_1_Shoes__c,
                                     Form_1_Skirt__c,
                                     Form_1_Soap__c,
                                     Form_1_Socks__c,
                                     Form_1_Sugar__c,
                                     Form_1_Sweater__c,
                                     Form_1_Washing_powder__c,
                                     Form_2_Bata_shoes__c,
                                     Form_2_Bed_Sheets__c,
                                     Form_2_Blanket__c,
                                     Form_2_Blouse__c,
                                     Form_2_Calculator__c,
                                     Form_2_Counter_Books__c,
                                     Form_2_Dress__c,
                                     Form_2_Exercise_Books__c,
                                     Form_2_Hardcover_books__c,
                                     Form_2_Maths_set__c,
                                     Form_2_Pens__c,
                                     Form_2_Pocket_money__c,
                                     Form_2_Safe_Term_Time_Accommodation__c,
                                     Form_2_Sanitary_Wear__c,
                                     Form_2_School_Bag__c,
                                     Form_2_Shoes__c,
                                     Form_2_Skirt__c,
                                     Form_2_Soap__c,
                                     Form_2_Socks__c,
                                     Form_2_Sugar__c,
                                     Form_2_Sweater__c,
                                     Form_2_Washing_powder__c,
                                     Form_3_Bata_shoes__c,
                                     Form_3_Bed_Sheets__c,
                                     Form_3_Blanket__c,
                                     Form_3_Blouse__c,
                                     Form_3_Calculator__c,
                                     Form_3_Counter_Books__c,
                                     Form_3_Dress__c,
                                     Form_3_Exercise_Books__c,
                                     Form_3_Hardcover_books__c,
                                     Form_3_Maths_set__c,
                                     Form_3_Pens__c,
                                     Form_3_Pocket_money__c,
                                     Form_3_Safe_Term_Time_Accommodation__c,
                                     Form_3_Sanitary_Wear__c,
                                     Form_3_School_Bag__c,
                                     Form_3_Shoes__c,
                                     Form_3_Skirt__c,
                                     Form_3_Soap__c,
                                     Form_3_Socks__c,
                                     Form_3_Sugar__c,
                                     Form_3_Sweater__c,
                                     Form_3_Washing_powder__c,
                                     Form_4_Bata_shoes__c,
                                     Form_4_Bed_Sheets__c,
                                     Form_4_Blanket__c,
                                     Form_4_Blouse__c,
                                     Form_4_Calculator__c,
                                     Form_4_Counter_Books__c,
                                     Form_4_Dress__c,
                                     Form_4_Exercise_Books__c,
                                     Form_4_Hardcover_books__c,
                                     Form_4_Maths_set__c,
                                     Form_4_Pens__c,
                                     Form_4_Pocket_money__c,
                                     Form_4_Safe_Term_Time_Accommodation__c,
                                     Form_4_Sanitary_Wear__c,
                                     Form_4_School_Bag__c,
                                     Form_4_Shoes__c,
                                     Form_4_Skirt__c,
                                     Form_4_Soap__c,
                                     Form_4_Socks__c,
                                     Form_4_Sugar__c,
                                     Form_4_Sweater__c,
                                     Form_4_Washing_powder__c,
                                     Form_5_Blouse__c,
                                     Form_5_Counter_Books__c,
                                     Form_5_Dress__c,
                                     Form_5_Exercise_Books__c,
                                     Form_5_Safe_Term_Time_Accommodation__c,
                                     Form_5_Sanitary_Wear__c,
                                     Form_5_Shoes__c,
                                     Form_5_Skirt__c,
                                     Form_6_Blouse__c,
                                     Form_6_Counter_Books__c,
                                     Form_6_Dress__c,
                                     Form_6_Exercise_Books__c,
                                     Form_6_Safe_Term_Time_Accommodation__c,
                                     Form_6_Sanitary_Wear__c,
                                     Form_6_Shoes__c,
                                     Form_6_Skirt__c
                              FROM District_Entitlement_Sheet__c
                              WHERE Year__c =: SearchCriteria.Year__c
                              AND Term__c =: SearchCriteria.Term__c
                              AND Sheet_Type__c =: SearchCriteria.Sheet_Type__c];
         if(DESs.size() == 0)
         {
            Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No records to Display')); 
         }
        
      } 
}

Hope someone can help or just give me an example I've searched and can't find an example of something like this.

 

Cheers

Dan

Hey,

 

I currently have an excel formula that generates a random code based on the salesforce id.

 

i'm keen to move this into salesforce but can't find what formula would do the same.

 

this is the formula - imagine that A2 is the salesforce id.

 

=CODE(MID(A2,11,1))&"."&CODE(MID(A2,12,1))&"."&CODE(MID(A2,13,1))&"."&CODE(MID(A2,14,1))&"."&CODE(RIGHT(A3))

 

The mid bit works fine I just can't find what formula I can use for the CODE.

 

Any help welcomed.

 

dan

Hi All,

 

Trying to find a good example bit of Apex code that can do something like the following for me.

 

1. VF Page that when I load it will provide me with a couple of select (picklist)options that act as filters. (otherwise the list would be huge)

2. Once I complete these (picklist)options the page should refresh and provide me with a list of records that match this criteria.

3. At this point I should have a check box against each on that allows me to then clone the records.

4. The final step would be to update the Year & Term to map the new value.

 

i'm pretty sure that it's one VF page and a Apex Class that I need but would like an example of something similar to get me started. 

 

Cheers

Dan

 

 

 

Hi,

  I want to schedule belows class to run every 1hour I tried using the scheduler to run every day at a specific time but this is not working please suggest me how to make this work. 
 
list<String> toAddresses = new List<String>();
 list<Messaging.SingleEmailMessage> mailsToSend = new List<Messaging.SingleEmailMessage>();
 list<opportunity> opp = new list<opportunity>();
 String htmlBody; 

 opp = [select id,name,account.name,owner.name,owner.email, 
               Stage_Prior_Value__c,StageName,Close_Date_Prior_Value__c,
               closedate,f_ACV__c 
         from Opportunity 
         where Stage_Prior_Value__c = '2 - Contracts' or Stage_Prior_Value__c = '3rd Notice - Contracts' ];

for(Opportunity Op: Opp){
 htmlbody = '<html><body>';             
 htmlbody += '<p><strong> Owner Name : ' + op.owner.name + '</strong><br/></p>';
 htmlbody += '<p><strong> Account Name : ' + op.Account.name + '</strong><br/></p>';    
 htmlbody += '<p><strong> ACV Amount : ' + op.f_ACV__c + '</strong><br/></p>';    
 htmlbody += '<p><strong> Prior Forecast Category : ' + op.Stage_Prior_Value__c + '</strong><br/></p>';    
 htmlbody += '<p><strong> New Forecast Category : ' + op.stagename + '</strong><br/></p>';       
 htmlbody += '</body> </html>';   
          
      toAddresses.add('sudhir.narayanaswamy@gmail.com')    
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      mail.setToAddresses(toAddresses);      
      mail.setSenderDisplayName('Deals moving out of Commit forecast ');
      mail.setSubject('Deals moving out of Commit forecast ');
      mail.setUseSignature(false);            
      mail.setHtmlBody(htmlBody);
      mailsToSend.add(mail);
      Messaging.sendEmail(mailsToSend);    
    
}

Thanks
Sudhir
My requirements are to
  • Incorporate a VF Page into the Case Object where Users could upload a single image
  • Have that single image stored as an Attachment for that Case
  • Renaming that Attachment 'CasePhoto1.jpg'
  • Extract that Attachment's ID and insert it into a custom field named CasePhoto1ID__c
So far, I've figured out everything but the extraction of the Attachment's ID. Here's what I have so far. Can anybody help me add the last piece of the puzzle (extracting the Attachment's ID and inserting it into CasePhoto1ID__c.

Here's the Controller:
public with sharing class CasePhotoUploadController1 {

    Private Static FINAL String fixedFileName = 'CasePhoto1.jpg';

    public boolean displaying { get; set; }
    public Case pageCase;
    public Blob casePicFile { get; set; }
    public Id currentPicture { get; set; }
    
    /** Constructor, grab record, and check/load an existing photo */
    public CasePhotoUploadController1(ApexPages.StandardController controller) {
        pageCase = (Case)controller.getRecord();
        
        List<attachment> currentPictures = [SELECT Id FROM Attachment WHERE parentId = :pageCase.Id AND name = :fixedFileName LIMIT 1];
        if(currentPictures.size() != 0) {
            currentPicture = currentPictures.get(0).Id;
        }
        
        displaying = true;
    }

    /** toggle switches between the photo display and photo upload form */
    public void toggle() {
        displaying = !displaying;
    }
    
    /** saveFile clears any existing (secondary) Case picture, retrieves the data from the form, and saves it under the relevant filename*/
    Public Pagereference saveFile() {

        // first, we cannot have any conflicting files
        List<attachment> savedPicture = [SELECT Id, name, body FROM Attachment WHERE parentId = :pageCase.Id AND name = :fixedFileName];
        if(savedPicture.size() > 0) {
            delete savedPicture;
        }
       
        // Now, the new blob is saved
        Attachment a = new Attachment(parentId = pageCase.Id, name = fixedFileName, body = casePicFile);
        insert a;
        
        currentPicture = a.Id;
        
        displaying = true;
        return null;
    }
  }

VF Page
<apex:page standardController="Case" extensions="CasePhotoUploadController1" showHeader="false" standardStyleSheets="true" sidebar="false">

<apex:form id="contentForm">
<div style="height:170px;">
    <apex:pageBlock mode="edit">
    
        <apex:pageblocksection columns="1" rendered="{!displaying}">
            <apex:image height="150" value="{!URLFOR($Action.Attachment.Download, currentPicture)}" rendered="{!currentPicture != null}"/>
            <apex:outputPanel rendered="{!currentPicture == null}"><em>No picture currently available</em></apex:outputPanel>
        </apex:pageblocksection>
        
        <apex:pageblocksection columns="1" rendered="{! !displaying}">
            <p>Use the button to below to select a new file and then press "Save"</p>
            <apex:inputFile value="{!profilePicFile}" />
            <p>Or press Cancel to return.</p>
        </apex:pageBlockSection>
        
    </apex:pageBlock>
</div>
    <apex:commandButton value="Upload new photo" action="{!toggle}" rerender="contentForm" rendered="{!displaying && currentPicture!=null}"/>
    <apex:commandButton value="Upload photo" action="{!toggle}" rerender="contentForm" rendered="{!displaying && currentPicture==null}"/>
    <apex:commandButton value="Cancel" action="{!toggle}" rendered="{! !displaying}"/>
    <apex:commandButton value="Save" action="{!saveFile}" rendered="{! !displaying}"/>
</apex:form>
  
</apex:page>

Any help would be much appreciated!

Thanks,
Ben

 
Hi all can anyone point me in the right direction for URL passing of cross filters within reports?

i've followed this guide and can't get it to work - i can get salesforce to recognise the cross filter but my filters within don't work

http://www.verticalcoder.com/2014/06/03/url-hacking-cross-filter-reports/

so basically my problem is that this works for my custom object

ptable0=072C0000002ezuA&ocond0=w&rtable0=01IC0000000qeCG&rtablecol0=00NC0000006DEAg

but adding in my filter within this doesn't work

&sfpc0_0=00NC0000006DEDY&sfpn0_0=eq&sfpv0_0=Term+1

has anyone managed to get url hacking for cross filters working and if so how - or whats another way around it?

thanks
dan

 
i've confused myself

i have an object with 2 fields

Form Name (external reference and unique name that is stored within the form_id field within a different custom object)
ObjectName__c (formula field that based on name enter the correct custom object mycustomobject__c)
Salesforce_Record_Count__c (i want to put the number of records that match my search critera in here)

i then want to create a batch process that will do something like this:

global class UpdateMonitoringForms implements Database.Batchable<sObject>{

    string query;
    global Database.querylocator start(Database.BatchableContext BC){
      Query = 'Select ID,Form_Name__c,Salesforce_Record_Count__c From Monitoring_Form__c';
      return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monitoring_Form__c> scope){
      List<Monitoring_Form__c> lstmforms = new List<Monitoring_Form__c>();  
       for (Monitoring_Form__c mf:scope) {
        string object = mf.ObjectName__c;
        IF(mf.ObjectName__c!= 'DO NOT PROCESS'){
          mf.Salesforce_Record_Count__c = [select count() from object where Form_ID__c =:mf.Form_Name__c];
        }
        lstmforms.add(mf)
        }
        update lstmforms;       
    }

    global void finish(Database.BatchableContext BC){

    }
}

so basically my challenge is how can I build my select count to use potentially a different customobject__c each time it runs.

I plan to limit this batch to only updating 20 records at time.

any thoughts or betters ways of doing this, please do as for clarification.

dan


I am creating a trigger which creates a Target_Sale__c which links to a Target__c. Each User has a Target per month and the Sales represents the Won Opportunity which rolls up to the target. The problem is that I need to take OpportunitySplits into account and create  Target Sale for each Opportunity Split.

I wrote the below trigger and am not getting any errors in the Developer Console but it is not saving in the browser - Here is my trigger:

trigger LinkOpportunitytoUserTarget on Opportunity (before insert, after update, after delete) {
   
    SET<String> oppyear = new SET<String>();
    SET<String> oppmonth = new SET<String>();
   
    SET<ID> oids = new SET<ID>();
    SET<ID> osids = new SET<ID>();
    SET<ID> userids = new SET<ID>();
   
    LIST<Target_Sale__c> targetsalelistdelete = new LIST<Target_Sale__c>();
    LIST<Target_Sale__c> targetsalelistinsert = new LIST<Target_Sale__c>();
    MAP<String,Target__c> targetmap = new MAP<String,Target__c>();
       
    String omaplookup;
    String osmaplookup;
   
    if(Trigger.IsInsert || Trigger.IsUpdate){
        for(Opportunity o : Trigger.new){
            if(o.Probability==100){
                oppyear.add(string.Valueof(o.CloseDate.Year()));
                oids.add(o.Id);
                oppmonth.add(string.ValueOf(o.CloseDate.Month()));
            }
        }
       
        system.debug('oppyear: '+oppyear);
        system.debug('oids: '+oids);
        system.debug('oppmonth: '+oppmonth);
    
     //Query Opportunity Splits linked to Opportunity and assign user ids to set
    for(OpportunitySplit getos : [SELECT Id, OpportunityId, SplitAmount, SplitOwnerId
                                FROM OpportunitySplit
                                WHERE OpportunityId IN :oids]){
                                    if(Opportunity.Probability=100){
                                        osids.add(getos.Id);
                                        userids.add(getos.SplitOwnerId);
                                  }
                                }
       
      system.debug('userids: '+userids);
      system.debug('osids: '+osids);
     
    //Query Target Sales already linked to Opportunity for delete
    for(Target_Sale__c getts : [SELECT Id, Name, Amount__c, Opportunity_Reference__c, Opportunity_Split_Reference__c, Opportunity_Name__c FROM Target_Sale__c WHERE Opportunity_Split_Reference__c IN :osids]){
        targetsalelistdelete.add(getts);   
    }
       
        system.debug('targetsalelistdelete: '+targetsalelistdelete);
   
        if(!targetsalelistdelete.isEmpty()){
            delete targetsalelistdelete;
        }
     
    //Query Target records for users for Month and Date of Opportunity
    for(Target__c gett : [SELECT Id, Name, Target_Amount__c, Actual_Sales__c, OwnerId, Sales_Rep__r.Id, Year__c, Month__c
                        FROM Target__c
                        WHERE Sales_Rep__r.Id IN :userids
                        AND Year__c IN :oppyear
                        AND Month__c IN :oppmonth]){
                        //add Targets to Target Map
                        targetmap.put(gett.Sales_Rep__r.Id + '_' + gett.Year__c + '_' + gett.Month__c,gett);                     
                        }
       
    system.debug('targetmap: '+targetmap);

    for(OpportunitySplit oppsplits : [SELECT Id, OpportunityId, SplitAmount, SplitOwnerId
                                FROM OpportunitySplit
                                WHERE Id IN :osids]){
            osmaplookup = oppsplits.SplitOwnerId + '_' + string.Valueof(oppsplits.Opportunity.CloseDate.Year()) + '_' + string.Valueof(oppsplits.Opportunity.CloseDate.Month()); 
            system.debug('osmaplookup: '+osmaplookup);
                            if(targetmap.get(osmaplookup) != null){
                                            targetsalelistinsert.add(new Target_Sale__c(Target__c = targetmap.get(osmaplookup).Id,
                                                                    Opportunity_Reference__c = oppsplits.OpportunityId,
                                                                    Opportunity_Split_Reference__c = oppsplits.Id,
                                                                    Amount__c = oppsplits.SplitAmount,
                                                                    Opportunity_Name__c = oppsplits.OpportunityId.Name)); 
                                            }
        }
            
        system.debug('targetsalelistinsert: '+targetsalelistinsert);
        if(!targetsalelistinsert.isEmpty()){
            insert targetsalelistinsert;
        }
    }
   
    if(Trigger.IsDelete){
        for(Opportunity o : Trigger.old){
            if(o.Probability=100){
                oids.add(o.Id);
            }
        }
       
        system.debug('oids: '+oids);
       
        for(Target_Sale__c getts : [SELECT Id, Name, Amount__c, Opportunity_Reference__c, Opportunity_Split_Reference__c, Opportunity_Name__c FROM Target_Sale__c WHERE Opportunity_Reference__c IN :oids]){
            targetsalelistdelete.add(getts);   
        }
       
        system.debug('targetsalelistdelete: '+targetsalelistdelete);
        if(!targetsalelistdelete.isEmpty()){
            delete targetsalelistdelete;
        }
    }
}

Any help would be greatly appreciated as I just can't figure out what the error is refering to!
Hi All,

I've recenrtly started working with some batch apex and have generally found it pretty simple to deal with but have now hit a problem that I can't get round.

Setup:

One object Entitlement__c which I need to provide a button to force update records that match a criteria.
I've create a second object Entitlement_Updates__c which allows them to set the criteria Year__c, Term__c

I then have a custom VF page that based on their criteria tells them how many records match and if the number is greater than 0 they get a button to press that is supposed to invoke a batch apex - all of this I've managed to get working relatively easily.

my problem is that I am unable to pass my soql query from my apex class to my batch apex.

Apex Class: 

public with sharing class FPS_ManualIntervention {
    public FPS_Update__c FPS { get; set; }
     // Class Constructor
    public FPS_ManualIntervention(ApexPages.StandardController controller){
        FPS =  (FPS_Update__c)controller.getRecord();  
      }
    // button page for firing of apex batch class
    public PageReference updaterecords() {
        string fpyear = fps.year__c;
        string fpterm = fps.term__c;
        string fpcountry = fps.country__c;
        string fpstudenttype = fps.student_type__c;
        Database.executeBatch(new BatchEntitlementUpdate('SELECT ID, Year__c, Term__c, StudentType__c, Student__r.Country__c ' +
                ' FROM Entitlement__c ' +
                ' WHERE Year__c =:\'' + fpyear + '\'' +
                ' AND Term__c =:\'' + fpterm + '\'' +
                ' AND StudentType__c=:\'' + fpstudenttype + '\''+
                ' AND Country__c=:\'' + fpcountry + '\''), 10);
        PageReference redirect  = new PageReference('/apex/FPSManageRunning?id=' + fps.id);
        redirect.setRedirect(true);
        return redirect;
        return null;
    }
 }

the button on this page is then firing this batch apex:

global class BatchEntitlementUpdate implements Database.Batchable<sObject>{

   global final String Query;

   global BatchEntitlementUpdate(String q){
             Query=q;
   }
   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   }
    global void execute (Database.Batchablecontext BC, list<Entitlement__c> scope){
        List<Entitlement__c> lsttoupdate = new List<Entitlement__c>();
        for(Entitlement__c ent:scope){
            ent.BatchProcess__c = 10;
            lsttoupdate.add(ent);
        }
        update lsttoupdate;
    }
    global void finish(Database.Batchablecontext BC){
    }
}

i've been reading so many docs that i've kind of lost the plot on how this should or could look now so any guidance appreicated.

the code as it is brings back: First error: Only variable references are allowed in dynamic SOQL/SOSL.


Hi All,

I have a subquery statement and I'm trying to make sure that parent records don't display if they have no child records available.

Query:

List<Training_Module__c> trainingmod;
    public List<Training_Module__c> gettrainingmod() {
        if(trainingmod == null) {
            trainingmod = [SELECT id, Name, Introduction__c,
                (SELECT id, Name, Introduction__c
                    FROM Training_Lessons__r
                    WHERE (Applicable_Country__c includes (:empcountry) and Applicable_Teams__c includes (:empteam) and Status__c=:'Online'))
                FROM Training_Module__c
                WHERE Training_Course__c =:currentpage and Applicable_Country__c includes (:empcountry) and Applicable_Teams__c includes (:empteam) and Status__c=:'Online'];
            }
            return trainingmod;
        }

Now I am displaying this on a page in a repeat 

<apex:repeat var="tm" value="{!trainingmod}" rendered="{!trainingmod.size>0}">
        <table border="0" width="100%">
            <tr>
                <th>Module</th>
                <th>Introduction</th>
            </tr>
            <tr>
                <td width="15%"><apex:outputfield value="{!tm.Name}" /></td>            
                <td colspan="3">{!tm.Introduction__c}</td>           
            </tr>
            <tr>
                <th></th>
                <th>Lesson</th>
                <th>Introduction</th>
            </tr>
            <apex:repeat var="tmsg" value="{!tm.Training_Lessons__r}">
                <tr>
                    <td>&nbsp;</td>
                    <td width="15%"><apex:outputfield value="{!tmsg.Name}" /></td>
                    <td width="55%">{!tmsg.Introduction__c}</td>
                    <td><a href="/apex/TrainingLesson?id={!tmsg.id}"><button type="button">Take Lesson</button></a></td>
                </tr>
            </apex:repeat>

my query is where i have: rendered="{!trainingmod.size>0}" in my apex:repeat

how can i make it only display if training_lesson__r.size>0 i tried rendered="{trainingmod.training_lesson__r.size>0 but get an error

Error: Unknown property 'VisualforceArrayList.training_lesson__r'

any ideas do i have to do this in the apex?

any guidance appreciated.

dan
Hello,

We would like to have documents attached to a custom object record (Notes & Attachments) be sent with the approval request email once that record has entered the approval process.  Is there anyway to do this?

It would be nice if when setting up the approval process, admin could just click a button similar to 'include record documents with approval email request'; but seems that is not available?

Alternately, set up a second email alert with documents attached that follows the approval process and is triggered each time an approval step is marked as approved.  That then triggers email with documents attached to next approver in process.

Have spoken with Conga and created a button, but having difficulty figuring out how to include 'next approver' in query to populate email address in secondary email.

Help greatly appreciated.
Hello everyone,

I am getting the error below when trying to make changes to my test class in Sandbox. 
Has anyone seen this before. Do you know how to fix it.

Thanks
Deployment Error
Here is the error message: error: {faultcode:'soapenv:Client', faultstring:'Attribute "xmlns" bound to namespace "http://www.w3.org/2000/xmlns/" was already specified for element "query".',}
Hello,

I created 2 Classes (below) for testing purposes.  The first class creates an Account record, with 3 dummy user records that get populated into 3 custom user lookup fields on the Account.  The second class is a test class that is meant to cover a trigger that fires when the values for the users are changed on the Account.  Everything saves OK, but when I run the test, I get an error stating:

System.QueryException: List has no rows for assignment to SObject
Class.TestStatusAcctCreate.createAcct: line 6, column 1
Class.TestAccountPlan.testMyController1: line 9, column 1

Does anyone know why I would be getting this error?  Thanks.

public class TestStatusAcctCreate {

        // create and insert a new Accountrecord that has an arbitrary value for Type.
    public static Account createAcct(Integer i){ 

        Profile ProDir = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Delivery (Director)'];
               
            User Dir1 = new User(Alias = 'DirUser',Country='United States',Email='DirUser@testing.com',EmailEncodingKey='UTF-8', LastName='Testing1', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProDir.Id,TimeZoneSidKey='America/New_York', UserName='DirUser@testing.com');
        insert Dir1;

        Profile ProTeamMgr = [SELECT Id
                              FROM Profile
                              WHERE Name='Client Delivery Team Manager'];
               
            User TM1 = new User(Alias = 'TMUser',Country='United States',Email='TMUser@testing.com',EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProTeamMgr.Id,TimeZoneSidKey='America/New_York', UserName='TMUser@testing.com');
        insert TM1;

        Profile ProCSM = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Success Manager'];
               
            User CSM1 = new User(Alias = 'CSMUser',Country='United States',Email='CSMUser@testing.com',EmailEncodingKey='UTF-8', LastName='Testing3', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProCSM.Id,TimeZoneSidKey='America/New_York', UserName='CSMUser@testing.com');
        insert CSM1;


    Account acct = new Account();
            acct.Name = 'Test' + i;
            acct.Type= 'Employer';
            acct.Client_Advisor__c = CSM1.Id;
            acct.Industry_Manager__c = TM1.Id;
            acct.Market_Director__c = Dir1.Id;
            
        return acct;
        
    }
}




@Istest(SeeAllData=true)
public class TestAccountPlan {

public static testMethod void testMyController1() {    
       
    Account acct1 = TestGeneralAcctCreate.createAcct(0);
    insert acct1;

    Account acct2 = TestStatusAcctCreate.createAcct(0);
    insert acct2;

        Profile ProDir2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Delivery (Director)'];
               
            User Dir2 = new User(Alias = 'Dir2User',Country='United States',Email='Dir2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing1a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProDir2.Id,TimeZoneSidKey='America/New_York', UserName='Dir2User@testing.com');
        insert Dir2;

        Profile ProTeamMgr2 = [SELECT Id
                              FROM Profile
                              WHERE Name='Client Delivery Team Manager'];
               
            User TM2 = new User(Alias = 'TM2User',Country='United States',Email='TM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing2a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProTeamMgr2.Id,TimeZoneSidKey='America/New_York', UserName='TM2User@testing.com');
        insert TM2;

        Profile ProCSM2 = [SELECT Id
                          FROM Profile
                          WHERE Name='Client Success Manager'];
               
            User CSM2 = new User(Alias = 'CSM2User',Country='United States',Email='CSM2User@testing.com',EmailEncodingKey='UTF-8', LastName='Testing3a', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = ProCSM2.Id,TimeZoneSidKey='America/New_York', UserName='CSM2User@testing.com');
        insert CSM2;

        Account acct2a = [SELECT id,Market_Director__c,Industry_Manager__c,Client_Advisor__c
                          FROM Account
                          WHERE id =: acct2.Id];
               acct2a.Market_Director__c = Dir2.Id;
               acct2a.Industry_Manager__c = TM2.Id;
               acct2a.Client_Advisor__c = CSM2.Id;
        
    Account acct3 = TestGeneralAcctCreate.createAcct(0);
    insert acct3;

    Account acct4 = TestGeneralAcctCreate.createAcct(0);
    insert acct4;

    Account acct5 = TestGeneralAcctCreate.createAcct(0);
    insert acct5;

//    Account acct6 = TestStatusAcctCreate.createAcct(0);
//    insert acct6;

    Opportunity opp1 = TestOppCreate3.createOpp(acct1.Id);
    insert opp1;

    Contract_Summary__c contsumm1 = TestContractCreate.createContSumm(opp1.Id);
    insert contsumm1;
  
        Contract_Summary__c contSumm2 = [SELECT id
                                         FROM Contract_Summary__c
                                         WHERE id =: contSumm1.id];
  
    Client_Status_Scorecard__c cssc1 = TestStatusSCCreate.createCSSC1(acct1.Id);
    insert cssc1;
    
        Client_Status_Scorecard__c cssc1a = [SELECT id
                                           FROM Client_Status_Scorecard__c
                                           WHERE id =: cssc1.id];
    
    Client_Status_Scorecard__c cssc2 = TestStatusSCCreate.createCSSC2(acct2.Id);
    insert cssc2;
    
    Client_Status_Scorecard__c cssc3 = TestStatusSCCreate.createCSSC3(acct3.Id);
    insert cssc3;
    
    Client_Status_Scorecard__c cssc4 = TestStatusSCCreate.createCSSC4(acct4.Id);
    insert cssc4;
    
    Client_Status_Scorecard__c cssc5 = TestStatusSCCreate.createCSSC5(acct5.Id);
    insert cssc5;
    
//    Client_Status_Scorecard__c cssc6 = TestStatusSCCreate.createCSSC6(acct6.Id);
//    insert cssc6;
    
    Account_Plan__c plan1 = TestAcctPlanCreate.createAP1(acct1.Id);

    ApexPages.StandardController AcctPlan = new ApexPages.standardController(acct1);
    AcctPlanController APControl1 = new AcctPlanController(AcctPlan);
  //  APControl1.ap.add(plan1);
    APControl1.ap2 = plan1;
    APControl1.testsf();
    APControl1.save();
    
    Test.startTest();
    update acct1;
    update acct2;
    update acct2a;
    update acct3;
    update acct4;
    update acct5;
//    update acct6;
    update opp1;
    update contsumm1;
    delete contsumm2;
    update cssc1;
//    update cssc2;
    update cssc3;
    update cssc4;
    update cssc5;
//    update cssc6;
    delete cssc1a;
    Test.stopTest();
  
}

}



  • June 09, 2014
  • Like
  • 0
I am looking to make a "Personal Productiviy App" - As a developer who is in an acting sales/admin role, I use salesforce often. Mainly, I am assigned tasks specific to my department.

I am looking to grab my tasks, and the attributes of those tasks somehow. Then once complete update the corresponding information.

I have had a good look around - I really don't know where to start or what would be the best approch. Does anyone have any ideas?
How to created an email alert if total amount of opened cases reaches lets say 100 per day?

Hi ,
I am trying to show some notification for unread private message in a VF page of Community Site.
In standard chatter page it used to notify the number of unread mails side by Messages link.

I did some search regarding this but didn't get clear idea how to achieve this.
Please suggest some ideas how I can know that a user has some unread private messages or how I can show similar functionality as of standard chatter page in VF page.


Thanks
Arabinda