• Alex.Acosta
  • SMARTIE
  • 804 Points
  • Member since 2010

  • Chatter
    Feed
  • 29
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 17
    Questions
  • 232
    Replies

Hello,

 

I'm fairly new to writing apex. I've written the following code to update the status of the case to match that of another dropdown(JIRA_Status2__c) on the case.  This trigger should only fire when JIRA_Status2__c changes and if the recordtype matches.

 

The code works, but I would like to know if I've written too much to achieve such a basic update.  Thanks for the input in advance. It wil help me to learn how to code better in the future.

trigger UpdateJiraOnlyRT on Case (after update) {

    //create list of case IDs
    List<ID>cid = new List<ID>();
   
    
    
    //add cases to list for only cases that has JIRA Status2 dropdown changed AND recordtype=012A00000017NFl

    for (Case c: Trigger.new){
        Case oldCase = Trigger.oldMap.get(c.Id);
        if((oldCase.JIRA_Status2__c != c.JIRA_Status2__c) && (c.RecordTypeID=='012A00000017NFl')){
            cid.add(c.ID);}
    }
  
   //update the list  
    List<Case>updatecase =[SELECT Id, Status, JIRA_Status2__c from Case WHERE Id IN:cid];
    for(Case c2:updatecase){
        c2.Status = c2.JIRA_Status2__c;
    }
    
    update updatecase;
        
}

 

 

Hello,

 

I am still very new to APEX.  I am trying to develop a simple visualforce page that lists all the accounts the active user owns.  Ideally, the user should be able to edit and save the records.  When the user clicks save, the record in the database should update.  Currently, the edit and save buttons do not work but I can make changes when double clicking but they do not save.  Any help is greatly appreciated.

 

My code so far:

 

*********************Visualforce page************************

 

<apex:page controller="MyController" >
     
      <apex:form >
     
        <apex:pageBlock title="My Accounts">
       
           
                <apex:pageblocktable value="{!myaccounts}" var="acct">
                    <apex:column value="{! acct.name}"/>
                    <apex:column value="{! acct.Preferred_Mode_S__c}"/>
                    <apex:column value="{! acct.type}"/>
                     <apex:inlineEditSupport event="ondblclick"/>
                  
                </apex:pageblocktable>
                <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandbutton value="Edit" action="{!edit}"/>
        </apex:pageblock>
  </apex:form>
</apex:page>

 

 

*****************************Controller*****************************

 

public class MyController {

         public List<Account> getMyAccounts(){        

List<Account> a = new List<Account>();        

a = [select Id,name,type,preferred_mode_s__c,macro_industry__c,micro_industry__c from Account WHERE (owner.id =: userinfo.getuserid())];            

return a;           

}   

 

public PageReference edit() {        

return null;    

}

    public PageReference save() {        

return null;    

}

}        

Hi Friends, 

 

I am sending an email based on template. I want to count the number of times emails are count successfully.

 

As you can see here:

 

 

try {
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
     Messaging.SendEmailResult[] mailResult = Messaging.sendEmail(new      
Messaging.SingleEmailMessage[] { mail }); if ( !mailResult[0].isSuccess() )
{ EmailFailure = 'Email Failed: ' + mailResult[0].getErrors()[0].getMessage() +' \n \n'; } else { EmailCounter.Emails_sent_from_apex__c = EmailCounter.Emails_sent_from_apex__c +
Number_Of_Recipients ; update EmailCounter; } } catch(System.EmailException emlEx)
{ EmailFailure = 'we got here: ' + emlEx+' \n \n'; }

The surprising thing is that I do get the email as expected BUT an  Email exception is till thrown. As a result my counter is not updated, even though an email was sent. 

 

The Email exception received is:  System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_FIELD_WHEN_USING_TEMPLATE, When a template is specified the plain text body, html body, subject and charset may not be specified : []

 

Just to make is clear - I am NOT using :text body, html body, subject and charset.

 

Why do I get this exception ?

 

Please Help :)

 

Eyal

 

  • July 11, 2013
  • Like
  • 0

Hi Everyone, 

 

I'm trying to learn APEX and wonder whether you could help.  I have a trigger which simply calls a class when a Slot__c record is inserted or updated.

 

trigger InsertAvailableServices on Slots__c (after insert, after update) {
    //Pass new/updated slot record to class    	
    AvailableServicesController.handleOpeningChange(Trigger.old, Trigger.new);    	
}

 My class is as follows and works until I add the following line and then it all goes rather wrong. 

 

insert availableTreatments; 

 

public class AvailableServicesController {
        public class AvailableServicesException extends Exception {}
        public static void handleOpeningChange(List<Slots__c> oldSlots, List<Slots__c> newSlots) { 

            for (Slots__c slot : newSlots) {  

            List<Treatment__c> treatments = [select Id, Name, Account__c, Duration_Int__c, Price__c from Treatment__c where Account__c =: slot.Account__c and Duration_Int__c <=: slot.Duration_mins__c];
            
            if (treatments.size() == 0) {  
                throw new AvailableServicesException('There are no Available Products/Services for your opening duration');  // then an exception is thrown.
            }
            
                List<Available_Treatments__c> availableTreatments = new List<Available_Treatments__c>();
	       	
	            for (Treatment__c treatment : treatments) {
	               if (treatment.Duration_Int__c <= slot.Duration_mins__c) {
	                   AvailableTreatments.add(new Available_Treatments__c(Slot__c = slot.id, treatment__c = treatment.id, Start_Time__c = slot.Start_Time__c,
	                                                                       Duration_mins__c = treatment.Duration_Int__c,
	                                                                       Internet_Price__c = treatment.Price__c - ((treatment.Price__c * slot.Discount__c) / 100),
	                                                                       Treatments_for_Slot__c = ((slot.Duration_mins__c / treatment.Duration_Int__c).round(roundingMode.DOWN))));          
	                }
	            }
	            
	            insert availableTreatments; 
            }

        }
    } 

I get this error: 

 

Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InsertAvailableServices: maximum trigger depth exceeded
Slots trigger event AfterInsert for [a00i0000003ejIb]
Slots trigger event AfterUpdate for [a00i0000003ejIb]

 

I'm sure it's because I'm trying to do everything in for loops of death, but here are the things I can't quite work out. 

 

1.  When a Slots__c record is inserted I need to store information about it for use in SOQL queries e.g. AccountId and Duration_mins__c.  I had it working with a load of variables but it just feels messy.  Not sure what the best way to do this is?

 

2.  For each inserted Slots__c record I want to query a list of Treatment__c based on criteria from the Slot__c record.  I then want to insert these records into the Available_Treatments__c object.  I also need to populate this object with information from the inserted Slot__c record.

 

My challenge is that I always need to re-use information from the Slot__c record throughout my SOQL queries and when I'm populating the list for insert.  I could put everything in variables but is there a better way?

 

Thanks

 

Please modify it:

 

Trigger RTODefault on Opportunity (before insert, before update) {
if(trigger.new[0].Business__RTO_Default__c != NULL && (trigger.new[0].Business__RTO_Default__c == 'Fixed' || trigger.new[0].Business__RTO_Default__c == 'Passthrough')){
trigger.new[0].Business__Energy__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__Capacity__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__Network_Service_Transmission__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__Congestion_Marginal_Losses__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__Ancillary_Services__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__Losses__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__Marginal_Losses__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__ARR_Credit__c = trigger.new[0].Business__RTO_Default__c;
trigger.new[0].Business__RMR_charge__c =trigger.new[0].Business__RTO_Default__c;
}
}

 

Thanks in Advance.

  • July 09, 2013
  • Like
  • 0

Hi all,

 

I am getting the error: 

 

Error:Apex trigger handleReservationChange caused an unexpected exception, contact your administrator: handleReservationChange: System.LimitException: Too many SOQL queries: 101

 

I know that it's wrong to have the SOQL queries inside the for loops, but can't understand how to perform what I need otherwise. Could someone please post a code sample of how I could take the SOQL queries outside of the loops?

 

 

private static void assignPricesToReservation (ReservationRoomAssociation__c assoc)
    {
    	Double todayRate = 0;
		Date currentDay;
		
		System.debug('adding assoc ' + assoc);
		
		// Initialize price
		assoc.Price__c = 0;
		
          
        // Get room type                            
		Room_Type__c rt = [SELECT Name,Number_of_Rooms__c, Default_Rate__c, Id
		 				   FROM Room_Type__c 
		 				   WHERE Id = :assoc.Room_Type__c LIMIT 1];
		System.debug('found roomtype ' + rt);		 
		String roomType = rt.Name;
		System.debug('Room type is ' + roomType);
		
		// Get reservation
		Reservation__c resa = [SELECT Total_Nights__c, Check_In__c, Check_Out__c, Total_Price__c
		 					   FROM Reservation__c 
		 					   WHERE Id = :assoc.Rooms__c LIMIT 1];
	        
        // Add price per night    
		for (Integer i = 0; i < resa.Total_Nights__c; i++)
        {
            currentDay = resa.Check_In__c.addDays(i);          
            System.debug('Date: ' + currentDay);
           
            // Check for availability for the night
            try 
            {      
                Availability__c avail = [SELECT Name, Rooms_Available__c,Room_Type__c 
                                         FROM Availability__c 
                                         WHERE Date__c = :currentDay AND Room_Type__r.Name = :roomType];

                // Yes, there is availability
                if (avail.Rooms_Available__c <= 0)
                {
                	throw new reservationException('No availablity for the selected dates');
                }		
                else
                {
                	// Remove one room from the total available rooms of this date / room-type match
                	avail.Rooms_Available__c -= 1;
                	update avail;
                }	    
		    }
		    catch (Exception e) 
			{
				// No availability record, create one
			    System.debug('no availability record, creating a new one with max rooms ' + rt.Number_of_Rooms__c);
			    Availability__c avail = new Availability__c ();
			    avail.Date__c = currentDay;
			    avail.Rooms_Available__c = rt.Number_of_Rooms__c - 1;
			    avail.Total_Rooms__c = rt.Number_of_Rooms__c;
			    avail.Room_Type__c = rt.Id;
			    insert avail;
			    	    			    
			}
			
			
			try 
            {
			    // Is there a specific rate for this day?
			    Date_Rate__c dateRate = [SELECT Price__c
			    						 FROM Date_Rate__c
			    						 WHERE Date__c = :currentDay
			    						 AND Room_Type__r.Name = :roomType
			    						 ];
				 if (dateRate != null)
				 {
				 	todayRate = dateRate.Price__c;
					System.debug('got date-specific rate for ' + currentDay + ' rt: ' + roomType + ' rate is: ' + todayRate);			 
				 }
			}
			catch (Exception e)
			{
			 	todayRate = rt.Default_Rate__c;    
				System.debug('couldn\'t find specific rate for ' + currentDay + ' using default rate: ' + todayRate);	 	
			}
			
	        // Add the rate for this date and room type   
	        System.debug('adding rate to the total price: ' + todayRate);   
	        assoc.Price__c += todayRate;
	          		
	        if (resa.Total_Price__c != null)
	        {
	        	resa.Total_Price__c += todayRate; 
	        }
	        else
	        {
	        	resa.Total_Price__c = todayRate;
	        } 
		            
        }
	    System.debug('New reservation total price is ' + resa.Total_Price__c);   
	    update resa;   	
    }
    
	private static void calculateReservationPrice (Reservation__c r)
	{
		try 
		{
			Reservation__c resa = [SELECT Total_Price__c FROM Reservation__c WHERE Id = :r.Id];
			resa.Total_Price__c = 0;
			update resa;
		}
		catch (Exception e)
		{
			System.debug('couldn\'t set reservation price to 0');
		}
		
		System.debug('calculating new reservation price');
				
		// Get all room associations for this resa
		List <ReservationRoomAssociation__c> assoc = [SELECT a.Id, a.Room_Type__c, a.Rooms__c
												      FROM ReservationRoomAssociation__c a
												      WHERE a.Rooms__c = :r.Id];
		
		System.debug('updating pricing for ' + r.Name);
		
		for (ReservationRoomAssociation__c a : assoc)
		{
			System.debug('Assigning price for association ' + a);
			assignPricesToReservation(a);
		}
	}
	public static void handleReservationChange(List <Reservation__c> oldResas, 
											   List <Reservation__c> newResas)
    {
    	System.debug('handleReservationChange');
    	
    	
    	Reservation__c oldResa;
    	// Check if reservation changed in length
    	for (Reservation__c r : newResas)
    	{
    		oldResa = null;
    		
    		// get the corresponding old resa
    		System.debug('in reservation iteration loop');
 
    		for (Reservation__c oldR : oldResas)
    		{
    			if (oldR.Id == r.Id)
    			{
    				oldResa = oldR;
    				break;
    			}
    		}
    		if (oldResa == null)
    		{
    			throw new reservationException('can\'t find old reservations');
    		}
    		
    		System.debug('old nights: ' + oldResa.Total_Nights__c + ' new nights: ' + r.Total_Nights__c);
    		
    		if (oldResa.Total_Nights__c != r.Total_Nights__c)
    		{
    			System.debug('calling caluclateReservationPrice for' + r);
    			calculateReservationPrice(r);
    		}
    	}
    	
    	
    }
    

 

Thanks!

 

Hello I've written a trigger to comment feeditems with special keywords. The problem is, that the feedItem.ID is null and so the insert comment fails. Why is the feeditem.ID null?

One of my test class fails with the following error, which is highlighted in red in trigger.

 

Could it be because i have an update in the class which is called by this trigger?

 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Agreement_Update_After: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.Agreement_Update_After: line 60, column 1: []

 

 

trigger Agreement_Update_After on Agreement__c (after update) { 

	if (trigger.isUpdate && trigger.new != null){
		
		 	                      
		list<Agreement__c> rid_onboard = new list<Agreement__c>();
		rid_onboard = trigger.new;
		   
		list<ID> reqids = new list<ID>();
		        
	   	for(Agreement__c rob : trigger.new){     
	      
	        if(!System.Trigger.oldMap.get(rob.Id).Approval_Status__c.equals(rob.Approval_Status__c) && rob.Approval_Status__c.equals('Approved')  && ((!rob.EngagementStatus__c.equals('Active')) || (!rob.EngagementStatus__c.equals('Probation'))) ){  	    	
	    	    reqids.add(rob.Id);
			}
	     
        }
        
        if (reqids.size() > 0 ){ 
        	
        	ctrl_SM_OverallTime.calculateOverallTime(reqids);    
     	} 
	
	}  
	


}

 

 

 

public with sharing class ctrl_SM_OverallTime { 
	
    public static void calculateOverallTime(list<ID> reqids){          
       	        
        list<Agreement__c> r1 = [ Select Id, .... 
        							From Agreement__c where Id = :reqids];
                
        list<Agreement__c> r2 = new list<Agreement__c>();
                            
        for (Agreement__c r: r1){                                               
	     
	     	if (.......){ 
	           
		        datetime tob = r.Approved_Date__c;   // this is populated in a before update trigger on  Agreement__c 
		        date dob = tob.dateGMT();
		        
		        datetime ttob = r.Exposed__c;
		        date ddob = ttob.dateGmt(); 
		       
		        r.On_Board_Cycle_Time__c = BusinesssDaysCalc.getDiffBusinessDays(ddob, dob);
	     	
	     	} else if (........){ 
	              
		       
			       if( r.Approved_Date__c != null){
				        datetime tob1 = r.Approved_Date__c;
				        date dob1 = tob1.dateGMT();
				        
				        datetime ttob1 = r.CreatedDate;
				        date ddob1 = ttob1.dateGmt(); 
				          
				        r.On_Board_Cycle_Time__c = BusinesssDaysCalc.getDiffBusinessDays(ddob1, dob1);         
			       }
	     	} else if (..........){ 
	          
		        datetime ttpa = r.Approved_Date__c;
		        date dtpa = ttpa.dateGMT();
		        
		        datetime ttpa1 = r.PA_Exposed__c;
		        date dtpa1 = ttpa1.dateGmt(); 
		         
		        r.On_Board_Cycle_Time__c = BusinesssDaysCalc.getDiffBusinessDays(dtpa1, dtpa);    
	     	}
        	
        		r2.add(r);	
	   }
    
			    if(r2.size() > 0){
			    	update r2;    /// could it be becuase of this. 			    	
			    }
  }
  

}

 

 

 

 

Hello Everyone,

 

I am new to the Salesforce development.Below is the trigger :

 

trigger trgUpdateComments on Task (before update)
{          
    DateTime d = system.now();
    for(task ta : trigger.new)
    {
        string dec = String.valueof(d) + '\n' + ta.Description ;
                ta.Description = dec;
         
    }    
}

 

What it does is that: whenever we enter any comment in the comments field on the tasks and save it.It will display the system date and time followed by the comment entered as below:


2012-09-27 10:25:41

Testing1

 

The problem is whenever I enter the second comment the format is as below:

 

2012-09-27 10:27:23

2012-09-27 10:25:41
Testing1

Testing2

 

But it should be as:

2012-09-27 10:27:23

Testing2

2012-09-27 10:25:41
Testing1

 

Can someone help me with this please.Thank you!!

 

Good day!
I write a trigger and ran into a problem ((

In the info_c comes this value:
Scott; Kavanagh; The Art Of; Vice President; 416-555-5555; scott@theartof.com | Steve; Comrie; Simplicate Interactive; Owner; 416-555-5555; steve@simplicate.ca | John; Smith; Rogers; Marketing Assistant; 416-555-5555; john.smith @ rogers.com

 

I need to convert this value and add to object Сontacts:

1st contact:
First Name - Scott
Last Name - Kavanagh
Company - The Art Of
Job Title - Vice President
Phone - 416-555-5555
Email - scott@theartof.com

2nd contact:
First Name - Steve
Last Name - Comrie
Company - Owner
Job Title - Vice President
Phone - 416-555-5555
Email - steve@simplicate.ca

 

N nd contact:

.......

 

How do I make it?

I have modified a code for inserting the account owner on an opportunity record to show the same on a case object, but getting error: Compile Error: Incompatible element type Schema.SObjectField for collection of Id at line 4 column 36

 

I am new to apex and have only successfully modified current triggers when fields change, any help is appreciated.

 

trigger trgAccOwner on Case (before insert,before update) {
    Set<Id> acctIDs = new Set<Id>();
    for(Case tl:Trigger.new) {
        if(case.AccountId != null) acctIDs.add(case.AccountId);
    }
    
    Map<Id, Account> acctMap = new Map<Id, Account>([select Owner.Name from Account where Id in :acctIDs]);

for(Case tl: Trigger.new) {
        if(case.AccountId != null) case.Account_Owner__c = acctMap.get(Case.AccountId).Owner.Name;
    }
}

 

 

I have an empty visual force page on my Account records.  This visualforce page has 

extensions="AccountRollUpController" action="{!getCounts}">

and the apex that it is calling looks like 

public void getCounts()
    {
        this.account.of_Contacts__c = getintNumberOfContacts();
        this.account.of_Open_Activities__c = getintNumberOfOpenActivities();
        this.account.of_Closed_Activities__c = getintNumberOfClosedActivities();
        update this.account;   
    }



The problem is that this code seems to be run after the Account Record is loaded. For instance, the very first time I view and account record the 3 fields above are blank, if I refresh the page the correct values appear. I also have a problem when, from the account record, a user chooses to add a contact, when they are returned to the account record the count of contacts isnt correct until the account record is refreshed.

Help? :)

My current trigger checks the opportunity probability percentage and denies deletion based on probability.  We want to add an exception that if the profile of the user trying to delete is the System Admin then it would not cause the trigger to fire.  Can someone please help me with what I would need to add that exception into my code?  I found one other question/answer from years ago on the topic but the answer didn't make sense to me so I wasn't sure if it was written for an s-control or something.

 

trigger CannontDeleteOpportunity95 on Opportunity (before delete) {
 if(System.Trigger.IsDelete)
        {
        for (Opportunity Opps : trigger.old)
            if (Opps.Probability >= 95)
          
                {
                Opps.addError('Error: You cannot delete this Opportunity.  Please contact a system Administrator for assistance');
                }
        }          
}

 

Thanks,

Amanda

Hi,

 

Anyone knows how to check the extension file for an attachment.

 

I have this Trigger:

 

trigger checkAttachment on Attachment (before insert) {
    For(Attachment att:Trigger.new)
    {
        if(att.ContentType=='.exe')    
        {
            att.addError('Cannot upload file with extension .exe');                    
        }
    }    
}

 

But it don't work, it still accepts files with .exe extension.

 

Hi, 

I'm fairly new to Apex and I have a trigger that isn't working.

Basically, I have two objects of importance - a holder and a provider. The holder has a name field that I want to be automatically set to the name of the provider. so far I have:

 

trigger rename on Holder__c (before update, before insert) {
    for(Holder__c h : trigger.new){
           h.Name = h.Provider__c.Name;
     }
}

 

but i'm getting a weird error. any help would be greatly appreciated.

-greg

Currently I have a workflow / field update but due to some limitations I want to change this workflow into a trigger

Note: All fields are in same object called object__c,

F1__c,F2__c etc are number fields,

FieldAddAll__c is of type Currency,

Field_1__c, Field_2__c etc are of type currency and the value in  these is populated by formula

evaluation criteria: Everytime a record is created or updated

Rule criteria:

OR(OR(RecordTypeId="012333333333",
RecordTypeId="0125555555555",
RecordTypeId="01266666666666"),
OR( ISCHANGED( F1__c ),
ISCHANGED( F2__c ),
ISCHANGED( F3__c ),
ISCHANGED( F4__c ),
ISCHANGED( F5__c ),
ISCHANGED( F6__c ),
ISCHANGED( F7__c ),
ISCHANGED( F8__c ),
ISCHANGED( F9__c ),
ISCHANGED( F10__c ),
ISCHANGED( F11__c ),
ISCHANGED( F12__c ),
))


Field update:

FieldAddAll__c =

( Field_1__c  + Field_2__c  + Field_3__c  + Field_4__c  + Field_5__c + Field_6__c + Field_7__c + Field_8__c + Field_9__c + Field_10__c + Field_11__c + Field_12__c  )

 

 

I want to chnage the above workflow into a trigger. Any help will be appreciated.

I have a custom Cases apex page where I use a apex:pageBlockTable to display my list of Cases. Here is the code for it:

<apex:page standardController="Case" recordSetVar="Case" sidebar="true" showHeader="true">
    <apex:form >
        <apex:pageBlock title="Cases">
              <apex:outputLabel value="View:"/>
              <apex:selectList value="{!filterId}" size="1">
                <apex:actionSupport event="onchange" rerender="cases_table"/>
                <apex:selectOptions value="{!listviewoptions}"/>
              </apex:selectList>
            <apex:pageBlock >
                <apex:pageBlockButtons >
                </apex:pageBlockButtons>
                <apex:pageBlockTable value="{!case}" var="c" rows="50" id="cases_table" >
                    <apex:column >
                        <a target="_parent" href="{!URLFOR($Action.Case.View, c.id)}">{!c.CaseNumber}</a>
                        <apex:facet name="header">Case Number</apex:facet>
                    </apex:column>
                    <apex:column value="{!c.ContactId}" />
                    <apex:column value="{!c.Subject}" />
                    <apex:column value="{!c.Status}" />
                    <apex:column value="{!c.Priority}" />
                </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:pageBlock>
    </apex:form>
    <base target="_parent"/>
</apex:page>

I would like to get a button inside my apex:pageBlockButtons like in the default Cases page. When the user clicks the button, I would like it to take the user to the new Cases page. I tried this:

<apex:commandButton action="{!new}" value="New"/>

but that gave me an error. How do I make a button that will take me to the new Cases page?

  • August 15, 2012
  • Like
  • 0

We have a customer portal where the users are managed by customer admins.  We want to give all new users read access to a certain content library, and I can't find anything in the documentation that states that we can update a user's permissions to a library via apex.  Is this possible?  My workaround is to generate a case to us everytime a new user is created, and we'll manually go in and set the new user's permissions via the UI.  I'd really rather have it automated.  Does anyone know how I can accomplish this?

 

Thanks.

I have an APEX select list on my page. And I would like to be able to load information via a SOQL query utilizing the selected value as a parameter.

 

How would I access the Select List value in my APEX?

 

For example does the visualforce tag have an ID attribute that I can then access somehow like ID.Value etc...

Hi buddies,

 

I have started writing the test class but I am facing error when trying to insert the opportunity line items as below:

 

Please help me out on how to inset opportunity lineitems for the opportunities

 

Compile Error: Invalid field Name for SObject OpportunityLineItem at line 16 column 57


@istest
public class testAnOVIIDClass
{
static TestMethod void testAnOVIIDClass(){
//data preparation
list<opportunitylineitem> olilist=new list<opportunitylineitem>();
list<opportunity> opplist=new list<opportunity>();
list<id> pricebookidlist= new list<ID>();
list<String> productlist=new list<string>();

for(integer i=0;i<2;i++){
opportunity opy = new opportunity(Name = 'test opp' + i);
opplist.add(opy);
}
for(integer i=0;i<2;i++){
opportunitylineitem aol= new opportunitylineitem(Name = 'test opp line item' + i);
olilist.add(aol);
}
}
}

 

Thanks

JL

Affected Orgs: Winter 15 Sandboxes

When using a field described as a Rich Text Field and displayed within a visualforce page, the content is not copied over to the hidden textarea. Thus Updates are not possible. All other fields are able to be updated correctly. Also no error messages are shown

Example Code:
<apex:page standardController="Template__c">
<!-- Error Message -->
    <apex:outputPanel id="msg">
        <apex:pageMessages />
    </apex:outputPanel>
<!-- Form -->
    <apex:form id="theForm">        
        <apex:pageBlock title="Template Edit">  
<!-- Standard Buttons -->
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save" rerender="msg,information,templateSubject" onclick="setTemplateBodyParams();"/>
                <apex:commandButton action="{!cancel}" value="Cancel"/>
            </apex:pageBlockButtons>
<!-- Body -->        
            <apex:pageBlockSection columns="1" title="Information" collapsible="false" id="information">
<!-- Sobject Name Field (String Type) --->
                <apex:inputField value="{!Template__c.Name}" />
<!-- Sobject CustomField (String Type) --->
                <apex:inputField value="{!Template__c.TemplateSubject__c}"/>
<!-- Sobject CustomField (RichText Type) --->
                <apex:inputField value="{!Template__c.TemplateBody__c}"/>
<!-- Sobject OwnerId Field (Lookup Type) --->
                <apex:outputField value="{!Template.OwnerId}" />
            </apex:pageBlockSection>
        </apex:pageBlock>       
    </apex:form>
</body>
</apex:page>


I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:

     "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false

As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?
I have a constant variable class for parsing out xml stucture on callouts as seen below. Problem is the way code is covered has changed it seems. Any idea why and/or how to fix this?

 
public with sharing class XMLElementNodeNames {
  public static final String CATEGORY_TAG = 'category';
  public static final String CATEGORIES_TAG = 'categories';
  public static final String ID_TAG = 'id';
  public static final String SCORE_TAG = 'score';
  ...
  static testmethod void testAll() {
// only having the following line would cover the class. Now it returns with 0% coverage
XMLElementNodeNames x = new XMLElementNodeNames();

// I have since added the following to try for code coverage to no avail.
String theString;
theString = CATEGORY_TAG;
theString = CATEGORIES_TAG;
theString = ID_TAG;
theString = SCORE_TAG;
....
  }
}

I'm having an issue with standard rendering. Within the 'Action' column, the checkbox next to the 'Edit' and 'Delete' links appears on some Sobjects and not others. Example would be in one Sandbox both Account and Leads works fine and you can see it on both. On other sandboxes only one works. I was hoping when pushing it to production I would be lucky enough to have it work, but alas, it did not. Works great on Leads when it came to Account, I had a no go.

 

 

VF code:

<apex:page showHeader="true">
    <apex:ListViews type="Account">
    </apex:ListViews>
</apex:page>

 

Short version of my question, how can I make this standard checkbox appear?

http://i.imgur.com/90UUEn2.png

 

 

 

Only possible solutions I've found online are:

Validating under Setup > Customize > User Interface
        Validate 'Enhanced Lists' and 'Inline Editing' is enabled.

Also If you have record types and in the list view you have more than one record types, you will lose the checkbox.
Try create a list view which contains only ONE record type.
so use a filter
account record type = xxx
and set your other filters.

 

 

I have tried both these with no luck. Please help!

I'm having an issue with a age range formula that's returning a numeric value back. On the page layout it displays the field value correctly, but whenever I try to run a report with it, it just throws me the error on the field column value. Anyone has this issue before?

 

Formula:

IF( 
	AND(
		NOT(ISNULL(CustomFieldDate__c)),
		DateValue(TEXT(CustomFieldDate__c)) > DateValue(Text(CreatedDate))
	),
	DateValue(TEXT(CustomFieldDate__c)) - DateValue(Text(CreatedDate)), 
	0
)

 

Now I've used this logic multiple times in the past... and they are working just fine, but this time for what ever reason I'm getting this error, 'System.JSONParser is not serializable.'

 

On my controller, if I just call a new instance of the class for example:

HttpResponse response; // has response from outbound call 

// This works just fine
new JSONResponseParser(response.getBody());

 

This is where I get the exception on my controller...

HttpResponse response; // has response from outbound call 

// This throws me the error
JSONResponseParser myParsedJSON = new JSONResponseParser(response.getBody());

 

 

Why is this occuring? I've done this before in the past just fine... is there just a limit to the JSON return size that causes it to not be serializable? 

 

 

My sample code that's doing the parser...

public class JSONResponseParser{
	private ResponseWrapper theResponse;
	private final JSONParser parser;
		
	public JSONResponseParser(String jsonString){
	    parser = JSON.createParser(jsonString);
	    parseJSON();
	}
		
	private void parseJSON(){	
	    while (parser.nextToken() != null) {
	        if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
	            theResponse = (ResponseWrapper)parser.readValueAs(ResponseWrapper.class);                
	        }
	    }
        }		
}

 

I'm having some issue with some code and this seems like some sort of bug, can anyone explain to me why this is happening?

 

Map<String, List<String>> stringMap = new Map<String, List<String>>();
stringMap.put('key1', new List<String>{'value1', 'value2'});

for(String mapKey :stringMap.keySet()){
	for(Integer i = 0; i <= stringMap.get(mapKey).size(); i++){

		if(stringMap.get(mapKey).size() > i){
			system.debug(stringMap.get(mapKey).get(i));
		}

		if(stringMap.get(mapKey).size() > i++){
			system.debug(stringMap.get(mapKey).get(i));
		}

                /**
                 * CODE BREAKS ON THIS IF CONDITION 
                 * WHICH IT SHOULD FAIL TO VALIDATE... 
                 * stringMap.get(mapKey).size() = 2
                 * i++ = 2
* This IF condition should not pass. **/ if(stringMap.get(mapKey).size() > i++){ system.debug(stringMap.get(mapKey).get(i)); } } }

 

I have an issue where my my org is uploading a ton of leads at a time via the dataloader. These new leads could potentually be existing accounts / leads and need to be merged to their latest associated record. The issue I'm having is, imagine a batch of 200 records hits my trigger and all have to be merged with older leads. Only 150 DML statements are allowed, and each merge has to be done one at a time which causes an issue. I know the Salesforce API has an object alled MergeRequest which allows you to do a collection of merges within a single call. Has anyone been able to figure out an effiecent way of achieving this? Also, does anyone know if the API can be called within a trigger / apex? 

Is it possible to merge multiple records at once as within the API? I seem to be having issues with this.

 

http://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_calls_merge.htm|StartTopic=Content%2Fsforce_api_calls_merge.htm|SkinName=webhelp

 

IE: potential to do 200 merges within a batch execute of a trigger/class/method/extension and not have to waste your precious DML statements for multiple merges limited to governor limits.

I'm trying to use the same functions using javascript allowed on a visualforce page, but on a button.
IE: something alone these lines https://sites.secure.force.com/success/ideaView?id=08730000000YKxY

 

Problem is when I try running my javascript within my button... all browsers (Chrome, IE, and FireFox) throw exceptions with Salesforce javascript library....

 

Code is as follows:

{!REQUIRESCRIPT("/support/console/25.0/integration.js")}
if (sforce.console.isInConsole()) {
alert("in console");
} else {
alert("not in console");
}

 

Javascript Error:
Uncaught TypeError: Cannot read property 'Caller' of undefined integration.js:10
(anonymous function) integration.js:10
(anonymous function) integration.js:782


If you can please point me in the right direction of how to resolve this issue, i would greatly appreciate this.

I'm trying to make an outbound callout to our internal server. I know Salesforce requires a valid cert by a trusted 3rd party vendor to be installed on that server. Now Salesforce provides the ability to use a CA -Signed Cert. I've gone ahead and created one of these types of certs on Salesforce, and provided back a signed Cert. This is being tested within my Sandbox, where this cert was created and reuploaded to and is now actived, I'm still getting: 

 

FATAL_ERROR System.CalloutException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

 

 

HttpRequest request = new HttpRequest();
        request.setMethod('POST');
        request.setHeader('Host', '<host url>');
        request.setHeader('api_key', '<api key>');           
        request.setClientCertificateName('<cert unique name on salesforce>');
        request.setEndpoint('<endpoint url>');
        
Http callout = new Http();
        HttpResponse response = new HttpResponse();
        response = callout.send(request);

 

 

Any idea what I might be doing wrong?

 

My whole goal originally was to get an Email Template and passing in my records to see the merged field results to display it for a user since the template/script will changed based on different critera within the visualforce page wizard I was making, and in order to avoid changing code as much as possible I was hoping the use of a template would suffice.

 

Sadly I was unable to successfully find a solution to this. So I've gone the route of using Regular Expression to do my find/replace of the merge fields. I currently have this example which works online in other regular expression validators but not within Apex.

 

String emailTemplate = 'Dear {!Lead.FirstName},'+
'Thank you for responding to your exclusive invitation. Blah blah blah your invitation code is {!Lead.externalId__c}.'+
'Stay well,\n{!User.FirstName} {!User.LastName}\nCompany Name';
		
Pattern myPattern = Pattern.compile('(\\{!+([a-zA-Z_.]*\\.[a-zA-Z_]*)})');
Matcher myMatch = myPattern.matcher(emailTemplate);
System.debug('\n\nMatch found? ' + myMatch.matches() + '\n\n');

if(myMatch.matches()){
	while (myMatch.find()) {
		System.debug('\n\nStart index: ' + myMatch.start() + '\nEnd index: ' + myMatch.end() + '\n' + myMatch.group() + '\n\n');
	}
}

 

Once this issue is resolved, with the matching working correctly, any ideas on how to replace those values dynamicly?

 

Any help is greatly appreciated!

I have a quick question. In a development org a few developers including myself are on hit the API limit of 5k. Once this happened our Developer Console stopped loading. We've tried multiple computers and browsers to verify it isn't some sort of caching issue. Are these two related some how or is the NA14 server having some issues? 

Hi there,

 

Been having a few issues with the Salesforce API for a while now... this doesn't happen often but it does occur pretty frequent. The link below is just an images to show what is happening....

 

http://i.imgur.com/VsMZf.png

 

Basically, I'm just showing off how 1 particular record looks like and the issue that seem to be occuring within the response from Salesforce which appears to be a bug. 

 

On section:

#1 -- I'm just showing Id of the record that's being retrieved.

#2 -- One of the values we're pulling back is slightly correct, but also very wrong. the value associated to the record is 0.0000 but the response we get back from salesforce is 9.2756605126005708706853560339489977171E-34..... instead of limiting to the 18 character float value it's suppose to be.

#3 -- Just a standard query we are using to pull back records from salesforce

#4 -- Showing the record we retrieved using the salesforce WSDL generated Class sObject

#5 -- Our field definision which is also incorrect. In this case, Salesforce is describing the field as a double with 26 field lenght size when the maxium allowed is 18 and also showing incorrect values.

 

I've tried submitting this as a bug through the partner portal, but Salesforce no longer supports none 'premium' partners when submitting a development case. 

 

I would greatly appreciate some help with this issue and figure out records are being retrieve in this way.

 

Thanks for your time.

 

API Session Id

 

I've been trying to find a work around for this issue. Basically, if I use the merge field {!$Api.Session_ID} on a button, the session Id is value and works just fine. If I attempt to use the same Api.Session_ID within either a formula field on a sObject, or within the APEX VisualForce page as a standalone merge field the session is no longer valid and fails when an outside source attempts to use that session Id. Would anyone know why and/or a work around for this?

Hi All,

 

Been having an issue here with salesforce and my trigger. It pretty much boils down to this... If I create an Opportunity my trigger works fine, but if I convert a Lead and have Salesforce generate my Opportunity I get this error:

FATAL_ERROR|System.DmlException: Insert failed. First exception on row 2; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>: []

Now my code consists of 2 triggers. First trigger generates Teams and Team Members for each Opportunity Created.

Second trigger consists of each time a Team Member is created they are set to auto Follow that Opportunity.

 

First Trigger Example:

trigger OpportunityTeams on Opportunity (after insert) {
    
    List<Team__c> teams = new List<Team__c>();
    List<Team_Member__c> teamMembers = new List<Team_Member__c>();
// Please make sure you have more than 2 users in your system. (so at least 3 users) to demostrate this issue
List<User> users = [SELECT id FROM USER WHERE id != :UserInfo.getUserId()];
for(Opportunity opp : trigger.new){ Team__c team1 = new Team__c(); team1.Opportunity__c = opp.id; team1.Name = 'Team 1'; teams.add(team1); Team__c team2 = new Team__c(); team2.Opportunity__c = opp.id; team2.Name = 'Team 2'; teams.add(team2); } if(teams.size() > 0){ insert teams;

Integer userPosition = 0; // loop through all teams to add all their team members for(Team__c t : teams){ Team_Member__c tm = new Team_Member__c(); tm.Opportunity__c = t.Opportunity__c; tm.Team__c = t.Id; tm.User__c = UserInfo.getUserId();
tm.User__c = users.get(userPosition);
userPosition++; teamMembers.add(tm); } if(teamMembers.size() > 0) insert teamMembers; } }

 

Second Trigger to Auto add Team Members. Please keep in mind, Opportunity__c is a lookup to Opportunity and User__c is a lookup to User, and this trigger only runs on After Insert

trigger TeamMemberChatterAutoFollow on Team_Member__c (after insert) {

// Opportunity Id Key, with a set of User Id Value Map<Id, Set<Id>> userOpp = new Map<Id, Set<Id>>(); // Collection of EntitySubscriptions to follow our record List<EntitySubscription> subscriptions = new List<EntitySubscription<>(); // Sets collection of users based on the Opportunity as the parent / key. for(Team_Member__c tm : trigger.new){ //This section of code is to keep track of the Oppornity and it's team members. Set<Id> members = new Set<Id>(); if(userOpp.containsKey(tm.Opportunity__c)){ members = userOpp.get(tm.Opportunity__c); } members.add(tm.User__c); // Recreate our Map to hold our proper Values userOpp.put(tm.Opportunity__c, members); } // loop through our Opp map so we can force follow all of the associated team members for(Id t : userOpp.keySet()){ for(EntitySubscription es : ChatterUtils.addFollowers(userOpp.get(t), t)){ subscriptions.add(es); } } if(subscriptions.size() > 0){ system.debug('list of subscriptions: ' + subscriptions); Database.insert(subscriptions, false); }

 

ChatterUtils Class:

static public List<EntitySubscription> addFollowers(Set<Id> userIds, Id objectToFollowId) {
    EntitySubscription[] es = new List<EntitySubscription>();
    for (Id userId : userIds) {
         EntitySubscription e = new EntitySubscription();
         e.subscriberId = userId;
         e.parentId = objectToFollowId;
         es.add(e);
    }
    return es;
}

 

Any help will be greatly appreciated.

 

Hi there,

 

I've been developing in Salesforce for a few months now, and long story short... I've been using Salesforce's SOAP API since Version 15, and currently using Version 20 with the Partner WSDL. Within the last few weeks I've noticed an issue with how Salesforce changed their back-end structure when accessing data from record that contains formula fields.  I've tried talking to salesforce development support team with no results other than extending the timeout per Salesforce Org.

 

This "bug" is happening when dealing with an object that has over 2 million records, and pulling back the oldest record within that object with all of its fields. But, if I exclude the formula field, the query is always successful, and I'm able to retrieve at least 100k records using the queryAll, and queryMore webService. So my question is how else can I get all of my data, without having knowledge of what the date is of my oldest record.

 

Example of query:

SELECT * FROM <objectName> WHERE LastModifiedDate >= '1993-02-23T00:00:00Z' ORDER BY LastModifiedDate LIMIT 1

 

In theory I would like to get this working with queryAll, so I could query more than 1 record, maybe 100k records and using the queryMore webService call to get data in smaller sets.

 

Please help.

I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:

     "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false

As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?
I have a constant variable class for parsing out xml stucture on callouts as seen below. Problem is the way code is covered has changed it seems. Any idea why and/or how to fix this?

 
public with sharing class XMLElementNodeNames {
  public static final String CATEGORY_TAG = 'category';
  public static final String CATEGORIES_TAG = 'categories';
  public static final String ID_TAG = 'id';
  public static final String SCORE_TAG = 'score';
  ...
  static testmethod void testAll() {
// only having the following line would cover the class. Now it returns with 0% coverage
XMLElementNodeNames x = new XMLElementNodeNames();

// I have since added the following to try for code coverage to no avail.
String theString;
theString = CATEGORY_TAG;
theString = CATEGORIES_TAG;
theString = ID_TAG;
theString = SCORE_TAG;
....
  }
}

I'm having an issue with standard rendering. Within the 'Action' column, the checkbox next to the 'Edit' and 'Delete' links appears on some Sobjects and not others. Example would be in one Sandbox both Account and Leads works fine and you can see it on both. On other sandboxes only one works. I was hoping when pushing it to production I would be lucky enough to have it work, but alas, it did not. Works great on Leads when it came to Account, I had a no go.

 

 

VF code:

<apex:page showHeader="true">
    <apex:ListViews type="Account">
    </apex:ListViews>
</apex:page>

 

Short version of my question, how can I make this standard checkbox appear?

http://i.imgur.com/90UUEn2.png

 

 

 

Only possible solutions I've found online are:

Validating under Setup > Customize > User Interface
        Validate 'Enhanced Lists' and 'Inline Editing' is enabled.

Also If you have record types and in the list view you have more than one record types, you will lose the checkbox.
Try create a list view which contains only ONE record type.
so use a filter
account record type = xxx
and set your other filters.

 

 

I have tried both these with no luck. Please help!

Hi All,

     I am making a POC to get the feel of encrytion/decrytion of fields in salesforce using apex. Her are my requirements.

 I have a custom object say XYZ__c with field say ABC__c. I want to enter this field in a visual force page , hit encrypt button(command button) that runs the apex code and display encryted text in the output field of the page. Can anyone please help me with the code.

 

Thanks

Shrey Tyagi

Hi All,

 

I have one special requirment just Suppos I have three objects, Specimen, Tests and  SpecimenTest, now On VF page I am  getting specimen Fields and on the Selection of any other object I am getting mulitple tests means more than 1. No if I click on save than  in SpecimenTest  object Multiple tests which I got should be save with Single specimenID  ( where Specimen and Test object has relation as look up relation in SpecimenTest object ).

 

So result will be If SpecimenID = 00001 and TestIDs are 00001, 00002, 00003 than in SpecimenTest table records will be like

 

SpecimenTest  SpecimenID  TestID

00001                  00001              00001

00002                  00001              00002

00003                  00001              00003

 

 

Please help Me in this,, Thanks in Advance

 

Regards

Raman

Hello All,

 

Our support agents our requesting a "Custom Button" on the Case E-Mail template.  What they would like is the ability to click a "Send E-Mail and Close Case" button.  Once clicked the e-mail would be sent to the customer and the agent would be redirected to the Case Close page.

 

Has anyone tackled a similar request?  I am a novice to Apex Code and Visualforce, so any assistance is greatly appreciated.

 

Thanks,

Hello,

 

I'm fairly new to writing apex. I've written the following code to update the status of the case to match that of another dropdown(JIRA_Status2__c) on the case.  This trigger should only fire when JIRA_Status2__c changes and if the recordtype matches.

 

The code works, but I would like to know if I've written too much to achieve such a basic update.  Thanks for the input in advance. It wil help me to learn how to code better in the future.

trigger UpdateJiraOnlyRT on Case (after update) {

    //create list of case IDs
    List<ID>cid = new List<ID>();
   
    
    
    //add cases to list for only cases that has JIRA Status2 dropdown changed AND recordtype=012A00000017NFl

    for (Case c: Trigger.new){
        Case oldCase = Trigger.oldMap.get(c.Id);
        if((oldCase.JIRA_Status2__c != c.JIRA_Status2__c) && (c.RecordTypeID=='012A00000017NFl')){
            cid.add(c.ID);}
    }
  
   //update the list  
    List<Case>updatecase =[SELECT Id, Status, JIRA_Status2__c from Case WHERE Id IN:cid];
    for(Case c2:updatecase){
        c2.Status = c2.JIRA_Status2__c;
    }
    
    update updatecase;
        
}

 

 

What is use of name space ? 

can i remoove it  ?

where it is  manditory ?    can any one send me .............

Hi. I have a trigger that triggers for more records than I hope for

 

trigger createOrderforABFSCB on Stem_Cell_Bank__c (after update) {

    List<ChargentOrders__ChargentOrder__c> co = new List<ChargentOrders__ChargentOrder__c>();  
   
  for (Stem_Cell_Bank__c scb : Trigger.new) {

    if (scb.Stage__c == 'Stem Cells Banked') { /*scb to oscb*/
      
      //initiate the object to put values for furture record
      ChargentOrders__ChargentOrder__c c = new ChargentOrders__ChargentOrder__c();

      //map Order fields to SCB that is being created for this Order
      c.Stem_Cell_Bank__c = scb.Id; /*scb to oscb*/

          c.ChargentOrders__Date__c = date.today();
          c.Order_Item__c = 'Yearly Stem Cell Banking Fee';
      
      if(scb.Stem_Cells_Banked_Date__c!=null)
        c.ChargentOrders__Payment_Start_Date__c = scb.Stem_Cells_Banked_Date__c.addYears(1);
      else
        scb.addError('Cannot have empty stem cell bank date before stage is set to stem cell banked');
          
      //add this new object to the list that would be inserted later
      co.add(c);
    } //end if
  } //end for scb
  
  //once the loop is done, insert the new record to Order
  try{
    insert co;
  } catch (system.Dmlexception e) {
    system.debug(e);
  }

}

This seems to add a new record for all records with stage__c = 'Stem Cells Banked'

 

I need to add a new ChargentOrder record for existing Stem_Cell_Bank__c record only to the respective ID when Stage__c is updated to 'Stem Cells Banked'

 

I tried researching more about using oldMap and played around with the logic:

 

Stem_Cell_Bank__c oscb = Trigger.oldMap.get(scb.ID);

 

But having a hard time getting it work. Plus if I could add a checksum logic to only allow 2 ChargentOrder records to 1 Stem_Cell_Bank record it will help even more to not encounter these type of errors in the future

 

Any suggestions would be greatly appreciated

 

Thank you in advance

 

Daniel

Hello,

 

I am still very new to APEX.  I am trying to develop a simple visualforce page that lists all the accounts the active user owns.  Ideally, the user should be able to edit and save the records.  When the user clicks save, the record in the database should update.  Currently, the edit and save buttons do not work but I can make changes when double clicking but they do not save.  Any help is greatly appreciated.

 

My code so far:

 

*********************Visualforce page************************

 

<apex:page controller="MyController" >
     
      <apex:form >
     
        <apex:pageBlock title="My Accounts">
       
           
                <apex:pageblocktable value="{!myaccounts}" var="acct">
                    <apex:column value="{! acct.name}"/>
                    <apex:column value="{! acct.Preferred_Mode_S__c}"/>
                    <apex:column value="{! acct.type}"/>
                     <apex:inlineEditSupport event="ondblclick"/>
                  
                </apex:pageblocktable>
                <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandbutton value="Edit" action="{!edit}"/>
        </apex:pageblock>
  </apex:form>
</apex:page>

 

 

*****************************Controller*****************************

 

public class MyController {

         public List<Account> getMyAccounts(){        

List<Account> a = new List<Account>();        

a = [select Id,name,type,preferred_mode_s__c,macro_industry__c,micro_industry__c from Account WHERE (owner.id =: userinfo.getuserid())];            

return a;           

}   

 

public PageReference edit() {        

return null;    

}

    public PageReference save() {        

return null;    

}

}        

I have a custom object called Car_Class__c and in it I have used a multi-select picklist to create a table of values in a field called Make__c for different vehicle makes. (i.e. Buick; Chevrolet; Chrysler; Dodge; Fiat; Ford; GMC; Honda; Hyundai; Isuzu; Jeep; Mazda; Mercury; Mitsubishi; Nissan; Oldsmobile; Plymouth; Pontiac; Ram; Saturn; Scion; Suzuki; Toyota;)

The same Car_Class__c object has fields called Class_c, Product_Group__c, and Insurer_c, and the Class_c field is meant to be based on the vehicle make for certain situations, like if Insurer = VS AND Product Group = MPP then Buick = Class 1, and in that same situation if it was an Acura then = Class 2, etc.).  What I'm having trouble with is taking user input from a field called Vehicle_Make__c from a drop down list and comparing it with the values in the multi select list, so if anyone can offer a suggestion on how to fix this I would be grateful.  This is what I have been trying so far, where the 'I' and "prod' variables are taken from earlier calculations involved in other things so I know they're right and the cl and cl2 are public lists of the Car_Class__c object:

Public String getClass(){
        cl = Database.query('SELECT Make__c FROM Car_Class__c WHERE Insurer__c =:I AND Product_Group__r.Name =: prod');
        List<String> avC = New List<String>();
        for(Integer i=0; i < cl.size(); i++){
        avC.add(cl[i].Make__c);
        }
        String strList = String.valueOf(avC);
        List<String> c = strList.splitByCharacterTypeCamelCase();
        if (strList != null){
        cl2 = [SELECT Class__c FROM Car_Class__c WHERE (Insurer__c =:I) AND (Product_Group__r.Name =: prod) AND (Make__c IN:c)];
        contract.Class__c = string.Valueof(cl2[0].Class__c);
        }
        return contract.Class__c;    
                            }

 So far this returns an List index out of bounds:0 error.

Hi Friends, 

 

I am sending an email based on template. I want to count the number of times emails are count successfully.

 

As you can see here:

 

 

try {
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
     Messaging.SendEmailResult[] mailResult = Messaging.sendEmail(new      
Messaging.SingleEmailMessage[] { mail }); if ( !mailResult[0].isSuccess() )
{ EmailFailure = 'Email Failed: ' + mailResult[0].getErrors()[0].getMessage() +' \n \n'; } else { EmailCounter.Emails_sent_from_apex__c = EmailCounter.Emails_sent_from_apex__c +
Number_Of_Recipients ; update EmailCounter; } } catch(System.EmailException emlEx)
{ EmailFailure = 'we got here: ' + emlEx+' \n \n'; }

The surprising thing is that I do get the email as expected BUT an  Email exception is till thrown. As a result my counter is not updated, even though an email was sent. 

 

The Email exception received is:  System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_FIELD_WHEN_USING_TEMPLATE, When a template is specified the plain text body, html body, subject and charset may not be specified : []

 

Just to make is clear - I am NOT using :text body, html body, subject and charset.

 

Why do I get this exception ?

 

Please Help :)

 

Eyal

 

  • July 11, 2013
  • Like
  • 0