+ Start a Discussion
Ap30Ap30 
Hello All,
In standard view we should see only one record at a time. On clicking next button, it should show another single record. Record shown first should not be there. I couldn't implement as i'm new to pagination concept.Please help.

<apex:page standardController="obj__c" extensions="contollername">
 <apex:form >
    <apex:pageBlock title="Student's Data">
  
           <apex:pageBlockTable value="{!listitem}"  var="sd">
            
          <apex:column value="{!sd.First_Name__c}"/>
          <apex:column value="{!sd.Last_Name__c}"/>
          <apex:column value="{!sd.Company__c}"/>
             
                        
            </apex:pageBlockTable>
            <apex:pageBlockButtons >
    <apex:commandButton action="{!previous}" value="Prev"/>
      <apex:commandButton action="{!next}" value="Next"/>
    </apex:pageBlockButtons>
           
       </apex:pageBlock>
   </apex:form>
</apex:page> 

======================
public class contollername
{
    public transient List<obj__c> listitem{get; set;}
    public Integer size {get; set;}

    public contollername(ApexPages.StandardController stdController) {

         size=1;
         setLists();
    }

    public void setLists()
    {
       listitem= [Select First_Name__c,Last_Name__c,Company__c From obj__c limit:size];
    }

   public void next()
   {
      
      setLists();
   }
   
   public void previous()
   {
      
      setLists();
   }
}
Best Answer chosen by Ap30
PriyaPriya (Salesforce Developers) 
Hi,
 

Check below example that matches your requirement :- 

https://developer.salesforce.com/forums/?id=906F0000000BZxWIAW

Please mark as Best Answer so that it can help others in the future.

Regards,

Priya Ranjan


 
Rafi RafiRafi Rafi 
Hi,
I have a requirement I don't know how to get it, Q)ABC containers require the ability to automatically associate a contact created in their salesforce instance with the respective account based on the email domain specified in the primary email address of the contact. The association should happen in real-time as soon as a contact record is created within the system. 1)Develop the necessary piece of apex code to implement a solution 2)necessary test code(with 90% of code coverage)
Thanks in advance,
Rafi
Best Answer chosen by Rafi Rafi
ANUTEJANUTEJ (Salesforce Developers) 
Hi Rafi,

Please try the below snippet.
 
trigger auto_Account_assignment on Contact(before insert) {
    Set<String> emailDomains = new Set<String>();

    for (Contact l : Trigger.New) {
        if (l.Email == null) {
            continue;
        }   

        emailDomains.add(l.Email.split('@').get(1));
    }

    emailDomains.remove(null);
           
    if (!emailDomains.isEmpty()) {
        Map<String, Account> emailDomainToAccountMap = new Map<String, Account>();

        for (Account a : [ 
            select Name,
                Id
            from Account
            where Name in :emailDomains
        ]) {
            emailDomainToAccountMap.put(a.Name, a);
        }   

        for (Contact l : Trigger.New) {
            if (l.Email == null) {
                continue;
            }

            String domain = l.Email.split('@').get(1);

            if (!emailDomainToAccountMap.containsKey(domain)) {
                continue;
            }

            l.AccountId= emailDomainToAccountMap.get(domain).Id;
        }
    }
}
 
@isTest
private class AccountTestClass {
 static testMethod void validateAId() {
Account a= new Account();
a.name='test';
//I am adding only the name but please add all the required fields so that above account record is properly inserted
insert a;
Contact tempc = new contact();
tempc.LastName='TestContact';
tempc.email='primary@test.com';
insert tempc;
Id AI= a.id;
Contact check=[select id,accountid from contact where id in :AI];
system.assert(check.AccountId,AI);
 }
}

Please be noted that the above is a sample snippet and you need to make changes accordingly.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
gbalakrigbalakri 

I am trying to execute the following code for recalling an approval process an ends up getting the following error

 

 

execution of AfterUpdate caused by: System.DmlException: Process failed. First exception on row 0; first error: INVALID_OPERATION, Illegal transition type:

 

 Approval.ProcessWorkItemRequest pwr = new Approval.ProcessWorkItemRequest();
       
List<ProcessInstance> procins = new List<ProcessInstance>([select Id from ProcessInstance where Status = 'Pending' and TargetObjectId = :objectId]);
// Retrieve the process work instance id associated to the process instance
            List<ProcessInstanceWorkitem>  workitem = new List<ProcessInstanceWorkitem>([select Id from ProcessInstanceWorkitem where ProcessInstanceId = :procins[0].id]);

            if ((workitem != null) && (workitem.size() > 0))
            {
                pwr.SetComments(statusToUpdate);

                pwr.setWorkItemId(workitem[0].id);
                pwr.setAction('Remove');
            
               
                // Execute process request
                Approval.ProcessResult pr = Approval.process(pwr);

}

Best Answer chosen by Admin (Salesforce Developers) 
jlojlo

 gbalakri - Try changing this line:

 

pwr.setAction('Remove');

 to this:

 

 

 

pwr.setAction('Removed');

 

 

See the docs: http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content%2Fapex_ProcessWorkitemRequest.htm|SkinName=webhelp

Message Edited by jlo on 04-08-2009 12:07 PM
Tobias Letzner 5Tobias Letzner 5 
Hii,
I want to simply find the number of Contacts linked with each account. So i use aggregate query for this. I want to debug Account name with number of contacts. But it shows "Field must be grouped or aggregated: Name" and i have already group it by accountid. 
My query is given below-

list<sobject> totalContactVsAccount=[select count(id) totalContact,accountid,account.name from contact where  accountid!=null group by accountid limit 10000];
        for(sobject obj:totalContactVsAccount){
            system.debug(obj);
        }
Best Answer chosen by Tobias Letzner 5
Malika Pathak 9Malika Pathak 9

Hi Tobias Letzner,

When you want to find the field from the aggregate query you have to put that field in the group by clause separated by a comma.
Here I will show you how to do it.

list<sobject> totalContactVsAccount=[select count(id) totalContact,accountid,account.name from contact where  accountid!=null group by accountid,Account.name limit 10000];

Now, this query will work and find the account name as well, and if you want more account fileds the put those fields by comma-separated.

if you having a problem then Ask me 
Please mark Best Answer If Your Problem Is Solved
thanks, Regards,
Malika Pathak

 

MAITREYEE DINGAREMAITREYEE DINGARE 
Hello All,
I am new to development. I have written a trigger to add a newly created product into the standard price book. But while deployment to PROD, it is failing because of 0% code coverage.
Could you please help me here?
Following is my trigger:
trigger createPriceBookEntry on Product2 (after insert) {
    
    List<priceBookEntry> priceBookEntryList= new List<priceBookEntry>();
    
    String pricebkId= [SELECT id from Pricebook2 where isStandard=true][0].Id;
    
    for(Product2 prod: trigger.new){      
        priceBookEntry priceBkEntry= new priceBookEntry();
        priceBkEntry.Product2Id= prod.Id;
        priceBkEntry.Pricebook2Id= pricebkId;
        priceBkEntry.IsActive= True;
        priceBkEntry.UnitPrice= 0; // Dummy Value
        priceBkEntry.UseStandardPrice= False;
        priceBkEntry.External_ID__c = prod.MSOFT_Artikelnummer__c;
        //Add more fields as per requirement
        
        priceBookEntryList.add(priceBkEntry);
    }
    
    if(priceBookEntryList.size()>0)
    {
        insert priceBookEntryList;
    }
}
Following is the test class:
@isTest
public class TestQuoteLineItem
{  
    Static testmethod void insertRecord()
   	{
        priceBookEntry priceBkEntry= new priceBookEntry();
       
        priceBkEntry.Pricebook2Id= '01s09000003qN9eAAE';
        priceBkEntry.IsActive= True;
        priceBkEntry.UnitPrice= 0; // Dummy Value
        priceBkEntry.UseStandardPrice= False;
        priceBkEntry.External_ID__c = 'test';
        priceBkEntry.Product2Id = '01t1l000005CY2aAAG';
        //Add more fields as per requirement
            
        insert priceBkEntry;
       
       //system.assertequals(priceBkEntry.Pricebook2Id,priceBkEntry.Pricebook2Id);
       //System.debug('My debug message: ' + priceBkEntry.Product2Id);
   }
}
Thank you so much for your help in advance!
Best Answer chosen by MAITREYEE DINGARE
veer soniveer soni
Hi ,
try following test class with 100%  code coverage.
@isTest
public class createPriceBookEntryTest {
    @isTest
    static void test(){
        List<Product2> prodList=new List<Product2>();
        prodList.add(new Product2( Name='Test 1', IsActive=true,MSOFT_Artikelnummer__c = 'test 1'));
        prodList.add(new Product2( Name='Test 2', IsActive=true,MSOFT_Artikelnummer__c = 'test 2'));
        
        // get Pricebook2 Records
        Pricebook2 standardPricebook = new Pricebook2(
            Id = Test.getStandardPricebookId(),
            IsActive = true  );
        Update standardPricebook;
        
        Test.startTest();
        if(prodList.size() > 0){
            insert prodList;   
        }
        Test.stopTest();
        
        
        System.assertEquals(2,prodList.size());
        
        
    }
    
}

let me know if it helps you and don't forget to marking it as best so that it can help to others in future.
Thank you
Shahab KhanShahab Khan 
Hi,

I have a number field (Number, 0) but when i put valuee 10000 in it it will diplay it as 10,000 i want to display it without comma.
I have selected number field because i need to select Max number from it and add 1 in Max number for new entry.
Can any body help me how i can do it.

Thanks,
Faraz
Best Answer chosen by Shahab Khan
Grazitti TeamGrazitti Team
Hi Shahab,

Create a new custom field, where type is "formula" and the formula return type is "text".

In the formula, use the TEXT() function, and pass the existing number field value into this formula. For example, if your number field is MyNumber_c then your formula would be: TEXT( MyNumber_c )

Your users will enter values into the existing number field, but you can use the formula field (which doesn't display thousands separators)


And don't forget to mark this answer as best, if answer this helps you :-)


--
Regards,
Grazitti Team
Web: www.grazitti.com
davehilarydavehilary 

I am getting a ‘Regex too complicated’ error below when loading data into our org using the following process:

 

1) an email service to receive the CSV data,

2) an APEX class to split and validate the CSV data, and then

3) a set of @future calls to upsert the data.

 

The same data works in smaller volumes, but not beyond a certain threshold. This applies whether we reduce the number of rows, or reduce the width of certain columns of data by truncating them to 3000 characters (a small number of columns have 10,000 characters of text included). When we do either or both of these steps in any combination to reduce the file size, we don't get this problem. It’s not a problem with a specific badly formatted row either, because reducing the number of rows in various combinations always causes the problem to go away.

 

So we don’t believe it is actually a regex problem, because the regular expression is just finding commas to split up a comma separated file/string - i.e. it's very simple.

 

This is why we think there's an undocumented storage or capacity limit somewhere within the APEX processing that is being exceeded - but one that doesn't have a governor limit associated with it, or indeed an accurate error message. We think it is an erroneous error message - i.e. it's not to do with complicated regex – and that this error message is a symptom of another issue.

 

This error has occurred in code that has been stable to date, but has appeared since the filesize we're uploading has increased to beyond about 4600-4800KB, which seems to be the threshold beyond which this problem occurs. There seem to be some undocumented limits in the volume of data than can be processed using the solution architecture we've designed.

 

We want to be able to code around this problem, but unless we know exactly what the error is, any changes we make to our code may not actually fix the problem and result in wasted effort. So I don't want to start changing this until I know exactly which part of the solution needs to be changed!

 

I’ve raised this with Salesforce as a potential bug or to see if they could clarify any undocumented limits on processing large volume datasets using the process we’ve designed, but they seem to have decided it’s a developer issue so won’t help.

 

The error message is below:

 

Apex script unhandled exception by user/organization: 

Failed to invoke future method 'public static void PrepareCSV(String, String, String, Integer, Boolean)'

caused by: System.Exception: Regex too complicated

Class.futureClassToProcess.GetList: line 98, column 17
Class.futureClassToProcess.parseCSV: line 53, column 38
Class.futureClassToProcess.PrepareCSV: line 35, column 20 External entry point

 The relevant code snippet is below:

 

 

 

public static list<List<String>> GetList(String Content)
        {
        Content = Content.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
            Content = Content.replaceAll('""','DBLQT');
            List<List<String>> lstCSV = new List<List<String>>();
            Boolean Cont = true;
            while (Cont == true){
                List<String> lstS = Content.Split('\r\n',500);
                if(lstS.size() == 500){
                    Content =lstS[499];
                    lstS.remove(499);
                }else{
                    Cont = false;
                }
                lstCSV.add(lstS);
            }
            return lstCSV;
        }

 

Any suggestions gratefully received as to whether we're missing something obvious, whether 4MB+ files just can't be processed this way, or whether this might actually be a SFDC APEX bug.

 

 

 

public static list<List<String>> GetList(String Content)
        {
            //Sanjeeb
            Log('GetList started.');
            Content = Content.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
            Log('Replaing DBLQT.');
            Content = Content.replaceAll('""','DBLQT');
            Log('Replaing DBLQT.');
            List<List<String>> lstCSV = new List<List<String>>();
            Boolean Cont = true;
            while (Cont == true){
                List<String> lstS = Content.Split('\r\n',500);
                Log('Split upto 500 Rows.');
                //List<String> lstS = Content.Split('\r\n',1000);
                if(lstS.size() == 500){
                    Content =lstS[499];
                    lstS.remove(499);
                }else{
                    Cont = false;
                }
                lstCSV.add(lstS);
            }
            Log('GetList ends.');
            return lstCSV;
        }
Best Answer chosen by Admin (Salesforce Developers) 
davehilarydavehilary

I got a response from my SFDC ISV partner technical support representative which I thought I'd post back to my own question since it's the only 'official' word I've received on this problem. He said:

 

"I’ve been doing some digging and the regex too complicated message is definitely based on the size of the files.  It looks like Email Services provides an entry point that allows developers to push in data sizes that far exceed the heap limits. The regex seems to be failing because of the heap supporting the regex. The only alternative is to cut the file sizes down or choose another integration approach."

 

He said this wasn't likely to change in the next release, although I still maintain it should provide a more meaningful error message.

 

In our use case, this means completely redesigning our integration solution. For anyone else, you should reconsider Email Services if you have large varying attachment sizes to be processed.

Omi DeshmaneOmi Deshmane 
I have Two List of object records.
List<Account> accList1 = {1st record, 2nd record, 3rd record, 4th record};
List<Account> accList2 = {1st record, 3rd record};
 
I have another List<Account> accList3 = new List<Account>()
now I want to compare both List list1 and list2, get the record from list1 which is not present in list2 and add to List3.
 
Best Answer chosen by Omi Deshmane
edralphedralph
//assuming that accList1 and accList2 already exist...
List<Account> accList3 = new List<Account>();

for(Account acc1:accList1) { //for each account in accList1...
  if(!accList2.contains(acc1)) accList3.add(acc1); //if list2 does not contain the item from list1, add it to list3
}

//do whatever with accList3

Something like this would work.
balajibondarbalajibondar 
I want to convert DateTime Value to Date Value , Please help me out ????????????
Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert
Try taking the Year, Month, and Day values out of the DateTime variable and pass them into the Date.newInstance() method.

Here is some psuedo-code:

DateTime dT = System.now();
Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());


Daniel RetaleatoDaniel Retaleato 
I need to get the name of the current app in the controller. So far I'm trying:
public static String getAppName() {
         UserAppInfo userAppInfo = [SELECT Id, AppDefinitionId FROM UserAppInfo WHERE UserId = :UserInfo.getUserId() LIMIT 1];
        AppDefinition appDefinition = [SELECT DurableId, Label FROM AppDefinition Where DurableId = :userAppInfo.AppDefinitionId LIMIT 1];
       return appDefinition.Label;
    }
But Im getting 3 errors:

Line 1: No such column 'AppDefinitionId' on entity 'UserAppInfo'
Line 2: Invalid type: AppDefinition
Line 3: Variable does not exist: appDefinition

Can anyone provide some insight as to what I may be doing wrong? Thanks!
Best Answer chosen by Daniel Retaleato
Khan AnasKhan Anas (Salesforce Developers) 
Hi Daniel,

Greetings to you!

Your code looks good to me. Make sure you are using API version 43.0 or later. As per the Salesforce doc, AppDefinitionId field on UserAppInfo object and AppDefinition object are available in API version 43.0 and later.

Please refer to the below links which might help you further.

https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_userappinfo.htm

https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_appdefinition.htm

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas