+ Start a Discussion
AddaAdda 

Truncating Text on Apex Code or Visualforce PAge

Hi,

I have written a fucntionality to convert lead to case. The only problem is I have a field on Lead as Web-to-Lead Notes which is Text Area long and that is being popualated on Case Subject on Conversion. It gives error if the length is big. So I need to truncate the length of Lead to Web Notes field to 50 to properly fit in the Case Subject. Please help. Here is my code VFP and Apex:

Visualforce Page:
<apex:page standardController="Lead" extensions="CaseConverter">
    <apex:form >
        <apex:pageBlock title="Convert information to a new Case.">
            <apex:pageBlockButtons >
                <apex:commandbutton action="{!createCase}" value="Finish"/>
                <apex:commandbutton action="{!returnToLead}" value="Previous"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Lead content Section">            
                <tr><th class="labelCol vfLabelColTextWrap " scope="row">Lead Record Type</th><td class="dataCol "><span id="j_id0:j_id1:j_id2:j_id6:nameId">{!recordTypeName}</span></td></tr>
                <apex:outputText value="{!lead.Web_To_Lead_Notes__c} " rendered="true"/>
                <apex:outputField value="{!lead.Name}" id="nameId"/>
                <apex:outputField value="{!lead.Company}" id="companyId"/>
                <apex:outputField value="{!lead.Phone}" id="phoneid"/>
                <apex:outputField value="{!lead.City}" id="cityId"/>
                <apex:outputField value="{!lead.Street}" id="streetId"/>
                <apex:outputField value="{!lead.Country}" id="countryid"/>
                <apex:outputField value="{!lead.Email}" id="emailid"/>
                <apex:outputField value="{!lead.PostalCode}" id="postalId"/>
                <apex:outputField value="{!lead.MobilePhone}" id="mobileId"/>
                <apex:outputField value="{!lead.Website}" id="websiteId"/>
                <apex:outputField value="{!lead.Description}" id="descriptionId"/>
                <apex:outputField value="{!lead.Industry}" id="industryId"/>                           
            </apex:pageBlockSection>
            
         
   Apex Class:
public with sharing class CaseConverter {
    public Lead curLead{set;get;}
    private final String name;
    private final String company;
    private final String phone;
    private final String city;
    private final String street;
    private final String country;
    private final String email;
    private final String postal;
    private final String mobile;
    private final String website;
    private final String description;
    private final String industry;
    private final String leadId;
    public String Web_To_Lead_Notes_Case;
    public string accountOwnerId;
    
    //getter,setter for the selected list values
    public String statusCaseSelected{get;set;}
    public String originSelected{get;set;}
    
    //getter,setter for the input fields
    public String subjectInput{get;set;}
    
    //getter,setter for the input fields
    public String recordTypeName{get;set;}
    
    //getter setter for the checkboxes
    public Boolean createAccount{get;set;}
    
    /*get the select options from the case system schema for the status field
    * Input: nothing
    * Output: List of the select options from case status
    */
    public List<Selectoption> getStatusCaseItems(){
        List<Selectoption> statusValues = new List<Selectoption>();
        Schema.Describefieldresult systemCaseStatus = Case.Status.getDescribe();
        for(Schema.Picklistentry plEntry : systemCaseStatus.getPicklistValues()){
            statusValues.add(
                new Selectoption(
                    plEntry.getValue(),
                    plEntry.getLabel()
                )
            );
        }
        return statusValues;
    }
    
    /*get the select options from the case system schema for the origin field
    * Input: nothing
    * Output: List of the select options from case origin
    */
    public List<Selectoption> getOriginItems(){
        List<Selectoption> originValues = new List<Selectoption>();
                 originValues.add(
                       new Selectoption(
                                'Customer Service','Customer Service'
                )
           );
                
        
        return originValues;
    }

    //constructor, this page will be called from the LeadToCase Page
    public CaseConverter(ApexPages.StandardController controller) {
        this.curLead= (Lead)controller.getRecord();
        List<QueueSobject> lstQueues = [SELECT Id,queue.Name, QueueId FROM QueueSobject WHERE SobjectType = 'Case'and queue.Name = 'Customer Service Cases'];
        curLead.OwnerId = lstQueues[0].QueueId;
        
        List<recordType> recordTypeList = [select Name from recordType where Id = :curlead.recordTypeId];
        if(recordTypeList.Size() > 0 ) {
            recordTypeName = recordTypeList[0].Name;
        } 
        this.name = curLead.FirstName + ' ' + curLead.LastName;
        this.company = curLead.Company;
        this.phone = curLead.Phone;
        this.city = curLead.City;
        this.street = curLead.Street;
        this.country = curLead.Country;
        this.email = curLead.Email;
        this.postal = curLead.PostalCode;
        this.mobile = curLead.MobilePhone;
        this.website = curLead.Website;
        this.description = curLead.Description;
        this.industry = curLead.Industry;
        this.leadId = curLead.Id; 
        this.Web_To_Lead_Notes_Case = curLead.Web_To_Lead_Notes__c;
        subjectInput = curLead.Web_To_Lead_Notes__c; 
       
    }
    
    
    
Best Answer chosen by Adda
sandeep sankhlasandeep sankhla
Hi Adda,

Please replace your code with this code and check and let me know ho wit works..because I hae created the same field and test the same and it is working fine for you even if it is blank..

if(curLead.Web_To_Lead_Notes__c != null)
               {
                   Integer Intlength = objCo.Web_To_Lead_Notes__c.length();
                   
                   if(Intlength >49 )
                    subjectInput = objCo.Web_To_Lead_Notes__c.substring(0,49);
                    else if(Intlength < 49)
                    subjectInput = objCo.Web_To_Lead_Notes__c.substring(0,Intlength);
                       
                   
                   
               }

Please check and let me know..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 

All Answers

AMIT KAMBOJAMIT KAMBOJ
Hi 
Change the line in class as below:
subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,49); 

If this helps please mark this answer as solution.
AddaAdda
Thanks it worked
AddaAdda
Hi Amit,

Sorry if the text is less than 50, I am getting this error. Please Help

Ending position out of bounds: 50 
 
AddaAdda
Also if the web to lead note field it empty, it gives error.. How it tackle that

Error:

Attempt to de-reference a null object 
An unexpected error has occurred. Your development organization has been notified.
sandeep sankhlasandeep sankhla
Hi Adda,

You can first do the null check for thise field and then proceed with calculation

Plese use this

if(curLead.Web_To_Lead_Notes__c!= null)
{
  subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,49); 

}

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
 
AddaAdda
Sandeep it worked if the size is null or size is greater than 49. When I try to test length less than 49, it throws me error. Pls help asap.

Error
Ending position out of bounds: 49 
sandeep sankhlasandeep sankhla
Hi Adda,

Can you paste your code how your tried ?

Thanks,
Sandeep
sandeep sankhlasandeep sankhla
Hi Adda,

You should check the field length first before substring, because if it is less than 49 and you are doing substring then it will surely throw an error..

In this sscenario what you can do, you can first check whatever is the length then you can substring based on that length..

Please try checking length first and then do substring..let me know if you need any help on this..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
AddaAdda
Here is the code. Pls help. Help me in case the condition with either 0 or less than 49.

this.leadId = curLead.Id; 
        if((curLead.Web_To_Lead_Notes__c!= null) || (curLead.Web_To_Lead_Notes__c.length() < 49))
        {
        subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,49); 
          }
        
sandeep sankhlasandeep sankhla
Hi Adda,

You can simply use below code:

this.leadId = curLead.Id; 
        if((curLead.Web_To_Lead_Notes__c!= null) || (curLead.Web_To_Lead_Notes__c.length() < 49))
        {
        subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,curLead.Web_To_Lead_Notes__c.length()); 
          }
 
Please check this, it will work for you..

The error was coming because length is less than 49 but it can be 4 and 5 and 34 which is less than 49..so in this case when you will do substring to (0,49)..where 49 does not exist so it will throw the error..

Please use above code , it will work ..
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 



 
AddaAdda
Sandeep it worked if the field is not blank. But if it is blank it is throwing me error and if the length is more than 49, it is not truncating and saying string too long. It is not working

Error: System.NullPointerException: Attempt to de-reference a null object 

Error: System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Error is in expression '{!createCase}' in component <apex:commandButton> in page leadtocase: Class.CaseConverter.createCase: line 171, column 1
 
sandeep sankhlasandeep sankhla
Hi Adda,

Please use below code it will solve your all issue..

this.leadId = curLead.Id; 

    if((curLead.Web_To_Lead_Notes__c!= null) && (curLead.Web_To_Lead_Notes__c!= '')&&(curLead.Web_To_Lead_Notes__c.length() < 49))
    {
        subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,curLead.Web_To_Lead_Notes__c.length()); 
    }
    else if(curLead.Web_To_Lead_Notes__c.length() > 49)
    {
        subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,49);
    }

from above code if it is not null, not blank and less then 49 then it will take entire string..if it is more than 49 then it will take till 49..
Please implement and let me know if it solves your issue..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
AddaAdda
Error : System.NullPointerException: Attempt to de-reference a null object 
Class.CaseConverter.<init>: line 92, column 1

If the field is blank, giving this error
sandeep sankhlasandeep sankhla
Hi Adda,

Can you paste your entire code here, so I can look into and help you out ?

Thanks,
Sandeep
AddaAdda
public with sharing class CaseConverter {
    public Lead curLead{set;get;}
    private final String name;
    private final String company;
    private final String phone;
    private final String city;
    private final String street;
    private final String country;
    private final String email;
    private final String postal;
    private final String mobile;
    private final String website;
    private final String description;
    private final String industry;
    private final String leadId;
    public String Web_To_Lead_Notes_Case;
    public string accountOwnerId;
    
    //getter,setter for the selected list values
    public String statusCaseSelected{get;set;}
    public String originSelected{get;set;}
    
    //getter,setter for the input fields
    public String subjectInput{get;set;}
    
    //getter,setter for the input fields
    public String recordTypeName{get;set;}
    
    //getter setter for the checkboxes
    public Boolean createAccount{get;set;}
    
    /*get the select options from the case system schema for the status field
    * Input: nothing
    * Output: List of the select options from case status
    */
    public List<Selectoption> getStatusCaseItems(){
        List<Selectoption> statusValues = new List<Selectoption>();
        Schema.Describefieldresult systemCaseStatus = Case.Status.getDescribe();
        for(Schema.Picklistentry plEntry : systemCaseStatus.getPicklistValues()){
            statusValues.add(
                new Selectoption(
                    plEntry.getValue(),
                    plEntry.getLabel()
                )
            );
        }
        return statusValues;
    }
    
    /*get the select options from the case system schema for the origin field
    * Input: nothing
    * Output: List of the select options from case origin
    */
    public List<Selectoption> getOriginItems(){
        List<Selectoption> originValues = new List<Selectoption>();
                 originValues.add(
                       new Selectoption(
                                'Customer Service','Customer Service'
                )
           );
                
        
        return originValues;
    }

    //constructor, this page will be called from the LeadToCase Page
    public CaseConverter(ApexPages.StandardController controller) {
        this.curLead= (Lead)controller.getRecord();
        List<QueueSobject> lstQueues = [SELECT Id,queue.Name, QueueId FROM QueueSobject WHERE SobjectType = 'Case'and queue.Name = 'Customer Service Cases'];
        curLead.OwnerId = lstQueues[0].QueueId;
        
        List<recordType> recordTypeList = [select Name from recordType where Id = :curlead.recordTypeId];
        if(recordTypeList.Size() > 0 ) {
            recordTypeName = recordTypeList[0].Name;
        } 
        this.name = curLead.FirstName + ' ' + curLead.LastName;
        this.company = curLead.Company;
        this.phone = curLead.Phone;
        this.city = curLead.City;
        this.street = curLead.Street;
        this.country = curLead.Country;
        this.email = curLead.Email;
        this.postal = curLead.PostalCode;
        this.mobile = curLead.MobilePhone;
        this.website = curLead.Website;
        this.description = curLead.Description;
        this.industry = curLead.Industry;
        
        this.leadId = curLead.Id; 
        if((curLead.Web_To_Lead_Notes__c!= null) && (curLead.Web_To_Lead_Notes__c!= '') && (curLead.Web_To_Lead_Notes__c.length() < 49))
          {
          subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,curLead.Web_To_Lead_Notes__c.length()); 
              }
          else if(curLead.Web_To_Lead_Notes__c.length() > 49)
          {
          subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,49);
            }
        
       
    }
    
    
    /* Exec after clicking the Finish Button
    *  Map the system lead fields to to the case description
    *  return the new case as page and delete the lead
    */
    public Pagereference createCase(){
        Case leadToCase = new Case();
        
        //reconstruct new owner information
        if(!((string)curLead.OwnerId).startsWith('00G')){
            accountOwnerId = curLead.OwnerId;
        } else{
            accountOwnerId = UserInfo.getUserId();
        }
        update curLead;
        system.debug('curLead---->'+curLead);
        List<Lead> updatedLeads = new List<Lead>([SELECT OwnerId FROM Lead WHERE id =:leadId limit 1]);
        List<recordType> recordTypeList = [select ID from recordType where sObjectType='Case' AND Name = 'Email to Case'];
        String newOenwerId = updatedLeads[0].OwnerId;
        system.debug('curLead43434---->'+updatedLeads[0].OwnerId);
        leadToCase.OwnerId = updatedLeads[0].OwnerId;
        system.debug('curLead9879---->'+leadToCase.OwnerId);

        //case without account/contact
        if(!createAccount){
            String combineContactInfos = '';
            if(name != null){
                combineContactInfos += 'Name: ' + name + '\r\n';
            }
            if(company != null){
                combineContactInfos += 'Company: ' + company + '\r\n';
            }
            if(phone != null){
                combineContactInfos += 'Phone: ' + phone + '\r\n';
            }
            if(mobile != null){
                combineContactInfos += 'Mobile: ' + mobile + '\r\n';
            }
            if(street != null){
                combineContactInfos += 'Street: ' + street + '\r\n';
            }
            if(city != null){
                combineContactInfos += 'City: ' + city + '\r\n';
            }   
            if(postal != null){
                combineContactInfos += 'Postal Code: ' + postal + '\r\n';
            }   
            if(country != null){
                combineContactInfos += 'Country: ' + country + '\r\n';
            }   
            if(website != null){
                combineContactInfos += 'Website: ' + website + '\r\n';
            }
            if(industry != null){
                combineContactInfos += 'Industry: ' + industry + '\r\n';
            }   
            if(description != null){
                combineContactInfos += 'Description: ' + description + '\r\n';
            }
            if(Web_To_Lead_Notes_Case != null){
                combineContactInfos += 'Web-to-Lead Notes: ' + Web_To_Lead_Notes_Case + '\r\n';
            }
              

            //set the required case information
            if(recordTypeList.Size() > 0 ) {
                leadToCase.recordTypeId = recordTypeList[0].Id;
            } 
            leadToCase.Description = combineContactInfos;
            leadToCase.Origin = this.originSelected;
            leadToCase.Status = this.statusCaseSelected;
            leadToCase.Subject = this.subjectInput;
            leadToCase.SuppliedEmail = this.email;
            system.debug('case44444---->'+leadToCase);
            insert leadToCase;  

        //case with account/contact
        }else{
            RecordType accountRecordTypeInfo = [SELECT Id FROM RecordType WHERE Name = 'Individual' AND SobjectType = 'Account'];
            RecordType contactRecordTypeInfo  = [SELECT Id FROM RecordType WHERE Name = 'IND Standard' AND SobjectType = 'Contact'];      
            //create the new account
            Account convAccount = new Account();
            convAccount.name = company;
            convAccount.Phone = phone;
            convAccount.OwnerId = accountOwnerId ;
            convAccount.Website = website;
            convAccount.RecordTypeId = accountRecordTypeInfo.id;
            insert convAccount;             
            
            //Create the contact and attach to the account
            Contact convContact = new Contact();
            convContact.AccountId = convAccount.Id;
            convContact.OwnerId = accountOwnerId;
            convContact.Phone = phone;
            convContact.MobilePhone = mobile;
            convContact.MailingCity = city;
            convContact.MailingStreet = street;
            convContact.MailingPostalCode = postal;
            convContact.MailingCountry = country;
            convContact.Email = email;
            convContact.RecordTypeId = contactRecordTypeInfo.id;
            List<String> subNames = name.split(' ',0);
            if(subNames.size() > 1){
                convContact.LastName = subNames[1];
                convContact.FirstName = subNames[0];
            }else{
                convContact.LastName = name;
            }
            insert convContact;
            
            //create the case and attach them to the new account
            if(recordTypeList.Size() > 0 ) {
                leadToCase.recordTypeId = recordTypeList[0].Id;
            } 
            leadToCase.Description = description; 
            leadToCase.Origin = this.originSelected;
            leadToCase.Status = this.statusCaseSelected;
            leadToCase.Subject = this.subjectInput;
            leadToCase.SuppliedEmail = this.email;
            leadToCase.AccountId = convAccount.Id;
            leadToCase.ContactId = convcontact.Id;            
            insert leadToCase;
        }
        
        //show the created case as new page and delete the lead
        Pagereference casePage = new Apexpages.Standardcontroller(leadToCase).view();
        casePage.setRedirect(true);
        delete curLead;
        return casePage;
    }
    
    /* Exec after clicking the previous button
    *  give the focus back to the list
    */
    public Pagereference returnToLead(){
        Pagereference leadPage = new Apexpages.Standardcontroller(this.curLead).view();
        leadPage.setRedirect(true);
        return leadPage;
    }
}
sandeep sankhlasandeep sankhla
Hi Adda,

Can you comment the code which I hev given, then check..because your code is very large and it seems you are using same field somewhere else and it is throwing the error from other place..so just to confirm that our code is throwing error, you can remove the code and check if error comes menas there is another place where we are refering teh same field else it is coming due to our code..Please can you quiclky confirm and it would be good if you can highlist the line number in code which is throwing the error..

Thanks
Sandeep
sandeep sankhlasandeep sankhla
Hi Adda,

You have not initalized your variables..

Please add this above my code..

 subjectInput = '';

After initalizing this can you check and let me know if it solves your issue..We should always initalize all variables in our constructor to avoid these type of errors.
In your case you have not initalized your variables which you are using pageside..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
AddaAdda
Adding subjectInput = ''; didn't help, same error

Removing your block of code is not throwing me error. This is your piece of code. May I will explain it better. 

Web to lead notes on lead needs to populated on case subject and description (2 places).If the length is more than 49, subject field can be truncated and only 49 character needs to be show  but on description the whole web to lead field needs to be shown.

This piece of code was working perfectly until I didn't realized the subject cannot take text area long. So, I thought of truncating it.

Thanks
Abhishek
sandeep sankhlasandeep sankhla
Hi Adda,

It will be very helpful if you can highlight the code or line number whihc is throwing error..or you can paste your code in code format by using <> this from bar..

Because we are doing null and blank check so it should not go inside any of the conidition and throw error..may b small thing we are missing so please highlight those..

Thanks,
Sandeep
AddaAdda
System.NullPointerException: Attempt to de-reference a null object 
Class.CaseConverter.<init>: line 94, column 1

This is pointing to  your code this

subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,curLead.Web_To_Lead_Notes__c.length()); 
sandeep sankhlasandeep sankhla
Hi Adda,

Can you replace above line with this line

if(!curLead.Web_To_Lead_Notes__c == ' ')
    subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,curLead.Web_To_Lead_Notes__c.length());  

Thanks,
Sandeep
AddaAdda
Error: Compile Error: NOT operator can only be applied to Boolean expressions at line 91 column 12
sandeep sankhlasandeep sankhla
Hi Adda,

Okay! give me sometime, let me have a look in depth if we are missing any small thing which is casuing the issue..

Thanks
AddaAdda
Sure take your time. Here is the full code.
public with sharing class CaseConverter {
    public Lead curLead{set;get;}
    private final String name;
    private final String company;
    private final String phone;
    private final String city;
    private final String street;
    private final String country;
    private final String email;
    private final String postal;
    private final String mobile;
    private final String website;
    private final String description;
    private final String industry;
    private final String leadId;
    public String Web_To_Lead_Notes_Case;
    public string accountOwnerId;
    
    //getter,setter for the selected list values
    public String statusCaseSelected{get;set;}
    public String originSelected{get;set;}
    
    //getter,setter for the input fields
    public String subjectInput{get;set;}
    
    //getter,setter for the input fields
    public String recordTypeName{get;set;}
    
    //getter setter for the checkboxes
    public Boolean createAccount{get;set;}
    
    /*get the select options from the case system schema for the status field
    * Input: nothing
    * Output: List of the select options from case status
    */
    public List<Selectoption> getStatusCaseItems(){
        List<Selectoption> statusValues = new List<Selectoption>();
        Schema.Describefieldresult systemCaseStatus = Case.Status.getDescribe();
        for(Schema.Picklistentry plEntry : systemCaseStatus.getPicklistValues()){
            statusValues.add(
                new Selectoption(
                    plEntry.getValue(),
                    plEntry.getLabel()
                )
            );
        }
        return statusValues;
    }
    
    /*get the select options from the case system schema for the origin field
    * Input: nothing
    * Output: List of the select options from case origin
    */
    public List<Selectoption> getOriginItems(){
        List<Selectoption> originValues = new List<Selectoption>();
                 originValues.add(
                       new Selectoption(
                                'Customer Service','Customer Service'
                )
           );
                
        
        return originValues;
    }

    //constructor, this page will be called from the LeadToCase Page
    public CaseConverter(ApexPages.StandardController controller) {
        this.curLead= (Lead)controller.getRecord();
        List<QueueSobject> lstQueues = [SELECT Id,queue.Name, QueueId FROM QueueSobject WHERE SobjectType = 'Case'and queue.Name = 'Customer Service Cases'];
        curLead.OwnerId = lstQueues[0].QueueId;
        
        List<recordType> recordTypeList = [select Name from recordType where Id = :curlead.recordTypeId];
        if(recordTypeList.Size() > 0 ) {
            recordTypeName = recordTypeList[0].Name;
        } 
        this.name = curLead.FirstName + ' ' + curLead.LastName;
        this.company = curLead.Company;
        this.phone = curLead.Phone;
        this.city = curLead.City;
        this.street = curLead.Street;
        this.country = curLead.Country;
        this.email = curLead.Email;
        this.postal = curLead.PostalCode;
        this.mobile = curLead.MobilePhone;
        this.website = curLead.Website;
        this.description = curLead.Description;
        this.industry = curLead.Industry;
                
        this.leadId = curLead.Id; 
        subjectInput = '';
        if(!curLead.Web_To_Lead_Notes__c == ' ')
          {
          subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,curLead.Web_To_Lead_Notes__c.length()); 
              }
          else if(curLead.Web_To_Lead_Notes__c.length() > 49)
          {
          subjectInput = curLead.Web_To_Lead_Notes__c.substring(0,49);
            }
        
        
       
    }
    
    
    /* Exec after clicking the Finish Button
    *  Map the system lead fields to to the case description
    *  return the new case as page and delete the lead
    */
    public Pagereference createCase(){
        Case leadToCase = new Case();
        
        //reconstruct new owner information
        if(!((string)curLead.OwnerId).startsWith('00G')){
            accountOwnerId = curLead.OwnerId;
        } else{
            accountOwnerId = UserInfo.getUserId();
        }
        update curLead;
        system.debug('curLead---->'+curLead);
        List<Lead> updatedLeads = new List<Lead>([SELECT OwnerId FROM Lead WHERE id =:leadId limit 1]);
        List<recordType> recordTypeList = [select ID from recordType where sObjectType='Case' AND Name = 'Email to Case'];
        String newOenwerId = updatedLeads[0].OwnerId;
        system.debug('curLead43434---->'+updatedLeads[0].OwnerId);
        leadToCase.OwnerId = updatedLeads[0].OwnerId;
        system.debug('curLead9879---->'+leadToCase.OwnerId);

        //case without account/contact
        if(!createAccount){
            String combineContactInfos = '';
            if(name != null){
                combineContactInfos += 'Name: ' + name + '\r\n';
            }
            if(company != null){
                combineContactInfos += 'Company: ' + company + '\r\n';
            }
            if(phone != null){
                combineContactInfos += 'Phone: ' + phone + '\r\n';
            }
            if(mobile != null){
                combineContactInfos += 'Mobile: ' + mobile + '\r\n';
            }
            if(street != null){
                combineContactInfos += 'Street: ' + street + '\r\n';
            }
            if(city != null){
                combineContactInfos += 'City: ' + city + '\r\n';
            }   
            if(postal != null){
                combineContactInfos += 'Postal Code: ' + postal + '\r\n';
            }   
            if(country != null){
                combineContactInfos += 'Country: ' + country + '\r\n';
            }   
            if(website != null){
                combineContactInfos += 'Website: ' + website + '\r\n';
            }
            if(industry != null){
                combineContactInfos += 'Industry: ' + industry + '\r\n';
            }   
            if(description != null){
                combineContactInfos += 'Description: ' + description + '\r\n';
            }
            if(Web_To_Lead_Notes_Case != null){
                combineContactInfos += 'Web-to-Lead Notes: ' + Web_To_Lead_Notes_Case + '\r\n';
            }
              

            //set the required case information
            if(recordTypeList.Size() > 0 ) {
                leadToCase.recordTypeId = recordTypeList[0].Id;
            } 
            leadToCase.Description = combineContactInfos;
            leadToCase.Origin = this.originSelected;
            leadToCase.Status = this.statusCaseSelected;
            leadToCase.Subject = this.subjectInput;
            leadToCase.SuppliedEmail = this.email;
            system.debug('case44444---->'+leadToCase);
            insert leadToCase;  

        //case with account/contact
        }else{
            RecordType accountRecordTypeInfo = [SELECT Id FROM RecordType WHERE Name = 'Individual' AND SobjectType = 'Account'];
            RecordType contactRecordTypeInfo  = [SELECT Id FROM RecordType WHERE Name = 'IND Standard' AND SobjectType = 'Contact'];      
            //create the new account
            Account convAccount = new Account();
            convAccount.name = company;
            convAccount.Phone = phone;
            convAccount.OwnerId = accountOwnerId ;
            convAccount.Website = website;
            convAccount.RecordTypeId = accountRecordTypeInfo.id;
            insert convAccount;             
            
            //Create the contact and attach to the account
            Contact convContact = new Contact();
            convContact.AccountId = convAccount.Id;
            convContact.OwnerId = accountOwnerId;
            convContact.Phone = phone;
            convContact.MobilePhone = mobile;
            convContact.MailingCity = city;
            convContact.MailingStreet = street;
            convContact.MailingPostalCode = postal;
            convContact.MailingCountry = country;
            convContact.Email = email;
            convContact.RecordTypeId = contactRecordTypeInfo.id;
            List<String> subNames = name.split(' ',0);
            if(subNames.size() > 1){
                convContact.LastName = subNames[1];
                convContact.FirstName = subNames[0];
            }else{
                convContact.LastName = name;
            }
            insert convContact;
            
            //create the case and attach them to the new account
            if(recordTypeList.Size() > 0 ) {
                leadToCase.recordTypeId = recordTypeList[0].Id;
            } 
            leadToCase.Description = description; 
            leadToCase.Origin = this.originSelected;
            leadToCase.Status = this.statusCaseSelected;
            leadToCase.Subject = this.subjectInput;
            leadToCase.SuppliedEmail = this.email;
            leadToCase.AccountId = convAccount.Id;
            leadToCase.ContactId = convcontact.Id;            
            insert leadToCase;
        }
        
        //show the created case as new page and delete the lead
        Pagereference casePage = new Apexpages.Standardcontroller(leadToCase).view();
        casePage.setRedirect(true);
        delete curLead;
        return casePage;
    }
    
    /* Exec after clicking the previous button
    *  give the focus back to the list
    */
    public Pagereference returnToLead(){
        Pagereference leadPage = new Apexpages.Standardcontroller(this.curLead).view();
        leadPage.setRedirect(true);
        return leadPage;
    }
}
sandeep sankhlasandeep sankhla
Hi Adda,

Please replace your code with this code and check and let me know ho wit works..because I hae created the same field and test the same and it is working fine for you even if it is blank..

if(curLead.Web_To_Lead_Notes__c != null)
               {
                   Integer Intlength = objCo.Web_To_Lead_Notes__c.length();
                   
                   if(Intlength >49 )
                    subjectInput = objCo.Web_To_Lead_Notes__c.substring(0,49);
                    else if(Intlength < 49)
                    subjectInput = objCo.Web_To_Lead_Notes__c.substring(0,Intlength);
                       
                   
                   
               }

Please check and let me know..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
This was selected as the best answer
AddaAdda
Sandeep, It worked for now. I will do through testing tom and let you know for any problem. 
sandeep sankhlasandeep sankhla
Hi Adda,

Sure, please test throughly and let me know if you face any issue..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
AddaAdda
Thanks for help Sandeep you made my day. I have another question. I will post another question. If you can please reply to my post if you know the answer
sandeep sankhlasandeep sankhla
Hi Adda,

Yes, please post your question..

Thanks,
Sandeep
AddaAdda
Sandeep,

Here is another problem. We are using Case Feed on Cases. And part of the case is article managment. There is 2 views - Case Feed view and regular Case Details view. We can attach or create article from Case detail view. But we can only attach article from Case Feed but cannot create a new article. Do you have any idea how to create a Knowledge Article from the Case Feed view?

Thanks
Adda
AddaAdda
Hi Sandeep,

Can you help in a button using URL hacking. 


I need to create a button that whenever a contact is created from case automatically the case should be attached in the contact as a related list. So far I can came upto this but I am not able to pass the value from case to contact. Please help.

https://cs30.salesforce.com/003/e?retURL=%2F003n0000006N1WG&con4={!Case.Account}&con10={!Account.Phone}&{!Case.ContactId}={!Case.Id}&RecordType=012n00000008Wq0&ent=Case
 
Troy CenterTroy Center
Sandeep. Wanted to say thanks. This solved my problem + two days of sleep before I worked on this again. :-) Thanks. Upvoted best answer here. Troy ~ Seattle, USA.