• sura
  • SMARTIE
  • 1330 Points
  • Member since 2011
  • Senior Software Engineer
  • attune


  • Chatter
    Feed
  • 35
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 11
    Questions
  • 313
    Replies
Hello,

For a person with read only acess to dashboard folder, how is it possible for him to save the dashboard.

Thanks
  • October 07, 2015
  • Like
  • 0
I have a SelectList which is dynamically built from the controller. But it doesn't seem to get run in the Test Class. How can I make sure its covered?
 
public List<SelectOption> getCountyList() {
        List<SelectOption> options = new List<SelectOption>();
        
        String counties = contactInfo[0].Preferred_Counties_for_Volunteering__c;
        
        if(!counties.contains(contactInfo[0].Home_County__c)) {
            
            options.add(new SelectOption(contactInfo[0].Home_County__c, contactInfo[0].Home_County__c));
        }
        
        List<String> prefCounties = counties.split(';', -2);
  		
        for(String pref : prefCounties) {
            
            options.add(new SelectOption(pref,pref));
    
        }
        
        return options;
    }

My Test Class currently
 
@isTest
public class ToTestFindNearby {

    static testMethod void testFindNearby () {
        
        PageReference pageRef = Page.FindNearby; 
        
        Contact contact = new Contact (LastName = 'Test', Are_you_an_Engineer__c = 'Engineer', Home_County__c = 'Waterford' );
        Account school = new Account (Name = 'Test', County__c = 'Waterford', Lat__c=5.0000, Lng__c=10.000, isMapped__c = true);
 		//Test.startTest();
        insert contact;
        insert school; 
        
        system.assertEquals(true, school.isMapped__c);
        
        date myDate = date.newInstance(2015, 11, 21);

        
        School_Visit__c schoolVisit = new School_Visit__c (School__c = school.id, Status__c = 'Open for Volunteering', 
                                      Topic__c = 'Science', How_many_students_in_the_class__c = 15, Requires_Irish_speaker__c = 'No',
                                      Preferred_Time__c = 'Afternoon', Date__c= myDate);
        
        School_Visit__c schoolVisit2 = new School_Visit__c (School__c = school.id, Status__c = 'Open for Volunteering', 
                                      Topic__c = 'Engineering', How_many_students_in_the_class__c = 15, Requires_Irish_speaker__c = 'No',
                                      Preferred_Time__c = 'Afternoon');
        
        School_Visit__c schoolVisit3 = new School_Visit__c (School__c = school.id, Status__c = 'Open for Volunteering', 
                                      Topic__c = '', How_many_students_in_the_class__c = 15, Requires_Irish_speaker__c = 'No',
                                      Preferred_Time__c = 'Afternoon');
        insert schoolVisit;
        insert schoolVisit2;
        insert schoolVisit3;
        //Test.stopTest();
       
        pageRef.getParameters().put('id', contact.id);
        Test.setCurrentPage(pageRef);
		FindNearby controller = new FindNearby();
        controller.backToContact();
        
    }
}

 
Hi All.
I have a scenario, where i need to create a Public Group through an Apex Class.
I need help.
Looking in a calc heavy apex class i inherited.  Probably a newbie question but.. I see this form alot in the class: 

SumCurrentSalesValueB = SumCurrentSalesValueB + (line.Current_Sales_Value__c != null ? Integer.ValueOf(line.Current_Sales_Value__c):0);  

 I assume the use of  "Line.Current_Sales_Value__c != null ?"  is basicly a test with the ":0)" the replacement value if true?  Seems to do that.  

I looked high and low thru the Apex doc - can anyoue point me to the  correct reference for this..  
 
Hey,
I am using apex:action 2 times. it is calling wrong action function everytime.

Here is the code
 
<apex:page standardController="Project__c" sidebar="false" showHeader="true" extensions="test3">
<apex:includeScript value="{!$Resource.modernizr}"/>
<script>
function doTheGeoThang() {
if (Modernizr.geolocation){
navigator.geolocation.getCurrentPosition(
function(position) {
findMe(position.coords.latitude,position.coords.longitude);
}
);
} else {
alert ("Your browser isn't hit. Upgrade man!");
}
}
</script>
<apex:form >
<apex:pageBlock >

<apex:actionRegion ><b><span style="cursor: pointer;"
onclick="doTheGeoThang()">
<center>Punch In</center>
</span>
</b><br/><br/>
<apex:actionFunction name="findMe" action="{!PunchIn}" rerender="jsvalues">
<apex:param name="lat" value="" assignTo="{!valueLat}"/>
<apex:param name="long" value="" assignTo="{!valueLong}"/>
</apex:actionFunction></apex:actionRegion>
</apex:pageBlock></apex:form>



<apex:form ><apex:actionRegion >
<b><span style="cursor: pointer;"
onclick="doTheGeoThang()">
<center>Punch Out</center>
</span>


</b><br/><br/>
<apex:actionFunction name="findMe" action="{!PunchOut}" rerender="jsvalues">
<apex:param name="lat" value="" assignTo="{!valueLat}"/>
<apex:param name="long" value="" assignTo="{!valueLong}"/>
</apex:actionFunction></apex:actionRegion>
</apex:form>


</apex:page>


here, when i click on punchin, it is calling punchout apex:actionfunction instead of punchin. i tried pageblock, apex:region , but everytime it is calling wrong method. please help me out here. 


Thanks
Hi All 

I got this Message from Salesforce when I tried to open one of my Home Component(Customize>> Home >> Home Components)
which its Type is HTML Area. Here is the messahe "This component contained unsupported elements that have been removed. Click continue editing the cleaned content".

User-added image

And once I opened it, there is nothig as it's totally cleaned. So, where can I get backup code?
Is it possible to find a backup of my code in Production or in any Sandbox. 
I googled it, and found this : http://docs.releasenotes.salesforce.com/en-us/summer14/release-notes/rn_forcecom_home_page_components.htm
Bug they don't mention about the backup code.

Best regards
Hello all,

I need help on a solution and for some reason I can not figure it out.  We have to many Admin (don't know why) here on Salesforce, with that I need to create my SOQL on the fly.  I currently have the module below for a few major sObjects and it works awesome. 
/*****************************************************************************************************
	Class Abreviations: S - Field, q - Built Query, c - Count
	
	Code class calling examples:
	Opportunity o =  Database.query(Utils.getOpportunityFields() +  ' limit 1');
	list<Opportunity> o =  Database.query(Utils.getOpportunityFields() +  ' where Id in: trigger.new');
	*****************************************************************************************************/
	
	public static string getOpportunityFields() 
	{
		List<String> f = new List<String>();
		Map<String, Schema.SobjectField> fields = Opportunity.getSObjectType().getDescribe().fields.getMap();
		string q = 'SELECT ';
		integer c = 1;
		for (String s: fields.keySet()) 
		{
			if (fields.get(s).getDescribe().isAccessible())
			{ 
				if(c == 1)
					q += s;
				else
					q += ', ' + s;
				c ++;
			}
		}

		return q + ' FROM Opportunity ';
	}



However, I would like it to work with all my objects but don't want to repeat the code over and over.  What I would like to be able to do but cannot figure it out (me stupid) is pass the sObject to one single piece of code.  I can not figure out how to send it or recieve the sObject like show below as <so>.

Any suggestions?
 
/*****************************************************************************************************
	Class Abreviations: S - Field, q - Built Query, c - Count
	
	Code class calling examples:
	Opportunity o =  Database.query(Utils.getOpportunityFields() +  ' limit 1');
	list<Opportunity> o =  Database.query(Utils.getOpportunityFields() +  ' where Id in: trigger.new');
	*****************************************************************************************************/
	
	public static string getOpportunityFields(sObject so) 
	{
		List<String> f = new List<String>();
		Map<String, Schema.SobjectField> fields = so.getSObjectType().getDescribe().fields.getMap();
		string q = ''; // required otherwise the first one is null.
		integer c = 1;
		for (String s: fields.keySet()) 
		{
			if (fields.get(s).getDescribe().isAccessible())
			{ 
				if(c == 1)
					q += s;
				else
					q += ', ' + s;
				c ++;
			}
		}

		return q;
	}

 
Hi,

i am getting an Error: Compile Error: Expression cannot be assigned at line -1 column -1 while saving this code. Can anyone please tell me where i made mistakes and what will be solution? 

public class Values
{
   public string rate{get; set;}
   @future(create=true)
   public static void create()
   {
       values val=new values();
       List<Account> Acc = new List<Account>();
   
       Acc = [Select id from Account where Minutes__c!=null];
       if(Account.Minutes__c = 'v1')
       {
          val.rate='$1.00'; 
       }
       if(Account.Minutes__c = 'v2')
       {
           val.rate='$2.00';
       }
       
   }
}
We have a custom field called Unique Email that is enforced to be unique.  This field is populated by a apex trigger that runs before inserting/updating.  I'm trying to use try/catch to take an alternate action if this error is experienced but the catch doesn't seem to be happening:

User-added image

Here is my code:

trigger uniqueEmail on Contact (before insert, before update) {

        for (Contact c : Trigger.new) {  
            try{
                c.Unique_Email__c = c.Email;
            }
          
            catch(Exception a){
                system.debug(c.id);
                c.Unique_Email__c = NULL;
                List<Contact> contactList = new list<Contact>();
                contactList = [SELECT Id,Email,Remove__c
                                    FROM Contact
                                    WHERE email = :c.Email AND id != :c.id
                                    LIMIT 100];
            
                for(Contact updateContact : contactList)
                {
                    updateContact.Remove__c = FALSE;
                    update updateContact;
                }
                if(c.id==Null){
                    c.Unique_Email__c = NULL;
                    Delete c;
                }
                else{
                    for(Contact cOld : trigger.old){
                        c.Unique_Email__c = NULL;
                    }
                    
                }
                //insert email code
            }
        }
    
}


 
Hi all,

  I am facing a proble with date when i upload a csv file in to salesforce in csv file i having the date filed as 9999/01/01,
when i am trying to upload the file its showing invalid date can u pleas help me on this.

thanks,
zabi
I'm trying to work with the FieldHistoryArchive object and am confused by versions. It shows as an object in the Spring 15 docs (which is the version we're on), but the implementation guide (https://help.salesforce.com/help/pdfs/en/field_history_retention.pdfOhNcQ&bvm=bv.95039771,d.aWw) seems to say it is for Summer 15. Anyone able to use this object (I'm trying to use it via SOQL)?
Hi,

Not accessible EmployeeNumber field of User object from Attachment Query whereas Name, Alias are accessible.
Plesae explain why am I not able to access EmployeeNumber.

API Version - 33.0
My Query is - SELECT Id,Name, CreatedBy.EmloyeeNumber FROM Attachment
Error - INVALID_FIELD: 
SELECT Id,Name, CreatedBy.EmloyeeNumber FROM Attachment
^
ERROR at Row:1:Column:17
No such column 'EmloyeeNumber' on entity 'Name'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.

Thanks.
I'm used to making test classes for inserting data in Objects but I'm kinda lost in making test data for this code...
(It retrieves the custom field names of my Custom Object mMovie__c)

public class objectlist {

  public List<string> fieldLabel {get;set;}
  
  public objectlist()
  {
    this.getAccountFields();
  }

  public void getAccountFields()
  {
          Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
          fieldLabel = new List<string>();      
          Map <String, Schema.SObjectField> fieldMap = gd.get('mMovie__c').getDescribe().fields.getMap();
          for(Schema.SObjectField fieldAPI : fieldMap.values())
          {     
              // if(fieldAPI.getDescribe().isCustom() )
              //{
               fieldLabel.add(fieldAPI.getDescribe().getLabel());
              //}
          }
          fieldLabel.sort();
          system.debug('fieldLabel-----'+fieldLabel);
  }     
}

 
The Trigger is supposed to run after another trigger has created the record. When the record is inserted, the trigger is called; but nothing happens. The trigger gives no errors and I have no idea why it doesn't work. Any help is greatly appreciated.
trigger TAMOCon_AssociatedChildUpdate on Topline_Account_Management__c (after insert) 
{
      
   for (Topline_Account_Management__c Tamo : Trigger.New)
   {
		List<contact> conToUpdate = new list <Contact>();

   for(contact Con : [select Id,D_T_TAMO_ID__c,LLC_AgreementNew__c
                      from Contact where D_T_TAMO_ID__c=:TAMO.Topline_Account_Management_Record_ID__c]) 
{ 

						Con.LLC_AgreementNew__c = 'Signed';
 						conToUpdate.ADD(Con);
                        update conToUpdate;
}}}
here is my code...

public class objectlist {
    //Do not forget to get instance in constructor for this list
    //String type='Account';
     Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
       List<string> fieldLable = new List<string>();
        
       Map <String, Schema.SObjectField> fieldMap = gd.get('Account').getDescribe().fields.getMap();
       for(Schema.SObjectField fieldAPI : fieldMap.values())
       {
               fieldLable.add(+ '<' +fieldAPI.getDescribe().getName()+ '/>' );
       }
       
       system.debug('fieldLable-----'+fieldLable);
}

IDK what part is wrong...pls help me fix this...THX!!!
Hello friends

I have wrriten apex class code to prevent duplicate contacts from being entered.
My apex class code and trigger code is working but my test class is failing.
Can anyone pls help me out?

apex code:
public class No_Account_Duplicates
{
   public void Display(list<Account> acc)
   {
      for(Account a:acc)
      {
         list<Account> myList=[select Name from Account where Name=:a.Name];
              if (myList.size()>0)
                 a.Name.addError('Account Name Already Exists');
      }
   }
}

apex trigger code:
trigger trg_NoDuplicates on Account (before Insert)
{
            if ((trigger.IsBefore) || (trigger.isInsert))
            {
                     No_Account_Duplicates obj=new No_Account_Duplicates();
                     obj.Display(trigger.new); //correct
            }    
    }


apex test class:
@istest(SeeAllData=false)
private class NoAccountDuplicates_Test
{
    private static testmethod void validatetest()
    {
          Account a1=new Account();
          a1.Name='Contact0';
          insert a1;
          
          Account a2=new Account();
           a2.Name='Contact0';
           insert a2;
           
           try 
           {
                        insert a2;
           }
           catch (DmlException e)
            {
                        //Assert Error Message
                   System.assert( e.getMessage().contains('Insert failed. First exception on ' + 'row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ' +
                                  'Account Name Already Exists'), 
                                  e.getMessage() );
                                   e.getDmlStatusCode(0);
                 }
               }
 }


I am getting error message as:
Error Message    System.AssertException: Assertion Failed: Insert failed. First exception on row 0 with id 0019000001OrsvvAAB;
first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Regards
sonali verma
 
Hi,

I have a LIST of userIds from the User object. In the Loginhistory object, userId is the reference field.
The LoginHistory maintains the login activities for all the users. Hence there are multiple record entries for each user.

How can I query and build a new LIST of the most recent LoginTime (one record per UserId) for each UserId, ensuring that the salesforce best practices are respected?
Any help would be greately appreciated.

Thanks,

Ajith
i have a simple apex program and i am trying to execute it from "developer console" i am getting this error.  " unexpected token: thisexample  at line 11"                  please help... thanks in advance

public class thisexample {
public integer age=10;
    public thisexample(integer age)
    {

        this.age=age;

System.debug('the value of age is '+age);    
}
}
thisexample t1=new thisexample(22);
t1.age;

Iam able to dispaly only one record out of 4duplicate records.

kindly help for me 


<apex:commandButton action="{!Next}" value="Check for Duplicates" status="status" reRender="duplicate"/>

 <apex:outputPanel id="duplicate">
              <apex:pageBlock title="Potential duplicates">
          <apex:pagemessage strength="2" title="Error!!" severity="error" detail="This Record Already Exists !!!" rendered="{!errormsg}"/><!-- End of error message -->
               <apex:pageblocktable rendered="{!NOT(ISNULL(existingcon))}" value="{!existingcon}" var="case" id="dup">
                               <apex:column headervalue="Select">
                                       <apex:commandlink action="{!SelectDuplicates}">
                                           <input type="radio" name="ContactSel"/>
                                       </apex:commandlink>                                         
                              </apex:column>
                              <apex:column headervalue="Name"> <apex:outputtext value="{!newcon.lastname}"/>  </apex:column>
                              <apex:column headervalue="Description"> <apex:outputtext value="{!newcon.email}"/>  </apex:column>
               </apex:pageblocktable>
     
 </apex:pageBlock>  </apex:outputPanel>


public List<Contact> chkdup;
public Contact newcon= new Contact();
public contact getcon()
 {
     return con;
 }
 public contact getexistingcon()
 {
     if (chkdup!= NULL)
     {
     if(chkdup.size()>0)
         return con;
     else
         return null;
     }
     else
         return null;
 }
public pagereference Next()
{
 chkdup=[select id,Lastname,Email from Contact where Lastname=:con.Lastname ];
 if(chkdup.size()>=0)
 {
      String tnum=con.Lastname;
     
      return null;
 }
 else
 {
       
       return null;
 }

}

Thanks
I have looked at the forums and for some reason, I think my code is complete, however, my page is not re-rendering.

When I click the commandbutton "Create Budget", it works in the background, it creates the budget, but the VF page does not refresh to show me the new budget related list.

Any help?

My VF page
<apex:page standardController="CCI_Project__c" extensions="budAddBudget">
    <apex:form>
    <apex:pageblock>
     <apex:pageblockButtons location="top">
                 <apex:commandButton value="Create Budget" action="{!addBudget}" reRender="bp"/>
            </apex:pageblockButtons>
     </apex:pageblock>
        <apex:outputPanel id="bp">
         <apex:repeat value="{!project}" var="p">
            <apex:pageBlock>
                <apex:pageBlockSection >
                    <apex:outputField value="{!p.Name}"/>
                    <apex:outputField value="{!p.Closed_Opportunity__c}"/>
                </apex:pageBlockSection>
        
                <apex:pageBlockTable value="{!p.Budgets__r}" var="b">
                    <apex:column value="{!b.Name}"/>
                    <apex:column value="{!b.Start_Date__c}"/>
                    <apex:column value="{!b.Total_Budget__c}"/>
                    <apex:column value="{!b.Total_Actual__c}"/>
                    <apex:column value="{!b.Total_Invoiced_to_Date__c}"/>
                </apex:pageBlockTable>
         
           
        </apex:pageBlock>
     </apex:repeat>
      </apex:outputpanel>
    </apex:form>
</apex:page>
The controlling class
public PageReference addBudget() {
        // Do code
        this.prj = (CCI_Project__c)standardController.getRecord();
        
        system.debug ('projId ' +prj.id);
        system.debug('a');

        proj = [Select ID, Name, Closed_Opportunity__c From CCI_Project__c Where Id=:prj.Id];
        // Call budgetAdd Method in class createBudget
            cb.budgetAdd(proj.id, proj.Closed_Opportunity__c);


        
        
        
        
        return null;
    
    }

Any suggestions GREATLY appreciated.
 
Hi All , 
I have a long runining real time (not future) operation in my production org and although it exceeds normal limit of 10000 ms it doesnt throw an error . when I check the debug log I saw this. Has Salesforce increased CPU limit ?
User-added image
  • June 01, 2016
  • Like
  • 0
Hi All ,

I have a visualforce page in production org which has started to give time limit exceed error at some times in last two days.Salesforce Server Status page doesnt display any performance issues at given times.It is not a page with a complex functionality or large amount of data.Other pages in the same org works find at the time page is giving the error .Any Idea on this
  • February 18, 2016
  • Like
  • 1
Hi guys , 
currently i am working on a performance improvement of salesforce Application.In that process one of my colleagus found an a post that said inline queries are much slower than the tradional queries https://www.youtube.com/watch?t=317&v=-edHmVGMkU0 (https://www.youtube.com/watch?t=317&v=-edHmVGMkU0) and we checked out and it seems to be true .some times to the extent of 5 times slower than tradional way. Since Salesforce recommend inline queries as a best practice this is really baffling.

only difference is inline quereis seems to consume much less heap 
eg:
 
for(Contact con :[Select Id,Name From Contact])
{

   system.debug('1111111111');

}

is much slower than 
List<Contact> con = [Select Id,Name From Contact];
for(integer i =0 ;i< con.size();i++)
{
    
    system.debug('1111111111');
    
}


 
  • October 07, 2015
  • Like
  • 0
My problem is as below
-------------------------------------
  • I want to update existing large number of records So I created a batch apex class to do that task (date loading is not an option becuase field values populated through a complex calculation)
  • but relevant object has a trigger calling future method my batch job fails
  • I cant deactivate or Edit the trigger because it is in manage package so  I cant edit or deactivate or even see it's code.
  • Is there any possible way to run my batch apex without failing (only option I can see is deactivate the trigger but even it is not possible since they are in a mange package)
  • July 27, 2015
  • Like
  • 0
Does anyone know a way to find the user who submitted the Approval request from apex code 
  • May 18, 2015
  • Like
  • 0

Hi Guys,

 

need some help My requirement is  as follows.

 

I want to find all records that given user is the owner irrespective of object type . Querying each objects owner field in multiple SOQL  s is not possible because I have 100+ objects .

 

If you can give me any guidance in this matter it is highly appreciated. 

  • May 08, 2013
  • Like
  • 0

Hi 

 

could anyone pls tell me is this possible ??

 

I have a visualforce page that uses standard controller , in that page I have few fields I have to set values dynamically using  ajax set method.

but object must be saved when save button is clicked including ajax set values as well as input field values. So far I think this is not possible

:smileyfrustrated:
  • April 10, 2012
  • Like
  • 0

Hi , guys  I am having trouble rendering a page element from inside  a visual force component 

 

Problem in breif is as follows

 

I have page  and that page contains  a custome (apex/visualforce )component and a panel group that contain  several out put panels.

 

In side the component I have a button ,

 

when that button is pressed in rerender one of the output panels on the page which is outside the component

 

problem is 

this doesnt work !!!!!!!!!!!!!!!!!!:manmad:

Any tips or clues on this matter will be really helpful , thanks

 

FYI : Component has a controller on its own

 

 

 

 

 

 

 Ex :Page code 

<apex:page >


<c:component > </c:component>

<apex:PanelGroup>

 <apex:outputPanel id="panel1" />

 <apex:outputPanel id="panel2" />

<apex:panelGroup>





</apex:page>

 

Ex:component

<apex:component controller="cont" >

<apex:commandLink rerender="panel1" />


</apex:component >

 


 

  • December 07, 2011
  • Like
  • 0

hi guys I am having trouble Assignning unique ids dynamically to visaul force page components inside a pageblock table since id element only allow String Literals as values ,

 

Does any one have work around for this ????

 

my code is as follows

<apex:pageblock id="pb2" rendered="{!employeesSearched}">           
               <apex:pageBlockTable id="feedbacktable" value="{!feedbackList}" var="item" rendered="{!employeesSearched}">
               <apex:column >
                  <apex:facet name="header">Employee Name</apex:facet>
                  <apex:outputField value="{!item.Employee__r.First_Name__c}"/>&nbsp;
                  <apex:outputField value="{!item.Employee__r.Last_Name__c}"/>
              </apex:column>
              <apex:column headerValue="Rating">
                 
                  
                <!--  <apex:inputHidden id="rating" value="{!item.Rating__c}" >
                  </apex:inputHidden>-->
                  
                  <input type="hidden" id="{!item.Employee__r.Id}" onfocus="testHidden(this)"/>
                  
                  <c:slider2 eId="{!item.Employee__r.Id}" width="100" />
                 
              </apex:column>   
              <apex:column >
                  <apex:facet name="header">Comment</apex:facet>
                  <apex:inputTextArea value="{!item.Comment__c}"></apex:inputTextArea>
              </apex:column>                
               </apex:pageBlockTable>

 <input type="hidden" id="{!item.Employee__r.Id}" onfocus="testHidden(this)"/> 

I have problem with above line

 

  • December 01, 2011
  • Like
  • 0

Hi , guys I am using an Apex Section header in my visual force page but I want to customize it 's look  accoding to my needs

 

specially font size and image ,

 

I you guys know how to do this pls reply

 

 

thanks.......

:smileywink:

  • November 21, 2011
  • Like
  • 0

Guys, I am developing an application that shares a controller between multiple pages.

In first page there is a form that contain multiple buttons.

on first page button one is pressed it calls a method and assign value  to Controller attribute and display that contents in the second page in a input field

 

Seond page contain a button to render same content in PDF format .when button is pressed  it redirects to a another page and display content in pdf format that Works fine !!!!!

 

On the first page there is a another button to directly show the content in PDF format by redirecting direcly to third page but that doesnt work  PDF is render as empty document

 

point to note

  • multiple pages share the same controller
  • content rendered as pdf
  • Same instance of the controller is used to access old value with out reinstantiation  (using PageReference.setredirect(false)  )

process works in two steps but same thing doesnt work in one step

step 1

public PageReference ViewMailInEditMode()

    
    {
        Map<String,String> formValues = new Map<String,String>();
        Id selectedEmp=employeeAssignment.Employee__c;
        String emailTemplate = this.emailTemplate;
        formValues.put('effectiveDate',String.valueOf(employeeAssignment.Effective_Date__c));
        formValues.put('id',selectedEmp);
        formValues.put('templateType',emailTemplate);
        if (emailTemplate.equals('Employee Extension'))
        {
            formValues.put('fromDate',String.valueOf(employeeAssignment.FromPeriod__c));
            formValues.put('toDate' ,String.valueOf(employeeAssignment.ToPeriod__c));
            formValues.put('currentDesignation',desgnationName);
            
        }
        EmailTemplates = new Email_Template__c();
        EmailTemplates.Body__c =EmailManager.CallMethod(formValues);
        PageReference pgRef = new PageReference('/apex/EmpAssignmentPrintview');
        pgRef.setRedirect(false);
        return pgRef;
    }

 

page 2

 

(printview)
  

<apex:page standardController="Employee_Assignment__c" extensions="EmployeeAssisgnmentExtension" id="page">
  
  <apex:pageBlock id="pageBlock1" >  
        <apex:form id="form1">
            <apex:inputField value="{!EmailTemplates.Body__c}"/>
            <apex:commandButton action="{!Save}" value="Print View"/>
        </apex:form>
    </apex:pageBlock> 
 </apex:page>

 step 2


  •  public PageReference Save()
        {
    
            PageReference pgRef = new PageReference('/apex/EmpAssignmentPrintview2');
            pgRef.setRedirect(false);
            return pgRef;
        }

     

    page 3 (printview2)
  • <apex:page standardController="Employee_Assignment__c" extensions="EmployeeAssisgnmentExtension" id="page" renderAs="pdf">
      <!-- Begin Default Content REMOVE THIS -->
      <apex:outputField value="{! EmailTemplates.Body__c}" />
      <!-- End Default Content REMOVE THIS -->
    </apex:page

     above code work fine

  • code that sum up above two steps to one

     public PageReference pdfview()
        {
            Map<String,String> formValues = new Map<String,String>();
            Id selectedEmp=employeeAssignment.Employee__c;
            String emailTemplate = this.emailTemplate;
            formValues.put('effectiveDate',String.valueOf(employeeAssignment.Effective_Date__c));
            formValues.put('id',selectedEmp);
            formValues.put('templateType',emailTemplate);
            if (emailTemplate.equals('Employee Extension'))
            {
                formValues.put('fromDate',String.valueOf(employeeAssignment.FromPeriod__c));
                formValues.put('toDate' ,String.valueOf(employeeAssignment.ToPeriod__c));
                formValues.put('currentDesignation',desgnationName);
                
            }
            
           // System.debug('ssssssssssssssssssssssssss');
            EmailTemplates = new Email_Template__c();
            EmailTemplates.Body__c =EmailManager.CallMethod(formValues);
            System.debug('ssssssssssssssssssssssssss'+ EmailTemplates.Body__c );
           
           PageReference pgRef1 = new PageReference('/apex/EmpAssignmentPrintview2');
           
            pgRef1.setRedirect(false);
           
            return pgRef1;
         } 

     the above code doesnt work 

Any help would be great  !!!!!!!!!!!!!!!!!!!!!

  • November 16, 2011
  • Like
  • 0
Hi All ,

I have a visualforce page in production org which has started to give time limit exceed error at some times in last two days.Salesforce Server Status page doesnt display any performance issues at given times.It is not a page with a complex functionality or large amount of data.Other pages in the same org works find at the time page is giving the error .Any Idea on this
  • February 18, 2016
  • Like
  • 1
I want to get all fields information which includes parent records details as well.
let suppose query is like, select * from contact.
Here contact is child object of Account, So i need account all feilds as well.

Is This Possiable?
Note: I wil have only recordID, based on i need all above info.
Any alternative soution other than Apex code?
Guys, please help me on this.
  • April 17, 2017
  • Like
  • 0
Hi,
I need to give Edit/View permission for custom fields user wise.So editing profile from Metadata api is not work out for me.
can u suggest me how to give FLS using permission set from Metadat API.
Hi, 
We're migrating data and I need to set the audit fields with created date which is a datetime format field. I tried everything but it just errors out on me. My current format is: mm/dd/yyyyThh:mm:ss".000GMT+01:00" 
However, this one won't work for me. Anybody knows the right format and has an example on how to set this in formatting in Excel?

Thanks
Hi Everyone, 

We are the developers of the Duplicate Check managed package in the AppExchange.
We now come across a client with a strange issue. 

Our package is able to show the field 'InformalName' on the Lead object via the FieldDescribe apex functions. However, when we run the same code via the DeveloperConsole on the same Org we cannot see the 'InformalName' field. 
 
Does anyone know what kind of field this is and why our package can see the field and the client itself cannot?
 
Thanks,
Sten
hi there,

Is there anyway to reset password for multiple users from apex?

the following can reset one user per transcation.
String newPassword = System.resetPassword(usrId ,false).getPassword();

Thanks in advance
LinThaw.
Hi All ,

I have a visualforce page in production org which has started to give time limit exceed error at some times in last two days.Salesforce Server Status page doesnt display any performance issues at given times.It is not a page with a complex functionality or large amount of data.Other pages in the same org works find at the time page is giving the error .Any Idea on this
  • February 18, 2016
  • Like
  • 1
Hello everyone, plz tell me how to write the test class for this trigger listed below..
trigger ConTest on Account(after insert,after Update)
{
 if(trigger.isInsert && trigger.isAfter)
 {
  List<Contact> lstCon = new List<Contact>();
  for(Account acc : trigger.new)
  {
   Contact con = new Contact();
   con.lastName=acc.Name;
   con.AccountId = acc.Id;
   lstCon.add(con);
  }
  insert(lstCon);
 }
 
 if(trigger.isUpdate && trigger.isAfter)
 {
  Map<Id,Account> mapACC = new Map<Id,Account>([select (select id,name from contacts) from account where id IN: trigger.new]);
  List<Contact> newCon = new List<Contact>();
  for(Account updatedAcc : trigger.New)
  {
   Account oldAcc = trigger.oldMap.get(updatedAcc.Id);
   if(mapACC.ContainsKEY(updatedAcc.Id) && oldAcc.Name != updatedAcc.Name)
   {
 for(Contact con : mapACC.get(updatedAcc.Id).contacts)
    {
     con.lastname = updatedAcc.Name;
     newCon.add(con);
    }
   }
  }
  update newCon;
 }
} 

Thanks in advance :)
Hi,

I am trying to develop S2S integration using canvas application. For that i followed http://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-canvas/ In that he asked to develop a VF(in service provider) which will be called in identity provider. 

VF code is as below
<apex:page showHeader="false">
    
    <script type="text/javascript" src="{!URLFOR($Resource.CanvasSDK,'SalesforceCanvasJavascriptSDK-master/js/canvas-all.js')}" />
    
    <script type="text/javascript">
        
        var sid="{!GETSESSIONID()}".substr(1,30) +'...';
    
    	function refreshSR(){
        	Sfdc.canvas.client.refreshSignedRequest(function(data){
            	
                if(data.status == 200){
                	var signedRequest = data.payload.response;
                    var part = signedRequest.split('.')[1];
                    var obj = JSON.parse(Sfdc.canvas.decode(part));
                    updateDisplay(obj) ;
                } 
            }); 
        }
    
    function updateDisplay(obj){
    	setValue('spSessionId', sid);
        setValue('ipOAuth', obj.client.oauthToken.substr(1,30)+'...');
        setValue('ipUser', obj.context.user.fullName);
        setValue('ipOrg', obj.context.organization.name);
        setValue('ipRefresh', obj.client.refreshToken.substr(1,30)+'...');
    }
    
    function setValue(eleId,val)
    {
       	var domEl = document.getElementById(eleId);
        if(domEl){
        	domEl.innerHTML = val;    
        }
    }
    
    Sfdc.canvas.onReady(function(){
    	refreshSR();
    });
         
    </script>
          
        <b> <u> Service Provider Org </u></b>  
        I am Canvas App from Salesforce Domain <b> Jitendra.zaa5@gmail.com </b>      
        User : {!$User.FirstName} {!$User.LastName} 
        Org : {!$Organization.Name}
        Session Id : <span id="spSessionId"></span>    

<hr />
 
        <b> <u> Identity Provider Org  - Current Org </u> </b>
        User : <span id="ipUser"></span>
         Org : <span id="ipOrg"></span>
         OAUth Token : <span id="ipOAuth"></span>
        Refresh Token : <span id="ipRefresh"></span>
     
</apex:page>

My VF page showing without the session id and informations of identity provider in identity provider entity as below
User-added image

How to get those values. I Need some one help to resolve it. 

Thanks.
 
friends
can we call Database.executebatch in trigger?
if yes, then how to do and if no what can be the limitation.
concrete example will be helpful

sonali​​​​
Hey All,

I have a trigger which i thought was bulkified, however when mass updating records through gridbuddy i still get the to many soql queries error.

Any help is appreciated.

below is the code of the trigger.

the map query is where it errors: 
 
trigger Fill_OneOff_Lookups on VG_One_Off_Planning__c (before update, before insert) {
            
            system.debug('test1 in trigger');
    
            list<id> UserIDs = new list<id>();
    		list<User> CurrentUsers = new list<User>();
    
            for (VG_One_Off_Planning__c OneoffLine : trigger.new)
            {               
                system.debug('test2 in for ' + OneoffLine);
                
                if(OneoffLine.ContactID__c != null)
                {
                	OneoffLine.Contact__c = OneoffLine.ContactID__c;
                }
                                
                if(OneoffLine.Al_ID__C != null)
                {
                	OneoffLine.Account_Location__c = OneoffLine.AL_ID__c;
                }
                OneoffLine.Account__c = OneoffLine.Location_Account_ID__c;                 
                system.debug('test3 in trigger' + OneoffLine.User_Id__c);
                if(OneoffLine.User_ID__c != null)  
                {
                	boolean ExecuteCode = true;
                   	/* if(trigger.IsUpdate){
                    
                        VG_One_Off_Planning__c OldPlanningRecord = System.Trigger.oldMap.get(OneOffLine.Id);
                        system.debug('test3 in trigger update' + OldPlanningRecord);
                        if(OneoffLine.User_ID__c == OldPlanningRecord.User_ID__c){
                            ExecuteCode = false;
                        }
                    }*/
                	system.debug('test4 ' + ExecuteCode);                
                	//if(ExecuteCode == true){               
                	UserIDs.add(Id.valueOf(Oneoffline.User_ID__c)); 
                }
            }         
    
    		Map<Id,User> GetUsers = new map<Id,User>([SELECT Id, IsActive FROM User WHERE Id in :UserIDs]);
    		currentusers = GetUsers.values();
    
    
    		for (VG_One_off_Planning__c oneoff : trigger.new)
            {
               	for(integer index =0; index <  CurrentUsers.size(); index++)
                {
                	if(CurrentUsers[index].IsActive == true && oneoff.User_ID__c == CurrentUsers[index].Id )
                	{             
                		Oneoff.OwnerId = Oneoff.User_ID__c;
                	}
				}
			}
}

With kind regards,
Thomas

Hi All,

I need to send an email to user. In salesforce usually from address will be the logged in user. Is it possible to set FROM address using apex code.

Please let me know the possible solution.

Thanks!

Hi,

Experts, i added button called 'Permit to dig'(i assigned a visualforce page to this button) to a object TWM_Tasks__c so this button  need to allow only with record type Intall and when the Type of install(Type_of_Install__c)='External' if its 'Internal or Screw in' it should not now allow it.could anyone help me please
Hello,

For a person with read only acess to dashboard folder, how is it possible for him to save the dashboard.

Thanks
  • October 07, 2015
  • Like
  • 0
Hi Guys,


I am new to this coding part....... I do't know even the basic of this apex classes.Please help out to reach out to learn this coding part .....
I wrote a trigger that edits the schedule of an opportunity product once it's created. Here's the trigger:

trigger editSchedule on OpportunityLineItem (after insert) {

if(Trigger.isInsert){

List<OpportunityLineItemSchedule> listOLIS = new List<OpportunityLineItemSchedule>();

for (OpportunityLineItem oli: Trigger.new){

Date myDate = Date.today();

for(Integer duration = (Integer)oli.Duration__c; duration == 0; duration--){

listOLIS.add(new OpportunityLineItemSchedule(OpportunityLineItemId = oli.Id, Quantity = 1, ScheduleDate = myDate));
myDate.addMonths(1);

}//end of inner for loop

}//end of for loop

insert listOLIS;

}//end of isInsert

}//end of trigger

Basically, it pulls in a custom field that I created called Duration, which is an integer representing how many months the client will be using the particular product. I want to add a schedule entry once a month based on the size of duration. For some reason though, when I add a product to an opportunity, my trigger doesn't change the schedule at all. 
I get the following error in the Data Loader cmd when trying to Upsert some custom object records;
"field name provided, does not match an external ID"

My GCD_ID__c field is categorised as an External ID and the same sdl file works perfectly when i use the Apex Data Loader tool rather than the cmd. So the mappings are definitely correct.

Maybe i am missing something in my xml file?