• souvik9086
  • PRO
  • 4035 Points
  • Member since 2011
  • Souvik
  • Tata Consultancy Services


  • Chatter
    Feed
  • 118
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 28
    Questions
  • 1032
    Replies
Hello,

I am using a standard object (Campaign) to track attendence at events.  Working with the "Total Contacts" field (automatically updated when a contact is added to campaign) and a custom "No of Attendees" field, I'm trying to create an Apex Trigger that updates the Campaign record with the current number of attendees whenever that number changes.  

Goal:  Anytime "Total Contacts" changes, I want to pass that value to the "No of Attendees" field.  

Here's what I've tried so far:
trigger AttendeeUpdate on Campaign (before update) {
    for (Campaign obj: trigger.new){
        No_of_Attendees__c = TotalContacts;
    }
}

Error Message:Compile Error: Variable does not exist: No_of_Attendees__c at line 3 column 9

Any help with this is greatly appreciated!
Ok I am new to Apex, this should be easy  but I am not finding a good resource manual. I have a Apex trigger to send an form email whenever a case changes owner.
What I'd like to do is include a link to the orginal case.

Here is what I think is the relevant lines as they exist

mail.setSubject('You are now the Owner of Case#:'+Trigger.new[i].CaseNumber);
                  mail.setPlainTextBody('Ownership of Case#:'+Trigger.new[i].CaseNumber+' has been set to you. Have a Nice Day.');

so I need to change this from plain text and include a field from the case containing the threadID so it'll link back to the case.
can that field be included?
Hi All,

I am trying to create test code for the Milestone Utilities Class, Trigger on Case Comment, Trigger on Email Message that has been published at

https://developer.salesforce.com/index.php?title=Auto-completion_of_Case_Milestones_with_Triggers&oldid=33636&language=en

The code I have found that I thought would complte this but could be totally wrong is 

@istest

public class CompleteMilestone{
 
  // test methods
  static testMethod void testCompleteMilestoneCase(){
   
    Contact oContact = [select id from Contact limit 1];
    String contactId;
    if (oContact != null)
      contactId = oContact.Id;
   
    Entitlement entl = [select id from Entitlement limit 1];
    String entlId;
    if (entl != null)
      entlId = entl.Id;
   
    List<Case> cases = new List<Case>{};
    if (entlId != null){
      Case c = new Case(Subject = 'Test Case with Entitlement ', EntitlementId = entlId, ContactId = contactId);
      cases.add(c);
    }
   
    // Insert the Account records that cause the trigger to execute.
    if (cases.isEmpty()==false){
      insert cases;
      List<Id> caseIds = new List<Id>();
      for (Case cL : cases){
        caseIds.add(cL.Id);
      }
      milestoneUtils.completeMilestone(caseIds, 'Response MAC', System.now());
        }
    }
 
    static testMethod void testCompleteMilestoneViaCase(){
     
        // Perform data preparation
        Entitlement entl = [select id from Entitlement limit 1];
        String entlId;
        if (entl != null)
            entlId = entl.Id;
        List<Case> cases = new List<Case>{};
        for(Integer i = 0; i < 1; i++){
            Case c = new Case(Subject = 'Test Case ' + i);
            cases.add(c);
            if (entlId != null){
                c = new Case(Subject = 'Test Case with Entitlement ' + i, EntitlementId = entlId);
                cases.add(c);
            }
        }
       
        // Insert the Account records that cause the trigger to execute.
        insert cases;

        List<CaseComment> ccs = new List<CaseComment>{};
        for(Case c : cases){
            CaseComment cc = new CaseComment(CommentBody='TestPublic', IsPublished=true, ParentId=c.Id);
            ccs.add(cc);
            cc = new CaseComment(CommentBody='TestPrivate', IsPublished=true, ParentId=c.Id);
            ccs.add(cc);
        }
        if (ccs.isEmpty()==false)
            insert ccs;
   
    // Now create emailmessage objects for them.
   
        List<EmailMessage> emails = new List<EmailMessage>();
        for(Case c : cases){
            emails.add(new EmailMessage(parentId = c.id));
        }
        if(emails.isEmpty()==false)
            database.insert(emails);
       
        for(Case c : cases){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddr = new String[] {'mramsey@salesforce.com'};
            mail.setToAddresses(toAddr);
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId(c.ContactId);
            mail.setWhatId(c.Id);
            mail.setHtmlBody('TestHTMLBody');
            mail.setPlainTextBody('TestTextBody');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
   
    for(Case c : cases){
      c.Status = 'Closed';
    }
    update cases;
   
        // Query the database for the newly inserted records.
        List<Case> insertedCases = [SELECT Subject,
                                           Description,
                                          (SELECT IsPublished, CommentBody From CaseComments),
                                          (SELECT TextBody, Subject, Incoming From EmailMessages)
                                           FROM Case
                                           WHERE Id IN :cases];
    }
}

But when I run the test it fails on line 8 colum 1
Contact oContact = [select id from Contact limit 1];

and line 38 column 1
Entitlement entl = [select id from Entitlement limit 1];

both have the following error

System.QueryException; List has no rows for assigment to Sobject

Thanks in advance for any help/pointers you give me

Error: CTI line 67, column 56: The element type "body" must be terminated by the matching end-tag "</body>" 
Error: The element type "body" must be terminated by the matching end-tag "</body>".

<apex:page>
<html>
<head>
<!-- Imports Open CTI JavaScript library. It should point to a valid Salesforce
domain. -->
<script src="https://domain:port/support/api/25.0/interaction.js"></script>
<script type="text/javascript">
// Callback of API method: isInConsole
var isInConsoleCallback = function (response) {
// Returns true if method is executed in Salesforce console, false
otherwise.
if (response.result) {
alert('SoftPhone is in Salesforce console.');
} else {
alert('SoftPhone is not in Salesforce console.');
}
};
// Invokes API method: isInConsole
function isInConsole() {
sforce.interaction.isInConsole(isInConsoleCallback);
}
// Callback of API method: getCallCenterSettings
var getCallCenterSettingsCallback = function (response) {
// Result returns call center settings as a JSON string.
if (response.result) {
alert(response.result);
} else {
alert('Error retrieving call center settings ' +
response.error);
}
};
// Invokes API method: getCallCenterSettings
function getCallCenterSettings() {
sforce.interaction.cti.getCallCenterSettings(getCallCenterSettingsCallback);
}
// Callback of API method: setSoftphoneHeight
var setSoftphoneHeightCallback = function (response) {
// Returns true if SoftPhone height was set successfully, false
otherwise.
if (response.result) {
alert('Setting SoftPhone height to 300px was successful.');
} else {
alert('Setting softphone height failed.');
}
};
// Invokes setSoftphoneHeight API method.
function setSoftphoneHeight() {
sforce.interaction.cti.setSoftphoneHeight(300,
setSoftphoneHeightCallback);
}
// Callback of API method: getPageInfo
var getPageInfoCallback = function (response) {
if (response.result) {
alert(response.result);
} else {
alert('Error occured while trying to get page info: ' +
response.error);
}
}
// Invokes API method getPageInfo
function getPageInfo() {
sforce.interaction.getPageInfo(getPageInfoCallback);
}
</script>
</head>
<body>
<button onclick="isInConsole();">isInConsole</button></br>
<button onclick="getCallCenterSettings();">getCallCenterSettings</button></br>
<button onclick="setSoftphoneHeight();">setSoftphoneHeight(300)</button></br>
<button onclick="getPageInfo();">getPageInfo</button>
</body>
</html>
</apex:page>
  • March 07, 2014
  • Like
  • 0

I have a controller which creates a wrapper class and a list of this wrapper class.

 

I have a Visualforce page which uses the standard opportunity controller with the controller containing the wrapper class as an extension. The VF page must use the standard opportunity controller because it is being embedded on the opportunity page layout.

 

I want the Visualforce page to iterate over the list of the wrapper class within a pageBlockTable.

 

However, I get this error.

Error: Unknown property 'OpportunityStandardController.AttachmentWOwnerProfile'

 

How do I let the pageBlockTable know that the list is contained within the extension class?

Hi,

 

I have a situation here. I have a custom object lets say SAAS_Profile__c. It has 2 text fields that contain queries like :

 

Query_Total_Records__c  : Select Count() FROM Case where RecordTypeID='012a0000001RRKBAA4' 

 

Query_Records_Per_Week__c : Select Count() FROM Case where RecordTypeID='012a0000001RRKBAA4'  and CreatedDate = LAST_N_DAYS:7

 

Now my requirement is I have to get all the rows of   SAAS_Profile__c object(total rows less than 100). And for each row returned I have to execute these 2 queries and update 2 fields : Records_pWeek__c(for weekly counts) and Records_Total__c (Total record count). These 2 fields are for statistics purposes and we intend to run this batch job on a weekly basis. Each row of this SAAS_Profile__c object queries on different objects both custom and standard . Here is the batch job that I have written:

 

global class batchSAASProfileUpdate implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
String query = 'SELECT Id,Name,Query_Records_Per_Week__c,Query_Total_Records__c,Records_pWeek__c,Records_Total__c FROM SAAS_Profile__c where Query_Records_Per_Week__c !=\'\' and Query_Total_Records__c != \'\') ';
system.debug('Query String : '+query);
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<SAAS_Profile__c> scope)
{
system.debug('******************Inside execute');
for(SAAS_Profile__c s : scope){
String queryPerWeek = s.Query_Records_Per_Week__c;
String queryTotalRec = s.Query_Total_Records__c;
system.debug('****************name :'+ s.name +'values : queryPerWeek :'+queryPerWeek +' queryTotalRec '+queryTotalRec );
try{
s.Records_pWeek__c = Database.countQuery(queryPerWeek);
s.Records_Total__c = Database.countQuery(queryTotalRec);
system.debug('****************values : s.Records_pWeek__c :'+s.Records_pWeek__c+' s.Records_Total__c '+s.Records_Total__c );
update s;
}
catch(Exception e){
system.debug('********Exception occured' + e.getMessage());
}
}

}
global void finish(Database.BatchableContext BC)
{
}
}

 

This batch job is working for the records that have total count values < 50,000. Its failing for the count() more than that. I am stuck here. I dont know how to work around this issue. Any help is really appreciated. This is really critical for us now!

 

 

Review all error messages below to correct your data. Apex trigger stuLimit caused an unexpected exception, contact your administrator: stuLimit: execution of BeforeInsert caused by: System.TypeException: Invalid integer: [Class__c (Number_Of_Students__c:2, Max_Size__c:2, Id:a0190000007tbH3AAI)]: Trigger.stuLimit: line 15, column 1m

 

 

 

trigger stuLimit on Student__c (after insert)
{
//////////////////////////////////////
// Do not allow insert student if class already reached MaxLimit.
// Created 20131009 max
// Modified 20131009
//////////////////////////////////////
if(Trigger.isAfter && Trigger.isInsert)
{
for (Student__c std : Trigger.new)
{
Id cid = std.class__c;
list<Class__c> cls=[SELECT Max_Size__c, Number_Of_Students__c from Class__c where class__c.id = : cid];
if(Integer.Valueof(cls.get(0)) <= Integer.Valueof(cls.get(1)))
{
std.addError('can\'t insert Class has already reached it\'s maximum limit');
}
}
}

}

 

Hi Everyone,

                       I have the following code.

 

 

 

trigger InsertInfo on Inventory__c (before Update)
 {
    
    for(Inventory__c inv : trigger.new)
      {
         Inventory__c oldValue = Trigger.oldMap.get(inv.ID);
         { 
            
           if( inv.Remaining_Stock__c < oldValue.Remaining_Stock__c)
            { 
              
              Date date1 = Date.Today();
              String abc = String.valueOf(date1);
              Decimal numofgifts = oldValue.Remaining_Stock__c - inv.Remaining_Stock__c ;
              Integer integerValue = numofgifts.intvalue();
              String fe = inv.Field_Executive__r.Name;  // THIS IS WHERE MY PROBLEM IS
              String pqr = String.valueOf(integerValue);
                  inv.Issued_Dates__c   = inv.Issued_Dates__c + '\n' + abc +'\t\t'+ fe +'\t\t'+ pqr;
                  
            }
                 
         }
      }
  }
  

 Issued_Dates is a textbox. But instead of fe Name it displays null. Any idea where I am wrong ?

 

Thanks in advance

 

                              

 

          

  • October 08, 2013
  • Like
  • 0

 

Hi there,

 

How can i get 100% coverage for this code? I get only 55% so far..

 

Any help is greatly appreciated.

 

Thank you,

Manohar

 

global class ISMTrackingBatchProcess implements Database.Batchable < sObject >
{    
    global Database.QueryLocator  start(Database.BatchableContext ctx)
    {
        System.Debug('***** Here it starts *****');
        String Query = 'Select Owner_Name__c, Contact_Name__c,CaseNumber, Owner_Email__c, Dummy_ISM_Datetime__c, TFS_ID__c, Id, ISM_Priority__c, ISM_Priority_Set_Critical_High_At__c From Case  where Dummy_ISM_Datetime__c <> Null and ISM_Priority_Set_Critical_High_At__c <> Null and TFS_ID__c <> Null and ISM_Priority__c in (\'Critical\',\'High\')' ;
        
        return Database.getQueryLocator(Query);
    }

    global void execute(Database.BatchableContext ctx, List<sObject> scope)
    {
        integer failedUpdates1;
        integer failedUpdates2;
        List<Case> cs= (List<Case>)scope;
        List<ISM_Communication_Tracker__c> ismcts = new List<ISM_Communication_Tracker__c>();
        List<ISM_Communication_Alert__c> ismcas = new List<ISM_Communication_Alert__c>();
        boolean missflg  ;
        integer missflg10;
        if (cs.size()>0) 
        {        
        for(Integer i = 0; i < cs.size(); i++){
            if (cs[i].ISM_Priority__c == 'Critical' )
            {
                // Send Email ISM Alert Emails
                integer dmincr = (Math.Floor(decimal.valueOf(Datetime.now().getTime() - cs[i].Dummy_ISM_Datetime__c.getTime() )) / (1000.0*60.0*60.0)).intValue();
                for (integer j = 0; j < dmincr; j++){

//Test not covered from here onwards

                    task[]  t =[select id from task where whatId = :cs[i].id and createddate >=  :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j) and createddate <= :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j).addMinutes(30) and Subject in ('Call','Email') limit 1];
                    if (t.size() == 0 )
                    {
                        ismcas.add(new ISM_Communication_Alert__c(Created_Date_and_Time__c = System.now() , 
                                                                    Case_Owner_Email__c =cs[i].Owner_Email__c, 
                                                                    ISM_Priority__c =cs[i].ISM_Priority__c, 
                                                                    Unique_index__c =cs[i].CaseNumber +string.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j)) + string.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j).addMinutes(30)),
                                                                    Case__c = cs[i].id, 
                                                                    Log_start_at__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j), 
                                                                    Log_End_At__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j).addMinutes(30), 
                                                                    of_Emails__c = j));
                    }
                }
               
////Test not covered until here
                
                // Create ISM Communication Logs
                integer hrincr = (Math.Floor(decimal.valueOf(Datetime.now().getTime() - cs[i].ISM_Priority_Set_Critical_High_At__c.getTime() )) / (1000.0*60.0*60.0)).intValue();
                for (integer j = 0; j < hrincr; j++){

//Test not covered from here onwards

                    task[]  t =[select id from task where whatId = :cs[i].id and createddate >=  :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j) and createddate <= :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j+1) and Subject in ('Call','Email') limit 1];
       
                    if (t.size() > 0 )
                    {
                        missflg = false;
                        missflg10 = 0;                          
                    }
                    else
                    {
                        missflg = true;
                        missflg10 = 1;
                    }
                    
                    ismcts.add(new ISM_Communication_Tracker__c(Case__c = cs[i].id,
                                                       Missed_Communication__c = missflg,
                                                       Missed_Communication1_0__c = missflg10,
                                                       Log_Start_At__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j),
                                                       PrimaryKey__c = string.valueOf(cs[i].id) + string.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c) + cs[i].ISM_Priority__c +  string.valueof(j) , 
                                                       ISM_Priority__c  = cs[i].ISM_Priority__c,
                                                       ISM_Priority_Set_Critical_High_At__c  = cs[i].ISM_Priority_Set_Critical_High_At__c,
                                                       Logged_At__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j+1),
                                                       of_hrs_since_ISM_Priority_Chnaged__c  =Math.Floor(Decimal.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j+1).getTime() - cs[i].ISM_Priority_Set_Critical_High_At__c.getTime() )) / (1000.0*60.0*60.0)    
                                                       ));
                }
            }

////Test not covered until here

            Else if (cs[i].ISM_Priority__c == 'High' )
            {
                
                // Send Email ISM Alert Emails
                integer dmincr = (Math.Floor(decimal.valueOf(Datetime.now().getTime() - cs[i].Dummy_ISM_Datetime__c.getTime() )) / (1000.0*60.0*60.0)).intValue();
                for (integer j = 0; j < dmincr; j=j+4){

//Test not covered from here onwards

                    task[]  t =[select id from task where whatId = :cs[i].id and createddate >=  :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j) and createddate <= :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j).addMinutes(150) and Subject in ('Call','Email') limit 1];
                    
                    if (t.size() == 0 )
                    {
                        ismcas.add(new ISM_Communication_Alert__c(Created_Date_and_Time__c = System.now() ,
                                                                    Case_Owner_Email__c =cs[i].Owner_Email__c, 
                                                                    ISM_Priority__c =cs[i].ISM_Priority__c, 
                                                                    Unique_index__c =cs[i].CaseNumber +string.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j)) + string.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j).addMinutes(150)),
                                                                    Case__c = cs[i].id, 
                                                                    Log_start_at__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j), 
                                                                    Log_End_At__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j).addMinutes(210), 
                                                                    of_Emails__c = j));
                    }
                }

////Test not covered until here                
                
                //Create ISM Communication Tracking Log
                integer hrincr = (Math.Floor(decimal.valueOf(Datetime.now().getTime() - cs[i].ISM_Priority_Set_Critical_High_At__c.getTime() )) / (1000.0*60.0*60.0)).intValue();
                for (integer j = 3; j < hrincr; j=j+4){

//Test not covered from here onwards

                    task[]  t =[select id from task where whatId = :cs[i].id and createddate >=  :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j-3) and createddate <= :cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j+1) and Subject in ('Call','Email') limit 1];
       
                    if (t.size() > 0 )
                    {
                        missflg = false;
                        missflg10 = 0;                          
                    }
                    else
                    {
                        missflg = true;
                        missflg10 = 1;
                    }
                
                    ismcts.add(new ISM_Communication_Tracker__c(Case__c = cs[i].id,
                                                       Missed_Communication__c = missflg,
                                                       Missed_Communication1_0__c = missflg10,
                                                       Log_Start_At__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j-3),
                                                       PrimaryKey__c = string.valueOf(cs[i].id) + string.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c) + cs[i].ISM_Priority__c +  +  string.valueof(j-3) , 
                                                       ISM_Priority__c  = cs[i].ISM_Priority__c,
                                                       ISM_Priority_Set_Critical_High_At__c  = cs[i].ISM_Priority_Set_Critical_High_At__c,
                                                       Logged_At__c = cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j+1),
                                                       of_hrs_since_ISM_Priority_Chnaged__c  =Math.Floor(Decimal.valueOf(cs[i].ISM_Priority_Set_Critical_High_At__c.addhours(j+1).getTime() - cs[i].ISM_Priority_Set_Critical_High_At__c.getTime() )) / (1000.0*60.0*60.0)    
                                                       ));
                }
            }
        }
        
        
        
        failedUpdates1 = 0;
        List<Database.UpsertResult> dsrs1 = Database.upsert(ismcts, false);
        for(Database.UpsertResult dsr1 : dsrs1){
            if(!dsr1.isSuccess()){
                failedUpdates1++;

////Test not covered until here  

            }
            
        }
        failedUpdates2 = 0;
        List<Database.UpsertResult> dsrs2 = Database.upsert(ismcas, false);
        for(Database.UpsertResult dsr2 : dsrs2){
            if(!dsr2.isSuccess()){
                failedUpdates2++;
            }
            
        }
        }
    }

    global void finish(Database.BatchableContext ctx) 
    {
        System.debug(LoggingLevel.WARN,'Batch Process Finished');
      
    }
}

 

 

My Test Class so far...

 

@isTest
private class testscheduleCriticalISM{

    
   public static testMethod void testscheduleISMTrackingBatchProcess()
    {
        Test.startTest();
        scheduleISMTrackingBatchProcess s = new scheduleISMTrackingBatchProcess();
        string sch = '0 0 * * 1-12 ? *';
        system.schedule('Process Trans 1', sch, s);
        Test.stopTest();
    }

    public static testMethod void testISMTrackingBatchProcess()
    {
        //get the initial details
        Profile pf = [Select Id from Profile where Name = 'System Administrator'];
 
        //creating RunAs User Record
        User u = new User();
        u.FirstName = 'Test';
        u.LastName = 'user';
        u.Email = 'testuser@test123456789.com';
        u.CompanyName = 'test.com';
        u.Title = 'Test user';
        u.Username = 'testuser@test123456789.com';
        u.Alias = 'testuser';
        u.CommunityNickname = 'Test User';
        u.TimeZoneSidKey = 'America/Chicago';
        u.LocaleSidKey = 'en_US';
        u.EmailEncodingKey = 'ISO-8859-1';
        u.ProfileId = pf.Id;
        u.LanguageLocaleKey = 'en_US';
        insert u; 
      //  Datetime dToday = datetime.newInstance(MySystem.SetToday().year(), MySystem.SetToday().month(),MySystem.SetToday().day());
		Datetime origDate = DateTime.valueOf('2013-01-01 0:0:0');
		Datetime nowDatetime = DateTime.valueOf('2013-01-01 12:0:0');
		
        String ISM_Priority;
        List <Case> kases = new List<Case>();
        for(integer i = 0; i<200; i++){
            if (i < 100) 
            {    ISM_Priority = 'Critical';}
            else
            {    ISM_Priority = 'High';}
            Case c = new Case(Subject='testCase'+'i', 
                        Ownerid = u.ID,
                        Status = 'Open',
                        Origin = 'Other',
                        TFS_ID__c = i,
                        ISM_Priority_Set_Critical_High_At__c = origDate,
						Dummy_ISM_Datetime__c = origDate.addMinutes(-30),
                        ISM_Priority__c = ISM_Priority 
                        ); 
                                  
            kases.add(c);
            }
		insert kases;	
		task[]  t =[select id from task where Subject in ('Call','Email') ];
                      	
        
        integer hrincr = (Math.Floor(decimal.valueOf(nowDatetime.getTime() - origDate.getTime() )) / (1000.0*60.0*60.0)).intValue();
        integer dmincr = (Math.Floor(decimal.valueOf(nowDatetime.getTime() - origDate.addMinutes(-30).getTime() )) / (1000.0*60.0*60.0)).intValue();
        Test.startTest();
        ISMTrackingBatchProcess b = new ISMTrackingBatchProcess();
        ID myBatchJobID = database.executebatch(b);		
        
		if (t.size() ==0 && hrincr > 4)
		{
			System.AssertEquals(database.countquery('SELECT COUNT() FROM ISM_Communication_Alert__c WHERE ISM_Priority__c  =\'Critical\''), 0);  
		}
		if (t.size() ==0 && hrincr > 4)
		{
			System.AssertEquals(database.countquery('SELECT COUNT() FROM ISM_Communication_Tracker__c WHERE ISM_Priority__c  =\'Critical\' and Missed_Communication__c = true'), 0);  
		}
		Test.stopTest();
    } 
}

 

Hi Everyone,

                      I used the function valueOf as following

Date date1 = Date.Today();
String abc = valueOf(date1);

 But I get the following error

 

Error: Compile Error: Method does not exist or incorrect signature: valueOf(Date) at line 10 column 28.

 

                          Can someone point me the error. I checked the syntax in the salesforce system calls list and it is the same as the one I used.

  • October 07, 2013
  • Like
  • 0

I want to get all the fields of an object.

Is there any way to get the whole object? Or I need to write the full query? My object has more than 200 fields (I can write them copying and pasting, but if exists another way ...

 

 

Thanks

 

 

I'm new in writing apex classes + triggers so I have a problem now with a batch class which has a for loop so DML statement limit goes over, I was reading about bulkifying code, but it seems it's only for triggers not classes(please correct me if I'm wrong)? And how should I change this part of the code if I need to make it work :

        for (Case c : suppportCases) {
            System.Debug('SCHEDULED: CASE ' + c.CaseNumber + ' HANDLING STARTED');
                    
            List<Service_Availability__c> oldSAsPerCase =
                                            [select Name, Status__c, Duration__c, Start_DateTime__c from Service_Availability__c                                                     
                                            where Case__c =: c.Id
                                            order by Name desc];
            
            System.Debug('SCHEDULED: OLD SA COUNT: ' + oldSAsPerCase.Size());
Should I make it this way :

 

List<Service_Availability__c> oldSAsPerCase : [SELECT Name, Status__c, Duration__c, Start_DateTime__c from Service_Availability__c                                                     
                                            where Case__c =: c.Id
                                            order by Name desc];

 

System.Debug('SCHEDULED: OLD SA COUNT: ' + oldSAsPerCase.Size());

 

for (Case c : suppportCases) {
            System.Debug('SCHEDULED: CASE ' + c.CaseNumber + ' HANDLING STARTED'); ?

  • October 07, 2013
  • Like
  • 0

HI there,

it's really confusing that how it is picking values by using {!filterId}
expression selectList component???

<apex:page standardController="Case" recordSetvar="cases">
    <apex:pageBlock >
        <apex:form id="theForm">
            <apex:panelGrid columns="2">
                <apex:outputLabel value="View:"/>
                <apex:selectList value="{!filterId}" size="1">
                    <apex:actionSupport event="onchange" rerender="list"/>
                    <apex:selectOptions value="{!listviewoptions}"/>
                </apex:selectList>
            </apex:panelGrid>
            <apex:pageBlockSection >
                <apex:dataList var="c" value="{!cases}" id="list">
                    {!c.subject}
                </apex:dataList>
            </apex:pageBlockSection>
        </apex:form>
    </apex:pageBlock>
</apex:page>

if anyone knows it there than please update me..... thanks.. in advance :)

  • October 04, 2013
  • Like
  • 1

I have a class which is used in opportunity insertion ... but when I am running it, it is giving exception error (highlighted)

-----------

 

public static void OppInsert(Opportunity[] newOpportunity)
{
String Record_Type = '0145000000000fdAAA'
TestWeek__c TestWeek;
try
{

TestWeek = [select Wk_Nmbr__c, Year__c from TestWeek__c where Start_Date__c <= TODAY and End_Date__c >= TODAY]; // This is returniong values 

}
catch(System.QueryException e)
{
trigger.new[0].addError(e);
return;
}
if(TestWeek !=null)
{
// loop thru the newly created opportunities
for (Opportunity opportunityLoop : newOpportunity)
{
if (opportunityLoop.RecordTypeId == Record_Type.substring(0, Record_Type.length()-3))
{

 

---------------

 

It is firing for other record types of opportunity and giving the exceprion on opportunity insertion as  : 

FIELD_CUSTOM_VALIDATION_EXCEPTION, List has no rows for assignment to SObject: []

 

Any suggestions here ?

How to write test method for the following web service method?

 

 public String resetPassword(Long contactId,String userName,String passWord,Integer updatedBy) {
            serviceFlorenceWeaComNew.resetPassword request_x = new serviceFlorenceWeaComNew.resetPassword();
            serviceFlorenceWeaComNew.resetPasswordResponse response_x;
            request_x.contactId = contactId;
            request_x.userName = userName;
            request_x.passWord = passWord;
            request_x.updatedBy = updatedBy;
            Map<String, serviceFlorenceWeaComNew.resetPasswordResponse> response_map_x = new Map<String, serviceFlorenceWeaComNew.resetPasswordResponse>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              ...
            );
            response_x = response_map_x.get('response_x');
            return response_x.return_x;
        }

I have a lookup field, I should need to make this field is only editable by system admin only. Not to users .how can i do this.

  • September 19, 2013
  • Like
  • 0

Hi,

 

I have got Professional edition and have created a VF page(for Detailed Page) using standard controller in Leads section and have override the standard layout. Now is there a possibility to have inline edit (& Save) option available in this VF page by not writing a controller.

 

Regards

I want to write a trigger:

 

I've one 'Account' object and 'Contact' is its child object. In 'Account Object' there is a custom field Name 'Contact_Name__c'.

 

If i inserts any record in 'Contact' object than its 'First Name'  field value copies into the 'Contact_Name__c' field.

 

I wants that all 'Contact' Object records 'First Name' copies into 'Contact_Name__c' field those are in relationship with that 'Account' Object.

 

For Example:

 

If Account Name-'Acc' and in Child 'Contact' have 3 records.

and First Name of these records are- 'Nitin', 'Rahul', 'Ashwani'

 

Now i want these field values in Contact_Name__c field

Contact Name: Nitin, Rahul, Ashwani

 

So how i can do this. Please help me to write trigger for it.

I have an extension with the following:

     caseOpen = [Select Priority,CaseNumber,Accountid,Subject,Contactid,CreatedDate,Ownerid,Status,SuppliedName   
                    from case

Which works fine.

 

I want to add a field: Owner, and I get the msg: Error: Compile Error: No such column 'Owner' on entity 'Case'.

 

It is a field in Case. The difference from the other fields is that it has Data Type Lookup(user,Queue)

 

How do I go about getting the field?

 

THanks,

Haya

  • September 13, 2013
  • Like
  • 0
Hello Everyone,

This is an issue relating to page display in salesforce sites.
When we hit something in site url with .html extension the url rewritter class is not getting called.
How can that url rewritter be called so that within that class we can interpret that lets say index.html and then 
change it as per requirement lets say index(A vf page or anything).

Similarly if we hit a static resource url directly through site then the url gets accessed and the static resource image is displayed to the user.
But the requirement is that teh image should not be displayed. What is happening there is in this case also the url rewriter cass is not called, because if it is getting called then we can restrict the resource display in that class.

If anybody has solution to this that how come we can call the rewriter class in the above two scenarios, please post here.

Thanks

Hello everyone,

 

We are integrating linkedIN in salesforce. We want to retrieve linkedIN profile information within salesforce.

For that we needed to callout from salesforce. We are following the Authentication steps as follows:

 

https://developer.linkedin.com/documents/authentication

 

We successfully reached upto Step 2, point a). But the problem arised in the HTTP POST Request in the point b) in order to retrieve the access token from the response. We are getting the authorization code correct and we are sending that code in the point b) but,  We are repetately getting the following error on that point

 

{"error":"invalid_request","error_description":"missing required parameters, includes an invalid parameter value, parameter more then once. : Unable to retrieve access token : authorization code not found"}

#Note: The authorization code which is coming in the URL is displaying correctly in the debug.

 

If anyone has any suggestion, kindly reply.

 

Thanks in Advance

Hello everyone,

 

This post is regarding the avoidance of getDescribe method.

What it is doing here is generic fields fetching from generic object selection.

It is working fine when the no of fields are less than equal to 100.  But as expected if it exceeds 100 then the above named error occurs as we all know.

 

fields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
for(SObjectField fieldtoken : fields.values()) {
     DescribeFieldResult dfr = fieldtoken.getDescribe();
    //Some logic 
}

 

 

##This statement will execute more than 100 which will error out.

 

Any suggestion? Is there any way to handle that?

 

Thanks in advance.

Hello everyone,

 

We have migrated leads from one salesforce org to another org  through dataloader. Presently some of those leads become converted in source org but those are unconverted in target org. Now the requirement is we have to update those leads which became converted in source to target org so that it will become converted in target org as well.

 

But the problem is when we are going to upload that csv file containing those CONVERTED fields it is not showing for mapping in the dataloader. So eventually it is not becoming converted and remains as unconverted even after update. 

 

Can anyone please help us through this how to enable those fields to display in dataloader for mapping.

 

Thanks in Advance

Hello everyone,

 

We are in the middle of a migration and we are stuck in TaskRelation standard object. When we extract TaskRelation records from source org, in the TaskId Lookup field event records are coming in the csv. Then naturally when we are going upload those in target giving error as event records are going in TaskId field. 

 

Anyone can suggest me how can we get the Task records in that field instead of Event records?

 

Thanks in advance.

Hello everyone,

 

We are doing salesforce data migration from one org to another. In some objects we have richtextarea fields, the value of which are not migrated in target org. In target org, the field is showing as "Image not Available". Also the path shows that it is a broken image like this "/img/rte_broken_image.png".

 

If anyone has solution of this, please help us out.

 

Thanks

Hi all,

 

We are migrating attachments and documents from one salesforce org to another. We are using FileExporter for exporting the attachments and Dataloader to import those in target org. We exported the attachments from old org successfully but the problem we are facing is"Error converting value to correct data type:" while importing to new org. 

 

If anyone has idea about this, please help me out.

 

Thanks in advance

Hi all,

 

We are migrating Event records from one Salesforce org to another. Some records failed to insert and it is giving error as

"Private events for other users are not allowed: Private"

 

But the requirement is we have to keep that private and also insert.

I tried by making IsPrivate = false during insert and later update those records as IsPrivate = true.

Then it is inserted correctly but update failed giving the same error.

Is there any way to insert it by keeping it private.

 

Thanks in advance.

Hi All,

 

We are migrating huge amount of data from one Salesforce org to another through dataloader. We faced some problem while migrating lead data. Some records of lead failed to migrate and it errored out like for e.g

"Converted Date(Mon Oct 19 00:00:00 GMT 2010) before Create Date(Tue Oct 19 10:54:57 GMT 2010).: Converted Date"

Didn't able to find out the reason of this. Just wondering how can this error come.

 

If anyone has any answer to this, kindly help us to this.

 

Thanks in advance

Hi all,

 

I'm migrating data using salesforce to salesforce. It is working fine. But while trying to insert audit field values from old organisation to new organisation it is not giving the option to map the audit fields. I have already enabled Audit field value insert  once in new organisation from salesforce.com but still CreatedBy, CreatedDate etc audit fields are not displaying in the mapping section to pass the old audit fields to new organisation.

 

If anyone has any solution to this kindly reply back as soon as possible.

 

Thanks in advance

Hi,

 

I have transferred two level deep records from one organisation to another through salesforce to salesforce.

For e.g Account and its related contacts.

But how can we transfer three level deep records at one go i.e Account -> Contact -> A child object of Contact.

 

I'm using this method

for(Account acc:ls)
                    {
                    //object declaration for PartnerNetwork
                    PartnerNetworkRecordConnection newrecord = new PartnerNetworkRecordConnection();
                    system.debug('Second for loop');
                    newrecord.ConnectionId = network.Id;
                    newrecord.LocalRecordId = acc.id;  
                    newrecord.RelatedRecords = 'Contact,Opportunity';
                    newrecord.SendClosedTasks = true;
                    newrecord.SendOpenTasks = true;
                    newrecord.SendEmails = true;
                    //All the Records are added to the PartnerNetwork
                    lstShareRecords.add(newrecord);
                    }

 In this way I'm transferring Account, related Contacts and opportunities. But how can we transfer any child records of contact or opportunity at one go?

 

If anyone knows about this kindly help me out.

 

Thanks in advance

 

Hi all,

 

I'm using salesforce to salesforce data migration for migrating huge amount of data from one organisation to another.

At first I send all account records and related contact records through apex coding. Account migration is successful. But the problem is coming in related contact records.

 

Some contact records are migrating as per the relationship with its respective account and the migration is fine. But some contact records are not migrating at all.

 

Lets say for e.g

Account                       Contact

    A                                      C1

    A                                      C2

 

This is migrating as per the relationship(both account and respective contacts)

But,

Account                       Contact

    B                                     D1

    B                                     D2

Only the account is migrated and the contacts are not migrated.

 

After that I also tried to transfer those contacts manually, but still they are not migrated and the status is showing as Pending(Sent).

Is there any reason for which some particular contact records are not migrating using salesforce to salesforce migration?

If anyone has any solution, kindly help me out

 

Thanks in advance

Hi all,

 

We have a managed package with Namespace prefix 'MFS'.
Package is installed at a production account.

 

Say, we have VF page XYZ with XYZController
and another VF page ABC with ABCController
Now While clicking at a link in a particular VF page, and it is forwarding to VF page XYZ, error coming is
"Apex class 'XYZController' doesn't exist"

WHAT is the reason?

 

I have found 1 thing. While clicking some link to forward any VF page like ABC , URL is coming like below:
https://MFS.ap0.visual.force.com/apex/ABC?widgetConditionId=a0s100...

And ABC is working fine.
But ONLY for XYZ, it is coming like this: https://c.ap0.visual.force.com/apex/XYZ?widgetConditionId=a0s100...

And XYZ is not working.

 

Is this any problem?

IS the problem lies in 'MFS' prefix?

 

If anyone has answer to this please reply as soon as possible.

Thanks in advance.

I'll give certification exam this week. Please solve me these questions if you know

How does Salesforce enforce data access using role hierarchy?
a. Users are given access to the records owned by the users who are
below them in the role hierarchy
b. Users are given access to the records owned by the users who share
the same role in the role hierarchy
c. Users are given access to the records accessible by the users who are
below them in the role hierarchy
d. Users are given access to the records accessible by the users who are
above the role hierarchy

 

What will cause the analytic snapshots run to fail?
Please select three (3) choices.
a. The source report has been deleted
b. The target object has a trigger on it
c. The running user has been inactivated
d. The target object is a custom object
e. The source report is saved as matrix report

 

Thanks 

Souvik

Hi,

In the outputfield style="width:100px;" is not working..I'm not able to reduce the width of the outputfield which is causing so much scrolling. The inputfield is working fine .but the same value when displaying through output field it is displaying horizontally instead of line breaking..How can I reduce that width?? If anyone has any solution to this please give me an idea..It is very urgent.

Thanks

Souvik.

How can we change the datatype of a Object Field which is in managed package? If anyone has any idea about that please reply as soon as possible. Its an urgent requirement.

Thanks,

Souvik

How to avoid Cross-site Scripting (XSS) using 

<apex:outputtext value="{!gadgetHTMLContent}" escape="false"/>

.. In the above outputtext gadgetHtmlContent is always a HTML CONTENT for e.g <div id="Test"></div>. Like this. For displaying html content we have to use escape="false". But whenever we are trying to write escape="false", an error is coming about  Cross-site Scripting (XSS) attacks. How can we avoid this attack by using escape="false".

                                     Please reply anyone who has any idea about this as soon as possible. It is very urgent.

                                                                                                                                                                                                   Thanks Souvik.

I have a visualforce page. Within it there are many tabs of custom objects where list of records are displaying by writing apex:listviews within the tab.

<apex:page showHeader="false" standardController="Panel__c">
  <apex:sectionHeader title="Panel" subtitle="Home" />
  <apex:listViews type="Panel__c" />
</apex:page>

But by clicking on a standard button/link it is redirecting to the standard salesforce page...But I'm trying to redirect it into my visualforce page without overidding the standard button/link. Because there are almost 20-25 objects. If I override I have to write the functionality of all of them in separate controllers. thats why I want to redirect that standard page within my visualforce page under respective tabs.
How can I do this?....Please help me if anyone has any suggestion...It is very urgent.......

Thanks 

Souvik

I want to fetch all the urlParameters from Url and then use it in a key=value pair. But the requirement is I have to get the parameters in the entered order as it is displaying in the URL not in alphabatical order. By default it is coming in alphabatical order but I have to get the exact order which is entered in the URL. For that I have used 

ApexPages.currentPage().getHeaders().get('Referer'); 

But it is displaying null. Kindly suggest me what to do if anyone do have any idea about this. Please reply as soon as possible its urgent.

 

Thanks

Souvik.

I want to do pagination of records.Suppose I want to show 5 records in one page,next 5 in next page.But the requirement is not to query database each time next button is clicked.The requirement is at first total list will be retrieved from controller then from that list, limited values will be displayed in a page,after clicking next , the next values from the list will be displayed. How this can be done. If you have any idea kindly help me as soon as possible.

 

Thanks

Souvik.

Hi all,

           I have a pageblocktable where there are two columns. In the second column of the pageblocktable there is a datatable. There is a commandLink on each row in the secondcolumn of the pageblocktable. By clicking on the link in a particular row, datatable will appear on that particular row only of the pageblocktable with its corresponding values.

           But the problem I'm facing is that after clicking the link in a particular row of the pageblocktable its corresponding values (i.e the datatable) is displaying in all the rows of the pageblocktable. But I have to display the datatable in that particular row only.

           Here is the code of the visualforcepage

 

<apex:pageBlockTable value="{!statuspostlist}" var="status" border="0" cellpadding="6" cellspacing="13" columnsWidth="3">
<apex:column headerValue="Name">
{!status.Userlogin__r.Total_Name__c}&nbsp;&nbsp;posted
</apex:column>
<apex:column headerValue="Status">
{!status.Status__c}<br/><br/>
<apex:image url="{!$Resource.fb45}" width="28px" height="28px" />&nbsp;&nbsp;
Like&nbsp;&nbsp;
<apex:commandLink action="{!commentstatus}">
Comment<apex:param name="cmid" value="{!status.id}"/>
</apex:commandLink>
<apex:outputPanel rendered="{!visible_comment =='show'}">
<apex:dataTable value="{!statuspost1.Comments__r}" var="cm">
<apex:column >
{!cm.Comments__c}
</apex:column>
</apex:dataTable>
</apex:outputPanel>
</apex:column>
</apex:pageBlockTable>

 

And the code of that method in apex is:

 

public PageReference commentstatus()
{
Id uid = System.currentPageReference().getParameters().get('uid');
Id cmid = System.currentPageReference().getParameters().get('cmid');
//comment = [select id,Comments__c,Status_Post__c,Userlogin__c from Comment__c where Status_Post__c=:cmid];
statuspost1 = [ select id,Status__c,Userlogin__c,User2__c,User2__r.Total_Name__c,Userlogin__r.Total_Name__c,
(select id,Comments__c,Status_Post__c,Userlogin__c from Comments__r) from Status_Post__c
where id=:cmid];
PageReference nextpage = ApexPages.currentPage();
visible_comment = 'show';
return nextpage;
}

 

So kindly if anyone have any suggestion about this,please help me.

 

Thanks in advance,

Souvik.

Hi all
I have created a Vf Page for file uploading.when i am uploading file and going to save the record its showing error

Visualforce ErrorHelp for this Page
System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!save}' in component <apex:commandButton> in page newsalesconfirmation: Class.NewSalesConfirmationExtension.save: line 55, column 1

 
public class NewSalesConfirmationExtension {
    public Purchase_Order__c purchaseOrder{get;set;}
    public Transient Attachment attachment {get;set;}
    public boolean showC1RecordType {get;set;}
    public boolean showC2RecordType {get;set;} 
    
    private Id c1RecordTypeId; 
    private Id c2RecordTypeId;
    
    public NewSalesConfirmationExtension(ApexPages.StandardController controller) {
        c1RecordTypeId = Schema.SObjectType.Purchase_Order__c.getRecordTypeInfosByName().get('C1').getRecordTypeId();
        c2RecordTypeId = Schema.SObjectType.Purchase_Order__c.getRecordTypeInfosByName().get('C2').getRecordTypeId();
        
        purchaseOrder = new Purchase_Order__c();
        purchaseOrder = (Purchase_Order__c)controller.getRecord();
        
        String isButtonClicked = Apexpages.currentPage().getParameters().get('setDefaultValues');
        if(isButtonClicked == 'true'){
            setDefaultValues();
        }
        
        showC1RecordType = false;
        showC2RecordType = false;
        attachment = new Attachment();
        
        
        if(purchaseOrder.RecordTypeId == c1RecordTypeId){
            showC1RecordType = true;
            showC2RecordType = false;
        }
        else if(purchaseOrder.RecordTypeId == c2RecordTypeId){
            showC1RecordType = false;
            showC2RecordType = true;
        }
        
    }
    
     public void setDefaultValues(){
        String quoteId = Apexpages.currentPage().getParameters().get('quoteId');
        Quote__c quote = [Select o.id, o.name, o.Quantity_formula__c, o.Opportunity_Product_Detail__r.Opportunity__c,
                    o.Opportunity__c, o.Record_type_name__c,o.Company_Name__c,Opportunity_Product_Detail__r.Opportunity__r.Account__c from Quote__c o WHERE O.id=:quoteId];
        //system.assert(false,quote);     
        purchaseOrder.Opportunity__c = quote.Opportunity_Product_Detail__r.Opportunity__c;
        purchaseOrder.Quote__c = quote.id;
        purchaseOrder.Company__c = quote.Opportunity_Product_Detail__r.Opportunity__r.Account__c;
        
        if(quote.Record_type_name__c == 'C1'){
            purchaseOrder.RecordTypeId = c1RecordTypeId;
        }
        else {
            purchaseOrder.RecordTypeId = c2RecordTypeId;
        }
    }
    public PageReference save(){
        if(attachment.Body == null){
            Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR, 'Please upload recent Purchase Order  before saving the record'));
            return null;
        }
        else{
            try{
                insert purchaseOrder;
                
                attachment.OwnerId = UserInfo.getUserId();
                attachment.ParentId = purchaseOrder.id;
                insert attachment;
                
                return new PageReference('/'+purchaseOrder.id);
            }
            catch(DMLException e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,e.getMessage()));
                return null;
            }
        }
    }
}
----------------------------------------------------------------------------------------------

<apex:page standardController="Purchase_Order__c" extensions="NewSalesConfirmationExtension">
    <apex:sectionHeader title="Sale Confirmation Orders" subtitle="{!purchaseOrder.Name}" />
      <apex:form enctype="multipart/form-data">
        <apex:pageMessages ></apex:pageMessages>
        <apex:pageBlock title="Sale Confirmation Order Edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
                <apex:commandButton action="{!cancel}" value="Cancel"/>
            </apex:pageBlockButtons>
            
            <apex:pageBlockSection title="Information" columns="2" collapsible="false" rendered="{!showC1RecordType}">
                <apex:inputField value="{!purchaseOrder.Opportunity__c}"/>
                <apex:inputField value="{!purchaseOrder.Sale_Confirmation_Order_Number__c}" required="true"/>
                <apex:inputField value="{!purchaseOrder.GRN_needed_for_Bill_Processing__c}"/>
                <apex:inputField value="{!purchaseOrder.Sale_Confirmation_Order_Date__c}" required="true"/>
                <apex:inputField value="{!purchaseOrder.No_of_Days_for_collecting_GRN__c}"/>
                <apex:inputField value="{!purchaseOrder.Pre_shipment_Inspection_required__c}" required="true" />
              
                <apex:inputField value="{!purchaseOrder.Purchase_Frequency__c}" required="true" />
                <apex:inputField value="{!purchaseOrder.Customer_Ordered_Quantity__c}" required="true" />
                <apex:inputField value="{!purchaseOrder.Credit_Limit__c}"/>
                   
                    <apex:inputField value="{!purchaseOrder.Customer_Price__c}"/>
                     <apex:inputField value="{!purchaseOrder.CurrencyIsoCode}"/>
                <apex:inputField value="{!purchaseOrder.Bill_Submission_Period__c}"/>
               
                <!---<apex:inputField value="{!purchaseOrder.New_Flash_Aidc_Email_sent__c}"/>--->
               
               
               <!--- <apex:inputField value="{!purchaseOrder.New_Flash_Email_sent__c}"/>--->
                <apex:inputField value="{!purchaseOrder.Committed_Dispatch_Date__c}" required="true"/>
              
               <!-- <apex:inputField value="{!purchaseOrder.PO_Uploaded__c}"/>
                <apex:inputField value="{!purchaseOrder.Try__c}"/>
                <apex:inputField value="{!purchaseOrder.CountAttachment__c}"/>--->
            </apex:PageBlockSection>
            
            <apex:pageBlockSection title="Information" columns="2" collapsible="false" rendered="{!showC2RecordType}">
                <apex:inputField value="{!purchaseOrder.Opportunity__c}"/>
                <apex:inputField value="{!purchaseOrder.Sale_Confirmation_Order_Number__c}" required="true"/>
                <apex:inputField value="{!purchaseOrder.GRN_needed_for_Bill_Processing__c}"/>
                <apex:inputField value="{!purchaseOrder.Sale_Confirmation_Order_Date__c}" required="true"/>
                <apex:inputField value="{!purchaseOrder.No_of_Days_for_collecting_GRN__c}"/>
                <apex:inputField value="{!purchaseOrder.Committed_Dispatch_Date__c}" required="true"/>
                <apex:inputField value="{!purchaseOrder.Credit_Limit__c}"/>
                <apex:inputField value="{!purchaseOrder.Customer_Ordered_Quantity__c}"/>
                <apex:inputField value="{!purchaseOrder.CurrencyIsoCode}"/>
                <apex:inputField value="{!purchaseOrder.Customer_Price__c}"/>
                <apex:inputField value="{!purchaseOrder.Purchase_Frequency__c}" required="true" />
                <apex:inputField value="{!purchaseOrder.Bill_Submission_Period__c}"/>
                <apex:inputField value="{!purchaseOrder.Application_Area__c}"/>
               
                <!---<apex:inputField value="{!purchaseOrder.CountAttachment__c}"/>
                <apex:inputField value="{!purchaseOrder.Try__c}"/>
                <apex:inputField value="{!purchaseOrder.New_Flash_Email_sent__c}"/>
                 <apex:inputField value="{!purchaseOrder.New_Flash_Aidc_Email_sent__c}"/>---->
            </apex:PageBlockSection>
            
            <apex:pageBlockSection title="Quote Details" columns="1" collapsible="false">
                <apex:inputField value="{!purchaseOrder.Quote__c}"/>
                <apex:inputField value="{!purchaseOrder.Company__c}"/>
                 <apex:inputField value="{!purchaseOrder.Delivery_Address__c}" required="true" />
            </apex:PageBlockSection>
            
            <apex:pageBlockSection title="New Flash Details" columns="2" collapsible="false">
                <apex:inputField value="{!purchaseOrder.Application_Area__c}"  rendered="{!showC1RecordType}"/>
                <apex:inputField value="{!purchaseOrder.Remarks__c}"/>
            </apex:PageBlockSection>
            
            <apex:pageBlockSection title="Upload Purchase Order" columns="2" collapsible="false">
                <apex:pageBlockSectionItem >
                <apex:outputLabel value="File" for="file" />
                <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
                </apex:pageBlockSectionItem>
            </apex:PageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Class.NewSalesConfirmationExtension.save: line 55, column 1

Hi Experts,

I'd like your guidance on how to use checkbox in visualforce to delete multiple records.

Below is how my visualforce look like. I want to be able to select multiple attachments then click on the "Delete Selected" button to delete the records that are selected.

User-added image

I'm stuck and I don't know how to achieve this.

I appreciate the help. Thanks much!


Here's my Code:

=====Page=====

<apex:page standardController="Contact" extensions="AttachmentController">
    <apex:form >
        <apex:pageBlock Title="Notes and Attachments">
            <!-- Buttons -->
            <apex:commandButton value="New Note"/>
            <apex:commandButton value="Attach File"/>
            <apex:commandButton value="Delete Selected"/>
            <apex:commandButton value="View All"/>
            <!-- Buttons -->
            <apex:pageBlockSection >
                <apex:pageBlockTable value="{!Attachments}" var="att">                    
                   <apex:column >
                       <apex:inputCheckbox />
                   </apex:column>
                   <apex:column value="{!att.id}"/>
                   <apex:column value="{!att.name}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 

=====Class=====

 

public class AttachmentController {

    public AttachmentController(ApexPages.StandardController controller) {}

    string AttParentId = apexPages.currentPage().getParameters().get('id');
    
    public List<Attachment> getAttachments(){
        list<attachment> att = [select id, name, body from Attachment where parentId =:AttParentId ];
        return att;
    }
}
i am not able to access the enteredacc variable value in my other vf pages,i am using  a single controller and also while moving from one page to another i am setting redirect to false,here is my apex classes and vf pages (3)
 apex class:
public class picklistdemo1{

public picklistdemo1(ApexPages.StandardController controller) {

}
public String enteredacc {get; set;}
public String Acno1{get;set;}
public String Acname{get;set;}
public Double AcAnnualRevenue{get;set;}
public String AcPhone{get;set;}
public Date Acdate{get;set;}
public void accDetails()

system.debug('enteredaccno is '+enteredacc); 
if(enteredacc == '' || enteredacc == null){
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter valid Account number or if you are a new user register by clicking the below button'));
return ;
}
else
{

List<Account> acc=[Select Name,AccountNumber,AnnualRevenue,Phone,SLAExpirationDate__c from Account where AccountNumber= :enteredacc];


for(Account a : acc)
{
Acno1=a.AccountNumber;
Acname=a.Name;
AcAnnualRevenue=a.AnnualRevenue;
AcPhone=a.Phone;
Acdate=a.SLAExpirationDate__c;
}

}


}


public PageReference show1() {
return null;
}

public ORDER__c rec=new ORDER__c();
public List<SelectOption> listofbooks{get;set;}

public list<String> selectedbooks { get; set; }

public PageReference add() {

rec.Accountname__c=enteredacc;
rec.select_books__c=String.join(selectedbooks,',');
insert rec;
return null;
}
public PageReference gotoPage() {
PageReference pr = Page.multipicklist;
pr.setRedirect(false);
return pr;
}
public PageReference gotoPageagain() {
PageReference pr = Page.adding_order;
pr.setRedirect(false);
return pr;
}

public picklistdemo1()
{
listofbooks=new List<SelectOption>();
listofbooks.add(new SelectOption('b1','b1'));
listofbooks.add(new SelectOption('b2','b2'));
listofbooks.add(new SelectOption('b3','b3'));
listofbooks.add(new SelectOption('b4','b4'));
listofbooks.add(new SelectOption('b5','b5'));
listofbooks.add(new SelectOption('b6','b6'));
listofbooks.add(new SelectOption('b7','b7'));
listofbooks.add(new SelectOption('b8','b8'));
listofbooks.add(new SelectOption('b9','b9'));
listofbooks.add(new SelectOption('b10','b10'));

}
}
istvf page:
<apex:page standardController="Account" extensions="picklistdemo1">
<apex:form >
<apex:pageBlock id="firstblock" >
<apex:pageMessages id="showmsg"></apex:pageMessages>
<apex:pageBlockSection >
<apex:outputText >Enter Account Number:</apex:outputText>
<apex:inputText value="{!enteredacc}"/>
</apex:pageBlockSection>
<apex:commandButton value="Search" action="{!accDetails}" rerender="firstblock,nextblock,showmsg"/>
<apex:outputText >enteredacc:{!enteredacc}</apex:outputText>
<apex:commandButton value="Next!" action="{!gotoPage}"/>
</apex:pageBlock>

<apex:pageBlock id="nextblock">
<apex:pageBlockSection title="ACCOUNTDETAILS">
<apex:outputText >Account Number:</apex:outputText>
<apex:inputText value="{!Acno1}"/>

<apex:outputText >Account Name:</apex:outputText>
<apex:inputText value="{!Acname}"/>
<apex:outputText >Annual Revenue:</apex:outputText>
<apex:inputText value="{!AcAnnualRevenue}"/>
<apex:outputText >Phone No.:</apex:outputText>
<apex:inputText value="{!AcPhone}"/>

</apex:pageBlockSection>
<apex:pageBlockSection title="REGESTRATION">


<apex:inputText value="{!Account.AccountNumber}"/>
<apex:inputText value="{!Account.name}"/>

<apex:inputText value="{!Account.AnnualRevenue}"/>

<apex:inputText value="{!Account.Phone}"/>

<apex:inputText value="{!Account.SLAExpirationDate__c}"/>


<apex:commandButton value="REGISTER!" action="{!save}"/>
</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:page>
2nd vf:
<apex:page controller="picklistdemo1">
<apex:form >
<apex:outputPanel >
<apex:outputLabel >select book from the list</apex:outputLabel>
<apex:selectList value="{!selectedbooks}" size="6" multiselect="true">
<apex:selectOptions value="{!listofbooks}">
<apex:commandbutton value="Show Values" action="{!show1}" rerender="pbs1,pbs2"/>
<apex:commandButton value="NEXT" action="{!gotoPageagain}"/>

</apex:selectOptions>
</apex:selectList>
</apex:outputPanel>
</apex:form>


<apex:pageBlock title="selected books">
<apex:pageBlockSection id="pbs1">
<apex:pageBlockSectionItem >
{!selectedbooks}
</apex:pageBlockSectionItem>
<apex:pageBlock title="accountvalue">
<apex:pageBlockSection id="pbs2">
<apex:pageBlockSectionItem > {!enteredacc}</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
3rd vf:
<apex:page controller="picklistdemo1">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="order information">
<apex:outputText > value="{!enteredacc}"</apex:outputText>
<apex:outputText > value="{!selectedbooks}"</apex:outputText>
<apex:commandButton value="PLACE ORDER" action="{!add}" />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
please help ,i am stuck in these for several hours.....
Thanks in advance
 
I am writing a test class feed item trigger ,iam getting this error can anyone help me
my trigger is
error:System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ChatterPostTrigger: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.ChatterPostTrigger: line 11, column 1: []


@isTest
Public with sharing class ChatterPostTriggerTest {
 static testmethod void testChatterPostTrigger(){ 
Profile pr = [Select Id from Profile where Name='Standard User'];
User u = new User();
        u.Username  ='kiranp@test.com';
        u.LastName  ='John jane';      
        u.Alias     = 'jjhan';
        u.CommunityNickname = 'jhane';    
        u.Email ='kumarp@test.com';
        u.EmailEncodingKey = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        u.LocaleSidKey = 'en_US';
        u.TimeZoneSidKey = 'America/Los_Angeles';
        u.ProfileId = pr.Id;
        insert u;
        
        // Inserting  feedItems list
        List<FeedItem> feedItems = new List<FeedItem>();
        FeedItem f = new FeedItem();
        f.Body = 'This is test class';
        f.ParentId = u.Id;
        f.ContentDescription = 'this is test class for feed item';
        f.ContentFileName ='test file';
        f.Title ='test class';
        f.Type = 'PollPost';
        feedItems.add(f);
        insert feedItems;
        
        //Collabaration Group Insertion
        List<CollaborationGroup> collabarationgroup = new List<CollaborationGroup>();
         CollaborationGroup   CG = new CollaborationGroup();
         CG.Description = 'This is Collabarationgroup' ;
         CG.Name ='MYGroup';
         
         collabarationgroup.add(CG);
         insert collabarationgroup;
         
         // Collabaration Group Member Insertion
          List<CollaborationGroupMember> cgm = new  List<CollaborationGroupMember>();
          CollaborationGroupMember CGMember = new CollaborationGroupMember();
          //CGMember.CollaborationGroupId = CollaborationGroup.Id;
         // CGMember.MemberId = CollaborationGroup.Id;
         CGMember.CollaborationRole ='Standard';
          cgm.add(CGMember);
          insert cgm;  
         
        }
        }
I receive the following error when trying to save any of the classes in my developer console: "DEPLOYMENT ERROR: An unexpected error has occurred. 891009581-41899 (749494588) for deploymentId=1drK0000000qbfFIAQ If this persists, please contact customer support."

I've tried closing the developer console and re-opening it. As of writing, I've tried saving for roughly an hour with no luck. 
Batch Apex Code:
global class BatchApex implements Database.Batchable<sobject> {
    global DataBase.QueryLocator start(DataBase.BatchableContext bc){
        String query ='select id,name from account';
        return DataBase.getQuerylocator(query);
    }
    global void execute(DataBase.BatchableContext bc,List<Account> scope){
        List<Account> acc=new list<Account>();
        for(Account a:scope){
            a.name ='mr.'+a.name;
            scope.add(a);
        }
        update scope;
    }
    global void finish(DataBase.BatchableContext bc){
        
    }
        }

BatchApex b =new BatchApex();
Database.executeQuery(b,5);
Is it possible to load data into a tab panel only for the active tab?

I have multiple tabs on one of my pages, embedded with the <apex:tabpanel>

As these are quite large and loading times are slow, is it possible to only load the data from the methods on the current tab panel as oppose to all of them?

Thanks in advance 
Background:
Although I have coded, it's been in the mainframe world and, thus, I have no experience in Apex.  I went through the tutorial (Visualforce Workbook) and now am in the associated thicker book (Visualforce in Practice).  In Chapter 5 (Building Wizards), the exercise is to code three pages which call each other.  In a nutshell, you enter data about the parent and, when you click Continue, it saves the record and takes you to page 2 where you enter information about the child.  (Page 3 is about grandchildren--same idea--but I'm not there yet).  The three tables are related with a Master-Detail field.

Problem:
Page 1 information is saved and takes me to page 2.  When I click on Save, it's supposed to get the ID of the parent (it does--it's in the log) and then somehow save the child's record.  I don't think it's getting to that line (failure is indicated on the line after the get and before the insert) but have no clue why.  The errant line is in bold (about ten lines from the bottom).

I'd like to solve this myself but, since I don't know enough to know where to look, I figured I'd try here while I look elsewhere.  I've checked the online version of the book (http://www.developerforce.com/guides/Visualforce_in_Practice.pdf) but it has the same code as the book.  I've searched this forum and Google but no one has posted these exercises and I can't see how to relate posted solutions to this one.

Thanks in advance.

Mke
 

The code:
public class ProjectCreateExtension
{
private ApexPages.StandardController sc;
    public Sprint__c sprint {get; set;}
    public List<Sprint__c> sprints {get; set;}
    public String selectedSprint {get; set;}
   
    public ProjectCreateExtension(ApexPages.StandardController standardController)
    {
        // store a reference to the standard controller
        sc = standardController;
        sprint = new Sprint__c();
        // create a new list to store the sprints added by the user
     sprints = new List<Sprint__c>();
    }
   
    public PageReference ToPage1()
    {
        return Page.ProjectCreate1;
    }

    public PageReference ToPage2()
    {
        if (ApexPages.CurrentPage().GetURL().StartsWithIgnoreCase('/apex/projectcreate1'))
        {
            sc.Save();
            Project__c project = (Project__c)sc.GetRecord();
            sprint.Project__c = project.Id;
            insert sprint;
        }
            return Page.ProjectCreate2;       
    }

    public PageReference ToPage3()
    {
        return Page.ProjectCreate3;
    }
   
    public PageReference SaveSprint()
    {
        Project__c project = (Project__c)sc.GetRecord();
        sprint.Project__c = project.Id;
        insert sprint;
       
        sprints.Add(sprint);
        sprint = new Sprint__c();
       
        return null;
    }
       
}

An App provider is asking for "View Setup and Configuration" permission. From what I see in the user interface, this is the area related to all Developments.

I have two questions:
  1. If I grant them this permission, will they have the option of downloading all my code?
  2. What permissions are granted by "View Setup and Configuration" via API?
Any insight will be highly appreciated
     S.
Hiii,
             i am able to do the pagination using the standard controller but now i want to implement the pagination using the extensions in visualforce pages.
Hii ,
            can i define the width of <apex:pageBlock> manually ? I am able to define the size of <apex:pageBlockTable> but not of pageBlock .
      Normally <pageBlock > take full width of page but i want to override it. so if possible then please tell me .

 Thanks
 Rishav
I have a batch apex class that runs on my custom object successfully - but my trigger doesn't seem to fire. If i edit/save the record manually, trigger fires just fine. What am i missing here? Why doesn't the trigger fire when batch apex runs? 
Getting the following when trying to deploy a custom object using change sets. My object is unrelated to ActionPlans. I never even touched it. I promise.
 
ActionPlanCreationController.testActionPlanSave() Class 356 1 Failure Message: "System.LimitException: Too many DML rows: 10001", Failure Stack Trace: "Class.ActionPlansTaskTriggerUtilities.deleteTasks: line 356, column 1"
ActionPlanCreationController.testActionPlanSaveAndNew() Class 356 1 Failure Message: "System.LimitException: Too many DML rows: 10001", Failure Stack Trace: "Class.ActionPlansTaskTriggerUtilities.deleteTasks: line 356, column 1"
I have a question about the order of execution of intertwined triggers.  If a 'before' trigger causes updates to other records, does the second set of records go through the complete life cycle ('before' and 'update' triggers) before returning to the original trigger.  Or, does it just kickoff the second set and return immediately?  Is it undefined and could run in any order?

I have seen the help articles on order of execution, but they don't seem to address the intertwined scenario.

Any insight would be appreciated.

Thanks.
Hello,

I am using a standard object (Campaign) to track attendence at events.  Working with the "Total Contacts" field (automatically updated when a contact is added to campaign) and a custom "No of Attendees" field, I'm trying to create an Apex Trigger that updates the Campaign record with the current number of attendees whenever that number changes.  

Goal:  Anytime "Total Contacts" changes, I want to pass that value to the "No of Attendees" field.  

Here's what I've tried so far:
trigger AttendeeUpdate on Campaign (before update) {
    for (Campaign obj: trigger.new){
        No_of_Attendees__c = TotalContacts;
    }
}

Error Message:Compile Error: Variable does not exist: No_of_Attendees__c at line 3 column 9

Any help with this is greatly appreciated!
Ok I am new to Apex, this should be easy  but I am not finding a good resource manual. I have a Apex trigger to send an form email whenever a case changes owner.
What I'd like to do is include a link to the orginal case.

Here is what I think is the relevant lines as they exist

mail.setSubject('You are now the Owner of Case#:'+Trigger.new[i].CaseNumber);
                  mail.setPlainTextBody('Ownership of Case#:'+Trigger.new[i].CaseNumber+' has been set to you. Have a Nice Day.');

so I need to change this from plain text and include a field from the case containing the threadID so it'll link back to the case.
can that field be included?
Hi All,

I am trying to create test code for the Milestone Utilities Class, Trigger on Case Comment, Trigger on Email Message that has been published at

https://developer.salesforce.com/index.php?title=Auto-completion_of_Case_Milestones_with_Triggers&oldid=33636&language=en

The code I have found that I thought would complte this but could be totally wrong is 

@istest

public class CompleteMilestone{
 
  // test methods
  static testMethod void testCompleteMilestoneCase(){
   
    Contact oContact = [select id from Contact limit 1];
    String contactId;
    if (oContact != null)
      contactId = oContact.Id;
   
    Entitlement entl = [select id from Entitlement limit 1];
    String entlId;
    if (entl != null)
      entlId = entl.Id;
   
    List<Case> cases = new List<Case>{};
    if (entlId != null){
      Case c = new Case(Subject = 'Test Case with Entitlement ', EntitlementId = entlId, ContactId = contactId);
      cases.add(c);
    }
   
    // Insert the Account records that cause the trigger to execute.
    if (cases.isEmpty()==false){
      insert cases;
      List<Id> caseIds = new List<Id>();
      for (Case cL : cases){
        caseIds.add(cL.Id);
      }
      milestoneUtils.completeMilestone(caseIds, 'Response MAC', System.now());
        }
    }
 
    static testMethod void testCompleteMilestoneViaCase(){
     
        // Perform data preparation
        Entitlement entl = [select id from Entitlement limit 1];
        String entlId;
        if (entl != null)
            entlId = entl.Id;
        List<Case> cases = new List<Case>{};
        for(Integer i = 0; i < 1; i++){
            Case c = new Case(Subject = 'Test Case ' + i);
            cases.add(c);
            if (entlId != null){
                c = new Case(Subject = 'Test Case with Entitlement ' + i, EntitlementId = entlId);
                cases.add(c);
            }
        }
       
        // Insert the Account records that cause the trigger to execute.
        insert cases;

        List<CaseComment> ccs = new List<CaseComment>{};
        for(Case c : cases){
            CaseComment cc = new CaseComment(CommentBody='TestPublic', IsPublished=true, ParentId=c.Id);
            ccs.add(cc);
            cc = new CaseComment(CommentBody='TestPrivate', IsPublished=true, ParentId=c.Id);
            ccs.add(cc);
        }
        if (ccs.isEmpty()==false)
            insert ccs;
   
    // Now create emailmessage objects for them.
   
        List<EmailMessage> emails = new List<EmailMessage>();
        for(Case c : cases){
            emails.add(new EmailMessage(parentId = c.id));
        }
        if(emails.isEmpty()==false)
            database.insert(emails);
       
        for(Case c : cases){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddr = new String[] {'mramsey@salesforce.com'};
            mail.setToAddresses(toAddr);
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId(c.ContactId);
            mail.setWhatId(c.Id);
            mail.setHtmlBody('TestHTMLBody');
            mail.setPlainTextBody('TestTextBody');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
   
    for(Case c : cases){
      c.Status = 'Closed';
    }
    update cases;
   
        // Query the database for the newly inserted records.
        List<Case> insertedCases = [SELECT Subject,
                                           Description,
                                          (SELECT IsPublished, CommentBody From CaseComments),
                                          (SELECT TextBody, Subject, Incoming From EmailMessages)
                                           FROM Case
                                           WHERE Id IN :cases];
    }
}

But when I run the test it fails on line 8 colum 1
Contact oContact = [select id from Contact limit 1];

and line 38 column 1
Entitlement entl = [select id from Entitlement limit 1];

both have the following error

System.QueryException; List has no rows for assigment to Sobject

Thanks in advance for any help/pointers you give me