• Sean Tan
  • SMARTIE
  • 1729 Points
  • Member since 2013

  • Chatter
    Feed
  • 59
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 192
    Replies

Hi all,

I need a simple help !!

Data in 'Billing City' and 'Shipping City' field of 'Account' object contains line breaks.

eg.  345 Shoreline Park
     Mountain View, CA 94043
     USA

 I want a code to fetch data of these two fields and and format it as below

345 Shoreline Park, Mountain View, CA 94043, USA    (ie.  in a single line and Line breaks to be replaced with comma)

 Thanks in advance !

  • September 12, 2013
  • Like
  • 0

Hi,

 

I'm tryin to send a date field by email.

But my date is showing this MM/dd/yyyy.

 

And I am looking for this dd/MM/yyyy.

 

So I tried:

 

trigger Email_EventoFinalizado on Case (after insert, after update) {

List<Case> CaseMap = new List<Case>();
    for(Case c : Trigger.new){
        IF(c.motivo__c == 'Último evento'){
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
          String[] toAddresses = new String[]{};   
            toAddresses.add('everton.gomes@cp7.com.br');
          mail.setToAddresses(toAddresses);          

          mail.setSubject(''+c.subject+'');
            
            Datetime myDT = Datetime.now();
            String myDate = myDT.format('dd/MM/yyyy');
            
            mail.setHtmlBody('<p>Turma: '+c.PIT__c+' - '+c.Nome_da_turma__c+'</p><p>Evento: '+c.Nome_do_evento__c+'</p><p>Data&colon; '+myDT(c.Data_do_evento__c)+'</p><p>'+c.Description+'</p>');
 
          Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
        }               
    }
}

 Error: Method does not exist or incorret signature : myDT(Date)

 

Thanks !

Hello,

 

I’m using a class to dynamically update and display data from OpportunityLineItem.

 

I’ve got the data coming through fine; i now want to tweak the filer of the SOQL search to make sure the object is related to an actual customer. I’ve run my query through the editor and it tests fine but when i place it in the actual code i get the following error: line 29 expecting a semi-colon, found 'Waste'. 

 

Any help would be most appreciated !

 

Here is my code:

public with sharing class WasteSheetController{

    //The SOQL without the order and limit
    private String soql{get;set;}
    
    //The collection of Products
    public List<OpportunityLineItem> products {get;set;}
    
    //The current sort direction
    public String sortDir {
        get{if(sortDir == null){sortDir = 'asc';} return sortDir;}
        set;
    }
        
    //Sort the data by Opportunity
    public String sortField {
        get{if(sortField == null){sortField ='Opportunity.Name';} return sortField;}
        set;
    }
        
    // format the soql for display on the visualforce page
    public String debugSoql {
        get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 999'; }
        set;
    }

    // init the controller and display some sample data when the page loads
    public WasteSheetController() {
        soql = 'select Id, Opportunity.Name, PricebookEntry.Product2.Name, Delivered__c, Contact_Sent__c, Contract_Signed__c, Ordered__c, Order_Confirmed__c, Opportunity.Postcode__c from OpportunityLineitem WHERE Opportunity.StageName='Waste Sale!'AND Opportunity.Name !=null';
        runQuery();
    }
    
    // toggles the sorting of query from asc<-->desc
    public void toggleSort() {
        // simply toggle the direction
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
        // run the query again
        runQuery();
    }
    
    // runs the actual query
    public void runQuery() {
        try {
            products = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 999');
        } catch (Exception e) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Something has gone wrong this the search!'));
        }
    }
        
    // runs the search with parameters passed via Javascript
    public PageReference runSearch() {
        String Opportunity = Apexpages.currentPage().getParameters().get('Opportunity');
        
        soql = 'select Id, Opportunity.Name, PricebookEntry.Product2.Name, Delivered__c, Contact_Sent__c, Contract_Signed__c, Ordered__c, Order_Confirmed__c, Opportunity.Postcode__c from OpportunityLineitem WHERE Opportunity.StageName='Waste Sale!'AND Opportunity.Name !=null';
            if (!Opportunity.equals(''))
                soql += ' and Opportunity.Name LIKE \''+String.escapeSingleQuotes(Opportunity)+'%\'';

                
        //Run the query again
        runQuery();
        
        return null;
    }
}

 

 

Hi all,

 

On the opportunity I have to fields:

First Delivery (Date field)

Last Delivery (Date field)

 

On a custom object (Fleet__c) linked via Master-Detail relationship I have two fields:

Year of First Delivery (Number (4,0))

Year of Last Delivery (Number (4,0))

Both fields are set to read-only.

 

What I want to the code to do is on saving an Opportunity, take only the year from the 'First Delviery' and 'Last Delivery' field on the opportunity and put it into the two fields on all related Fleet__c entries.

 

Any help is very much appreciated! 

 

Many thanks,

Patrick

I know I am doing the wrong way as I hittin the governor limits.

But I am not getting how to change the code as it is behaving

 

What needs to be done

here is the code

 

public approval_dynamic_differential()
{
Dynamiclist = new list< Dynamic_territory_differential>();
UserTerritory ustr = [Select TerritoryId ,UserId From UserTerritory where UserId = :UserInfo.getUserId()];

for(Territory terr :[SELECT Id ,name FROM Territory where ParentTerritoryId =:ustr.TerritoryId])
{ 

UserTerritory user = [SELECT Id, UserId, TerritoryId FROM UserTerritory where TerritoryId = :terr.Id];
User userid = [select Id,Name From User Where id = :user.Userid];

TransferAcc = [select id,name,Active__c,Specialization_differential__c,Reason_For_Change__c ,Approval__c,Billingcity,Billingstate,Original_Calls_Total__c,Notes__c from Account WHERE OwnerId=:userid.id and Approval__c='Pending'and Submit__c=True];

UpdateAcc = [select id,name,Active__c,Approval__c,Specialization_differential__c,Billingcity,Billingstate ,(select id,name,Original_CallString__c,Updated_CallString__c,Call_String_Status__c from Call_Strings__r where Call_String_Status__c='Pending') from Account WHERE OwnerId=:userid.id and Approval__c!='Pending' and Submit__c=True];

d1= new Dynamic_territory_differential();
d1.TerritoryId = terr;
d1.userTerrid = user;
d1.username = userid;
d1.Accountslist = TransferAcc;
d1.UpdateAcclist = UpdateAcc ;
Dynamiclist.add(d1);
system.debug('size======='+d1.UpdateAcclist.size());

}

getdynamicdifferential();

}

 

Hi,

How would I write a try catch that needs to catch a custom exception that happens down stream from within a class method that I am calling?

 

For example, my called class would be something like this...

 

try {

  calledClass.mymethod;

catch ( ??THIS NEEDS TO TRAPPED THE CALLED CLASS CUSTOM EXCEPTION?? e) {

   ??HERE I WOULD LIKE A USER FRIENDLY MESSAGE??

catch (System.Exception e) {

   String FatalError = 'Whatever I want the user to see on the visualforce page';

   ApexPages.addmessage( new ApexPages.message(ApexPages.severity.FATAL, FatalError);

}

 

 

 

public  Calledclass {

   ...

   class CalledclassException extends Exception {}

   ...

   ...

   public myMethod {

      ...

      ...

      if ( some condition ) {

         throw new CallingClassException('ERROR IN CalledClass');

      }

   }

}

 

I have table where I am getting records from method called foo

 

Now I want to get only distinct values.

 

How to get that.

 

Below is my code where I am getting records

"

public list<footprint__c> getfoot()
{


foo=[select id,name ,Territory__c,User__c from footprint__c where AxtriaCallPlan__Account__c=:ApexPages.currentPage().getParameters().get('id') Order By User__c ];

return foo;
}

"

 

How to get that.

 

 

Is there a way to delete records with apex by passing only the id? I see that you can use the API by sending an ID[] array, but I'm not sure how to use that through Apex. 

 

This should explain what I'm attempting to do... 

public void deleteRecords() {
	list<Id> ids;
	// add an account
	ids.add('001____________');
	// add a contact
	ids.add('003____________');
	// add a custom object
	ids.add('a0Y____________');
	// delete them all
	delete(ids);
}

I have a strange thing happening here.

 

I have this working otherwise, however for one condition -

 

Whenever the Account_Division__c is null (i.e not entered in the system), this logic fails to even enter the Else loop thus giving me the Attempt to dereference a null object error.

 

Any ideas why ??  

 

 

List <Employee__C> empList = [SELECT ..........];

for(Employee__c emp : empList){
	        	
	system.debug('Check the vlaue of Branch Email: ' +emp.Branch__r.Branch_Email__c);
	system.debug('Check the Kelly Division: ' +emp.Account_Division__c);

if(emp.Account_Division__c.contains('DAO')) {
	            	
  emp.Email_Branch__c = CT_EmailFields__c.getInstance().Mailbox__c;
	            
} else if(!emp.Account_Division__c.contains('DAO') || emp.Account_Division__c==null){ 

  emp.Email_Branch__c = emp.Branch__r.Branch_Email__c;

}

}

 

  • June 03, 2013
  • Like
  • 0

Greetings!

 

I've been backwards and forwards through the forums here looking at the examples of solutions to "System.LimitException: Too many code statements: 200001" errors and have made a number of the suggested modifications (that I can figure out) to my code below.  I am easily able to update a handful of records, but as soon as I try to push 50 or more through the trigger I get the error.

 

I am swimming in the deep end and beyond my current comfort.  I would sincerely appreciate some input and guidance on how I can best address the issue I'm seeing!

 

The intent of this code is to align the OwnerId of all related Leads and Contacts when an Account either has a new Owner assigned, or when a check box is selected.  Stipulations - the Account and the Lead records must have North American Country values.

 

 

Thanks

 

 

 

trigger Account_ChangeOwner on Account (before update) {
//This trigger updates Lead and Contact Owners based on either a new Account Owner or a selected check box

	integer counter=0;
	Set<Id> AccountIds = new Set<Id>();
	For (Account Obj : trigger.new){

//Only applies to North American Accounts
		if (Obj.BillingCountry!=null && (
       			Obj.BillingCountry=='CA' || 
       			Obj.BillingCountry=='US' ||
       			Obj.BillingCountry=='Canada' ||
       			Obj.BillingCountry=='United States')  
       			)
       				{
       					if (Obj.OwnerId!=trigger.old[counter].OwnerId)
       					{
       						AccountIds.add(Obj.Id);
       					}
       					else if (Obj.Reset_Contact_Owners__c==true)
       					{
		       				AccountIds.add(Obj.Id);
       					}
       				}

       	counter++;
    }//end of loop 1
    
//Gather all relevant Leads and Conacts and add them to Lists
	list<Lead> Lead_list = [Select 		l.Id,
										l.Account_Record__c,
										l.OwnerId
									From Lead l
										where l.IsDeleted=false 
										and l.IsConverted=false 
										//Only applies to North American Leads
										and (l.Country!=null and (
							       			l.Country='CA' or 
							       			l.Country='US' or
							       			l.Country='Canada' or
							       			l.Country='United States'))
										and Account_Record__c IN :AccountIds]; 

	list<Contact> Contact_list = [Select 	c.Id,
											c.AccountId,
											c.OwnerId
									From Contact c
										where c.IsDeleted=false 
										and AccountId IN :AccountIds]; 

//Make the changes
	counter=0;
    For (Account Obj : trigger.new){
		if (Obj.OwnerId!=trigger.old[counter].OwnerId || Obj.Reset_Contact_Owners__c==true){

					//Review the Leads and Contacts for the Acounts and change the Owner;
		       		For (Lead MyLead : Lead_list){
		       			if (MyLead.Account_Record__c==Obj.Id){
		       				if (Obj.Named_Account__c==true){
				       				MyLead.OwnerId=Obj.OwnerId;								
		       				}
		       			}
       				}       			
       				{
		       		For (Contact MyContact : Contact_list){
		       			if (MyContact.AccountId==Obj.Id){
		       				MyContact.OwnerId=Obj.OwnerId;
		       			}
		       		}
       				}
       	}

		//Clear the Reset Contact Owners field
      	if (Obj.Reset_Contact_Owners__c==true){
			   Obj.Reset_Contact_Owners__c=false;
       	}
       	      	
       	counter++;
	}//end of loop 2 

//Process Leads		
	Lead[] LeadsToUpdate=new Lead[]{};
	For (Lead MyLead : Lead_list){
		LeadsToUpdate.add(MyLead);
		if (LeadsToUpdate.size()==5000){
			update LeadsToUpdate; 
			LeadsToUpdate.clear();
		}
	}
	if (LeadsToUpdate.size()>0){
		update LeadsToUpdate;
	}

//Process Contacts	
	Contact[] ContactsToUpdate=new Contact[]{};
	For (Contact MyContact : Contact_list){
		ContactsToUpdate.add(MyContact);
		if (ContactsToUpdate.size()==5000){
			update ContactsToUpdate; 
			ContactsToUpdate.clear();
		}
	}
	if (ContactsToUpdate.size()>0){
		update ContactsToUpdate;
	}
	
    
}//end of trigger

 

Hi. I'm just trying to do a simple trigger but I'm experiencing a lot of frustration with how to actually access reference fields. I'm just triggering the creation of an Event from a custom object insert. Basically, in the custom object Set_Up, there is a lookup field (Pre_Communication__r) that is tied to Users...I'd like that specific user to be assigned the event (i.e. not the current user, etc.). This is what I have:

 

trigger createEvent on laniangela__Set_Up__c (after insert) {
         
       for (laniangela__Set_Up__c suObj:Trigger.new){     
  
             Event evtobj = new Event();
             evtobj.Owner = suObj.Pre_Communication__r;
             evtobj.Subject = 'Pre Communication EVENT';
             evtobj.DurationInMinutes = 60;
             evtobj.StartDateTime = suObj.Pre_Communication_Date__c;
             insert(evtobj);
             
  }
}

 

This is clearly not working. This is the error I receive: Error: Compile Error: Illegal assignment from SOBJECT:User to SOBJECT:Name at line 7 column 14 I'm sure it's something ridiculously easy but I'd really love a pointer here. THANK YOU

Hello!

I need to make a HTTP request to trigger.

But SFDC disallowed it.

How can I get out of this situation?

My code:

            String MailBody = obj.co_coname__c + '\\n\\n' + obj.CreatedDate + '\\n' + ' FAO ' +
            obj.Account.FirstName + ' ' + obj.Account.LastName + '\\n\\n' +
            'Reservation Number ' + obj.co_coname__c + '.\\n\\n' +
            'Your booking has now been confirmed.\\n\\n Please note: All hire bookings are subject to our hire terms and conditions which can be read here:\\n\\n' + obj.co_legal__c +
            '\\n\\n On completion of your hire, post hire charges may apply - a Post Hire Charges Schedule is available to read here:\\n\\n' + obj.co_surcharges__c +
            '\\n\\n Please review your booking details and complete the Cardholder Authorisation Form using the Docusign link below.\\n\\n By using Docusign, you can electronically sign and complete this document.\\n\\n (After you complete the form, all parties will receive a final PDF copy by email)\\n\\n';
            String Body = '{\n  \"emailSubject\": \"' + 'Booking Details ' + obj.Name + '",\n  \"emailBlurb\": \"'+ MailBody +'\",\n  \"templateId\": \"49131602-40EB-4548-AC8E-DE16DC9BE450\",\n  \"templateRoles\": [\n    {\n      \"roleName\": \"Signer 1\",\n      \"name\": \"'+ obj.Account.FirstName + ' ' + obj.Account.LastName +'\",\n      \"email\": \"'+ obj.Hirer_Email__c +'\"\n    }\n  ],\n  \"status\": \"sent\"\n}';    
            HttpRequest req = new HttpRequest();
            req.setEndpoint('https://demo.docusign.net/restapi/v2/accounts/279584/envelopes');
            req.setMethod('POST');
            String    authenticateStr =  '{\"Username\":\"soloho@rogers.com\",\"Password\":\"docu777\",\"IntegratorKey\":\"WEBS-3d5dc187-4870-4a52-9276-3458da82699b\"}';
            req.setHeader('X-DocuSign-Authentication', authenticateStr);
             req.setHeader('Content-Type', 'application/json');     
             req.setHeader('Content-Length', String.valueOf(Body.length()));
             req.setHeader('Accept', 'application/json');   
             Http http = new Http();
             HTTPResponse res = http.send(req);
             Result = res.getBody();

 

Is there a julian date function in APEX,

 

For example today [May 28 2013] has the julian date 2456441

 

Thanks

 

 

I have a trigger question.

 

I have a custom object named employee with a lookup field to the user record called Salesforce_user__c

 

I have another custom object called DD master list in which there is a field called Account_Manager__c that is a lookup to employee object.

 

 

Mt requirement is to populate the Account manager Salesforce User id in the new AM__c field. Below is the trigger i wrote(that does not work at all), if someone can help me with the test class and refinining the trigger I would be very grateful to you.

Please help

trigger SetDDmasterFields on DD_master_list__c (before insert, before update) {
    Map<Id,User> userMap = new Map<Id,User>();
    
    for (dd_master_list__c dd : Trigger.new) {
        userMap.put(dd.account_manager__r.Salesforce_User__c, null);
    }
    userMap.remove(null);
    
    if (!userMap.keyset().isEmpty()) {
        for (User u : [SELECT Id FROM User WHERE Id IN :userMap.keyset()]) {
            userMap.put(u.Id,u);
        }
        
        for (dd_master_list__c dd : Trigger.new) {
            if (userMap.get(dd.account_manager__r.Salesforce_User__c) != null) {
              dd.AM__c = userMap.get(dd.account_manager__r.Salesforce_User__c).Id;
          }
        }
    }
}

 

IN SOQL can't we compare Account.RecordType.Name to the contents of a set ?

 

In the code below if i add Account.RecordType.Name in :recordTypeSet  in the Where clause, the query returns 0 rows.

 

Is it a wrong way to check if the Account Recrd Type Name exists in a set?

 

Please advice? Thanks in advance.

 

Set<ID> recordTypeSet = new set<ID>();

List<RecordType> rtList = [Select Id, SobjectType, Name From RecordType  Where SobjectType in ('Lead', 'Account') and Name in ('Supplier Record Type', 'Temp Record Type', 'Supplier Registration', 'Temp Registration')];

system.debug('rtlist size ' +rtlist.size());

for(RecordType rt : rtList){
  recordTypeSet.add(rt.Id);
}

system.debug('record type set ' +recordTypeSet);

public Map<String, String> holdingMap = new Map<String, String>();

holdingMap.put('rova@acme.com','USA');
holdingMap.put('samp@axis.com','USA');


List<Contact> contactUser = [Select Id, Account.Id, Account.Name, Account.CreatedDate, Account.RecordType.Name,Name, Email From Contact WHERE Account.RecordType.Name in :recordTypeSet AND Email in :holdingMap.keySet()];

system.debug('SIZZZZZZZZ ' +contactUser.size());

for(Contact c : contactUser){
system.debug('Record Type ' +c.Account.RecordType.Name);
}

 

 

 

 

 

  • May 24, 2013
  • Like
  • 0

I tried all the possible but couldnt find the right way..!!

 

I know the reason why I am getting "System.LimitException: Too many DML statements: 151". Its because Iam updating inside for Loop.

 

I I tried to remove from inside for loop But the updation is not happening.

 

 

 " 

public void saveme()
{
System.debug('In Save Me Method===');
try
{
Account updatedAcc;
String__c String;

List<Account> updatedAccList = new List<Account>();
List<String__c> updatedStringList = new List<String__c>();

System.debug('Records in Call plan === '+ListWrapper.size());


for(Wrapper wrapObj:ListWrapper)
{
updatedAcc = new Account();
updatedAcc = wrapObj.acc;
updatedStringList = wrapObj.acc.Strings__r;
System.debug('String === '+updatedStringList);
updatedAccList.add(updatedAcc);
update updatedStringList;

}

update updatedAccList;
}
catch(Exception e)
{
System.debug('Exception in Saving records == '+e.getMessage());
}

}

 

 "

Please Help me in updating the record and Not to get governor limit error..

Hello,

 

I require to create a private aes128 key, store the key in my org and use this key for encrypting and decrypting values. I've run into the following challenges though and have been a bit stumped by them.

 

- If I create a secret key using 

 

Blob cryptoKey = Crypto.generateAesKey(128);

 

If I use the following to get the key I get an "BLOB is not a valid UTF-8 string"  error.

 

String cryptoString = cryptoKey.toString();
System.debug('cryptoString= ' + cryptoString);

 

If I instead convert my created key to a hex value and use it in a encryptWithManagedIV( function I get the following error

 

"Invalid private key. Must be 16 bytes."

 

String hexRep = EncodingUtil.convertToHex(cryptoKey);
System.debug('hexRep=' + hexRep);
Crypto.encryptWithManagedIV('AES128', Blob.valueOf(hexRep), Blob.valueOf('just4testing'));

 

However using the generated crypto key directly in encryptwithManagedIV works fine

 

Blob encryptedData = Crypto.encryptWithManagedIV('AES128', Crypto.generateAesKey(128), Blob.valueOf('just4testing'));

 

 

As I wish to store my secret key generated by Crypto.generateAesKey(128) , as the hex represenation of it won';t work I guess I would need to store the BLOB in a field in my org.  This seems a bit unusual to me however can it even be done?

Can a BLOB be stored in a custom field?  If not does anyone know why I get an error with my HEX represenation of the secretkey above?

 

Thanks in advance for any help on this.

I have been trying to use pagreferences but I am getting null values in the debug. I'm guessing it's because there is no id before the record is actually saved. I have put pagereferences before and after the insert. 

 

The whole reason I am trying to do it is because I would like to re-direct the user back to the Saved record in viewing state (not edit) after hitting saved. I'll be able to do it if I can just get the record id of the new record.

 

Anybody know how to do this ? 

 

Thank you very much.

Hello,

 

I found a controller that will clone all fields for an object. I am using this controller to help me clone and opp if specific requirements are met. (StageName = '09-Win' and type = 'Reseller / Partner Registration'). The works fine if there is an opp that meets the requirements but if I try to change that op (or update any op that does not meet the requirements) I get the error:

Error:Apex trigger partnerOppClone caused an unexpected exception, contact your administrator: partnerOppClone: execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.partnerOppClone: line 2, column 1

 

I understand that it is telling me that since it does not meet the requirements it had no rows - I am just stumped at how to go about fixing it.

 

Thanks in advance.

 

 

 

 

trigger partnerOppClone on Opportunity (after update) {
Opportunity originalOpp = [select Id from Opportunity where 
                                StageName = '09-Win' and type = 'Reseller / Partner Registration'];

    sObject originalSObject = (sObject) originalOpp;

        List<sObject> originalSObjects = new List<sObject>{originalSObject};
      
            List<sObject> clonedSObjects = SObjectAllFieldCloner.cloneObjects(
                                      originalSobjects,
                                      originalSobject.getsObjectType());
                                     
    Opportunity clonedOpp = (Opportunity)clonedSObjects.get(0);
  clonedOpp.StageName='training';
if (clonedOpp != null)
insert clonedOpp;
}

 

Here is the trigger I'd like to create:

 

I have an Opportunity Product with a Actual Impressions field. I use the Quantity to forecast the likely impressions; however, at the end of each month, I go back and populate Actual Impressions. When I change Actual Impressions, I'd like to launch a trigger that update the Quantity field to the value of the Actual Impressions field. 

 

Any help would be appreciated!

  

My code so far:

 

trigger updateQuantity on OpportunityLineItem (after update) {

for (OpportunityLineItem newQuantity : Trigger.new) {
    OpportunityLineItem oldQuantity = Trigger.oldMap.get(newQuantity.Id);
    if (oldQuantity.Actual_Impressions__c != newQuantity.Actual_Impressions__c) {
        // this is where I don't know how to update a given field
    }
}

}

Hey,

 

This is more of a nitty gritty type question but a question that has come up nonetheless.

 

If I have a formula field that is doing a cross object join, will this perform faster than a join in a raw SOQL statement when retrieving the information (not filtering)? For example:

 

Contact has a lookup to Account

Formula field on Contact called Account_Name__c

 

If I query something like this:

 

Contact[] contactList =  [ SELECT Account_Name__c FROM Contact ];

 

 

vs

 

Contact[] contactList =  [ SELECT Account.Name FROM Contact ];

Would the first query be faster than the second?  As far as I know, formula fields are always evaluated at point in time that the query is run and therefore should perform roughly the same. I am however being told otherwise and that a formula field will be more performant. Am I missing something here?

 

Hi all,

I need a simple help !!

Data in 'Billing City' and 'Shipping City' field of 'Account' object contains line breaks.

eg.  345 Shoreline Park
     Mountain View, CA 94043
     USA

 I want a code to fetch data of these two fields and and format it as below

345 Shoreline Park, Mountain View, CA 94043, USA    (ie.  in a single line and Line breaks to be replaced with comma)

 Thanks in advance !

  • September 12, 2013
  • Like
  • 0

I have created one wrapper class with sObject and index for sObject and am getting and setting list of wrapper to show on VF page. On VF page im showing some fields from that sObject and provided one button to clone that record so that cloned record  will be shown on next row. In the controller if i assign values directly from wrapper (i.e. new wrapper instance = wrapper instance to be clone) its getting cloned and displayed on VF but while saving its giving me error as "id" of sObject is also get clonned. If i try to get field values one by one from wrapper its giving me null values. (eg new wrapper.sObject.field = wrapperToBeCloned.sObject.field), sObject from the wrapper to be cloned is giving null values. How to solve this problem ?

 

Here are two possibilities as below when i clicked on clone button in vf page

 

1.  JobSuite__job__c obj = new JobSUite__Job__c();
     obj.Name = '';
     obj.JobSuite__Job_Description__c = wrapJob.objJob.JobSuite__Job_Description__c;
     obj.JobSuite__Dummy_Picklist_2__c = wrapJob.objJob.JobSuite__Dummy_Picklist_2__c;
     jbw.objJob = obj;
     wrapper.add(jbw)

If i use above code the record is assigned by blank values.

if i print wrapJob.objJob, it is displaying null in system.debug.

 

But when i used below code record is getting cloned and displayed in vf page 

 

 

    here am copying record from previous wrapper record
     jbw.objJob = wrapJob.objJob;
     wrapper.add(jbw)

 

 If i use above code the record is copied but while saving it is throwing exception because of same record ID.

 

Hi,

 

I'm tryin to send a date field by email.

But my date is showing this MM/dd/yyyy.

 

And I am looking for this dd/MM/yyyy.

 

So I tried:

 

trigger Email_EventoFinalizado on Case (after insert, after update) {

List<Case> CaseMap = new List<Case>();
    for(Case c : Trigger.new){
        IF(c.motivo__c == 'Último evento'){
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
          String[] toAddresses = new String[]{};   
            toAddresses.add('everton.gomes@cp7.com.br');
          mail.setToAddresses(toAddresses);          

          mail.setSubject(''+c.subject+'');
            
            Datetime myDT = Datetime.now();
            String myDate = myDT.format('dd/MM/yyyy');
            
            mail.setHtmlBody('<p>Turma: '+c.PIT__c+' - '+c.Nome_da_turma__c+'</p><p>Evento: '+c.Nome_do_evento__c+'</p><p>Data&colon; '+myDT(c.Data_do_evento__c)+'</p><p>'+c.Description+'</p>');
 
          Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
        }               
    }
}

 Error: Method does not exist or incorret signature : myDT(Date)

 

Thanks !

Hello,

 

I’m using a class to dynamically update and display data from OpportunityLineItem.

 

I’ve got the data coming through fine; i now want to tweak the filer of the SOQL search to make sure the object is related to an actual customer. I’ve run my query through the editor and it tests fine but when i place it in the actual code i get the following error: line 29 expecting a semi-colon, found 'Waste'. 

 

Any help would be most appreciated !

 

Here is my code:

public with sharing class WasteSheetController{

    //The SOQL without the order and limit
    private String soql{get;set;}
    
    //The collection of Products
    public List<OpportunityLineItem> products {get;set;}
    
    //The current sort direction
    public String sortDir {
        get{if(sortDir == null){sortDir = 'asc';} return sortDir;}
        set;
    }
        
    //Sort the data by Opportunity
    public String sortField {
        get{if(sortField == null){sortField ='Opportunity.Name';} return sortField;}
        set;
    }
        
    // format the soql for display on the visualforce page
    public String debugSoql {
        get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 999'; }
        set;
    }

    // init the controller and display some sample data when the page loads
    public WasteSheetController() {
        soql = 'select Id, Opportunity.Name, PricebookEntry.Product2.Name, Delivered__c, Contact_Sent__c, Contract_Signed__c, Ordered__c, Order_Confirmed__c, Opportunity.Postcode__c from OpportunityLineitem WHERE Opportunity.StageName='Waste Sale!'AND Opportunity.Name !=null';
        runQuery();
    }
    
    // toggles the sorting of query from asc<-->desc
    public void toggleSort() {
        // simply toggle the direction
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
        // run the query again
        runQuery();
    }
    
    // runs the actual query
    public void runQuery() {
        try {
            products = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 999');
        } catch (Exception e) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Something has gone wrong this the search!'));
        }
    }
        
    // runs the search with parameters passed via Javascript
    public PageReference runSearch() {
        String Opportunity = Apexpages.currentPage().getParameters().get('Opportunity');
        
        soql = 'select Id, Opportunity.Name, PricebookEntry.Product2.Name, Delivered__c, Contact_Sent__c, Contract_Signed__c, Ordered__c, Order_Confirmed__c, Opportunity.Postcode__c from OpportunityLineitem WHERE Opportunity.StageName='Waste Sale!'AND Opportunity.Name !=null';
            if (!Opportunity.equals(''))
                soql += ' and Opportunity.Name LIKE \''+String.escapeSingleQuotes(Opportunity)+'%\'';

                
        //Run the query again
        runQuery();
        
        return null;
    }
}

 

 

Hi all,

 

On the opportunity I have to fields:

First Delivery (Date field)

Last Delivery (Date field)

 

On a custom object (Fleet__c) linked via Master-Detail relationship I have two fields:

Year of First Delivery (Number (4,0))

Year of Last Delivery (Number (4,0))

Both fields are set to read-only.

 

What I want to the code to do is on saving an Opportunity, take only the year from the 'First Delviery' and 'Last Delivery' field on the opportunity and put it into the two fields on all related Fleet__c entries.

 

Any help is very much appreciated! 

 

Many thanks,

Patrick

Hey,

 

This is more of a nitty gritty type question but a question that has come up nonetheless.

 

If I have a formula field that is doing a cross object join, will this perform faster than a join in a raw SOQL statement when retrieving the information (not filtering)? For example:

 

Contact has a lookup to Account

Formula field on Contact called Account_Name__c

 

If I query something like this:

 

Contact[] contactList =  [ SELECT Account_Name__c FROM Contact ];

 

 

vs

 

Contact[] contactList =  [ SELECT Account.Name FROM Contact ];

Would the first query be faster than the second?  As far as I know, formula fields are always evaluated at point in time that the query is run and therefore should perform roughly the same. I am however being told otherwise and that a formula field will be more performant. Am I missing something here?

 

Hi All,

I am writting a trigger in which I am using:

Testpro__c.AllowableLimit__c = Testpro__c.AllowableLimit__c-i;

Where i is an integer, with value=1 where as AllowableLimit__c is a field of number type and have default value of 10,

When in my trigger I am trying to save this line- I am getting error:

Error: Compile Error: Arithmetic expressions must use numeric arguments at line 12 column 32

My full trigger code is:
trigger testpatpro on Testpatient__c (before insert, before update, after insert) {
Integer i;
i=1;
for ( Testpatient__c T : Trigger.New)
{

if(Testpatient__c.Testpro__c!= Null)

{


Testpro__c.AllowableLimit__c = Testpro__c.AllowableLimit__c -i ;
System.debug('Test');
}
}
}

where Testpatient__c and Testpro__c object have look up relationship.

I know its due to mismatch of Datatype, any idea how I can rectify it (at line# 12)

Thanks

  • July 08, 2013
  • Like
  • 0

I know I am doing the wrong way as I hittin the governor limits.

But I am not getting how to change the code as it is behaving

 

What needs to be done

here is the code

 

public approval_dynamic_differential()
{
Dynamiclist = new list< Dynamic_territory_differential>();
UserTerritory ustr = [Select TerritoryId ,UserId From UserTerritory where UserId = :UserInfo.getUserId()];

for(Territory terr :[SELECT Id ,name FROM Territory where ParentTerritoryId =:ustr.TerritoryId])
{ 

UserTerritory user = [SELECT Id, UserId, TerritoryId FROM UserTerritory where TerritoryId = :terr.Id];
User userid = [select Id,Name From User Where id = :user.Userid];

TransferAcc = [select id,name,Active__c,Specialization_differential__c,Reason_For_Change__c ,Approval__c,Billingcity,Billingstate,Original_Calls_Total__c,Notes__c from Account WHERE OwnerId=:userid.id and Approval__c='Pending'and Submit__c=True];

UpdateAcc = [select id,name,Active__c,Approval__c,Specialization_differential__c,Billingcity,Billingstate ,(select id,name,Original_CallString__c,Updated_CallString__c,Call_String_Status__c from Call_Strings__r where Call_String_Status__c='Pending') from Account WHERE OwnerId=:userid.id and Approval__c!='Pending' and Submit__c=True];

d1= new Dynamic_territory_differential();
d1.TerritoryId = terr;
d1.userTerrid = user;
d1.username = userid;
d1.Accountslist = TransferAcc;
d1.UpdateAcclist = UpdateAcc ;
Dynamiclist.add(d1);
system.debug('size======='+d1.UpdateAcclist.size());

}

getdynamicdifferential();

}

 

I'm trying to write a test class, but I keep getting this error message.  Here's my code:

@isTest
public class Test_AttachPRTOPOExtension_Final{
    static testmethod void Test_Attachment_process() {
        SFDC_Purchase_Order__c myOrder = new SFDC_Purchase_Order__c();
        List<SFDC_Purchase_Requisition__c> RequestsToUpdate = new List<SFDC_Purchase_Requisition__c>();
        List<SFDC_Purchase_Items__c> ItemsToUpdate = new List<SFDC_Purchase_Items__c>();
        //Instatiate Controllers
        
        ApexPages.StandardController con = new ApexPages.StandardController(myOrder);
        AttachPRTOPOExtension ext = new AttachPRTOPOExtension(con);
          
        // create items
        List<SFDC_Purchase_Items__c> newItems= new List<SFDC_Purchase_Items__c>();
        for(integer i=0;i<100;i++){
            SFDC_Purchase_Items__c thisitem = new SFDC_Purchase_Items__c(name ='item '+ i);
            newItems.add(thisItem);
        }	//end for
        if(newItems.size() != 100){
            system.debug('newItems <> 100'+ newItems.size());
                } else {		//end if
        system.assertEquals(newItems.size(),100);
                }		// end else
        try {
            Database.SaveResult[] sriList = database.insert(newItems);
            for (Database.SaveResult sri : sriList) {
    			if (sri.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted item. Item ID: ' + sri.getId());
    } else {
        // Operation failed, so get all errors                
        for(Database.Error err : sri.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Item fields that affected this error: ' + err.getFields());
        }		// end inner for
    }			// end else
}				// 3ne outer for
        } catch (DMLEXCEPTION e){
            system.debug('insertItems failed: ' + e);
                         }	//end catch
		List<SFDC_Purchase_Order__c> newOrders = new List<SFDC_Purchase_Order__c>();
        date newDate= date.today();
        ID myPurchaser = [select id from User where  has_purchasing_authority__c = true Limit 1] ;
        ID myApprover = [select id from User where (has_approval_authority__c = true) and (has_purchasing_authority__c = false) Limit 1] ;
        List<SFDC_Purchase_Requisition__c> newReqs= new List<SFDC_Purchase_Requisition__c>();
       
        for(integer i=0;i<100;i++){
            SFDC_Purchase_Requisition__c thisReq = new SFDC_Purchase_Requisition__c(status__c = 'Sent to Purchaser',Department__c = 'Dev CR',Quantity__c = i,
                Item_requested__c = newItems[i].id, Approver__c = myApprover, Purchaser__c = myPurchaser); 
            newReqs.add(thisReq);
        }
        if(newReqs.size() != 100){
            system.debug('newIReqs <> 100'+ newReqs.size());
                } else {
        system.assertEquals(newReqs.size(),100);
                }
        Set<string> ReqSet = new Set<string>();
           try {
            Database.SaveResult[] srrList = database.insert(newReqs);
            for (Database.SaveResult srr : srrList) {
    if (srr.isSuccess()) {
        ReqSet.add(srr.getId());
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted Requisition. Requisition ID: ' + srr.getId());
    } else {
        // Operation failed, so get all errors                
        for(Database.Error err1 : srr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Requisition fields that affected this error: ' + err.getFields());
        }		//end inner for
    }		//end else
}			// end  outer for
        } catch (DMLEXCEPTION e){
            system.debug('insertReqs failed: ' + e);
        }
         List<SFDC_Purchase_Requisition__c> AllReqs = new List<SFDC_Purchase_Requisition__c>(AttachPRTOPOExtension.m_requestQuery);               }

        // create Orders

        

    for(integer o=0;o < 20; o++){
            SFDC_Purchase_Order__c anOrder = new SFDC_Purchase_Order__c(PO_notes__c = 'note number '+ o, Ship_To_Location__c= 'Cedar Rapids Office',
                                                                        Category = 'Dev CR', Expedite= true,
                                                                        PO_Date__c = newDate);
            newOrders.add(anOrder);
        }
    Test.startTest();
    	Set<string> OrderSet = new Set<string>();
        integer placeInList = 0;
        for(myOrder : newOrders){
            OrderSet.add(myOrder.id);
            myOrder = (SFDC_PurchaseOrder__c)myOrder;
            holdPage = SavePO();
            if(holdPage.URLfor = AttachPRTOPOExtension.m_DetailPage.urlFor){
                AssertNotEquals(AttachPRTOPOExtension.m_currentID, null);}
                AssertNotEquals(AttachPRTOPOExtension.m_resultList.size(), 0);
                for(AttachPRTOPOExtension.tempPR myReq : AttachPRTOPOExtension.m_resultList){
                    myReq = (AttachPRTOPOExtension.tempPR)myReq;
                    for(x=PlaceInList : x<PlaceInList+5 :x++){
                        myReq.selected = true;
                    }
                    PlaceInList++; 
                    AttachPRTOPOExtension.processSelected();
                    AssertEquals(AttachPRTOPOExtension.m_resultList.size(),5);
                    holdPage=AttachPRTOPOExtension.FinalizePO();
                    AssertEquals(ApexPage.currentPage().getURL(),AttachPRTOPOExtension.m_DetailPageROURL + AttachPRTOPOExtension.m_currentId)
                        }  //end inner for
						
                }  //end outer for
            Test.stoptest();
    List<SFDC_Purchase_Order__c> checkPOs = new List<SFDC_Purchase_Order__c>([select id,name,PO_Notes__c,
                                                                    PO_Date__c,Category__c, numRequisitions__c,
                                                                    Total_Price__c, Status__c,Ship_To_Location__c,
                                                                    Expedite__c, Finalized__c from
                                                                    Purchase_Order__c where id in OrderSet];
                                                                             for(SFDC_Purchase_Order__c myOrder : checkPOs){
                                                                                 AssertEquals(Status__c,'Placed');
                                                                                 AssertEquals(Finalized__c,'Placed');
                                                                                 AssertEquals(numRequisitions, 5);
                                                                                 AssertEquals(Expedite, false);
                                                                             }
    List<SFDC_Purchase_Requisitions__c> checkPRs= new List<SFDC_Purchase_Requisitions__c>([select Department__c,
                                                                                            Status__c,Approver__c,
                                                                                            Purchaser__c, Purchase_Order__c,
                                                                                            Quantity__c,Price_per_Unit__c,
                                                                                            Expedite__c,Editable__c,Finalized__c,
                                                                                            Item_Requested__c from SFDC_Purchase_Requisitions__c 
                                                                                            where id in ReqSet Order by Purchase_Order__c Limit 100]);
                                                                             for(SFDC_Purchase_Requisitions__c myReq : checkPRs){
                                                                                 AssertEquals(Status__c,'Sent to Purchaser');
                                                                                 AssertEquals(Finalize__c,true);
                                                                                 AssertEquals(Editable__c, false);
                                                                                 AssertEquals(Expedite__c, false);
                                                                                 AssertNotEquals(Price_per_unit__c, 0);
                                                                                 AssertNotEquals(Quantity__c, 0);
                                                                             }		//end for
																			 }		// end Class

 I've scoured the code to find the (apparent) unmatched curly bracket, with no joy, so I'm probably doing something else wrong which is messing with the compiler.  If I put a right curly bracket on line 82, as would be obvious, it matches up with the bracket at the start of the class, the message becomes "unexpected token: for" which makes sense as it would be appearing after the bracket ending the class definition.  Can anyone offer suggestions about what is wrong and how to fix it?

Thanks in advance.

Hi,

How would I write a try catch that needs to catch a custom exception that happens down stream from within a class method that I am calling?

 

For example, my called class would be something like this...

 

try {

  calledClass.mymethod;

catch ( ??THIS NEEDS TO TRAPPED THE CALLED CLASS CUSTOM EXCEPTION?? e) {

   ??HERE I WOULD LIKE A USER FRIENDLY MESSAGE??

catch (System.Exception e) {

   String FatalError = 'Whatever I want the user to see on the visualforce page';

   ApexPages.addmessage( new ApexPages.message(ApexPages.severity.FATAL, FatalError);

}

 

 

 

public  Calledclass {

   ...

   class CalledclassException extends Exception {}

   ...

   ...

   public myMethod {

      ...

      ...

      if ( some condition ) {

         throw new CallingClassException('ERROR IN CalledClass');

      }

   }

}

 

I have one date field tht is returning date as '2013-06-03'. I want to subtract this date with todays date.

 

Whn am trying for today's date using Date d = Date.today(); It is returing time also along with date. I want only date part. How to retrive only date part

 

1) datetime myDateTime = datetime.now();
Date d = myDateTime.date();

 

 

2) date tt = system.today();

string ss = tt.format();

 

Tried in differenct scenarios but getting time also can any one help me on this. Only wanto get the date part.

 

Joining_Date__c - Today () >= 25

 

This is the condition for me. Want to do this

Hi.

 

   I have written just a few triggers and was wondering if this trigger is absolutely fine or if it lacks something.. although the trigger is working when i am inserting single entry through the window.. was wondering if it would also work when using data Loader.

I'm trying to create a contitional query of sorts.  I have a multi-select list field on my Account object, referenced below:  

Account[] pChk = [SELECT Products_Available_for_Sale__c FROM Account WHERE Name =:acct];

 And I want to use the specific contents from each account, whatever they may be, as a search paremeter for the below query and populate a list on my VF page with the results.  Currently this is what I have, but it is incorrect as it does not seem to accept the array in the manner I'm trying as I keep getting unexpected token errors one way or the other:

String qry = 'SELECT Name, Insurer__c, Form_Number__c, Form_Title__c, Cancellable__c, Product_Group__c, State_Specific__c, In_Use__c FROM MG_Forms__c WHERE In_Use__c = TRUE AND (Form_Title__c LIKE \''+String.escapeSingleQuotes(query)+'%\') AND (Product_Group__c INCLUDES ('+ pChk +'))';
      searchResults = Database.query(qry);

 I've also tried just making the array a list, with the same lack of results, so I'm wondering if perhaps there is a simpler way to go about this, or if I may just be missing a step somewhere.  Any help would be appreciated.