• jason.bradley
  • NEWBIE
  • 25 Points
  • Member since 2013

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 13
    Replies

Hello,

 

How would I go about using Batch Apex to insert a massive number of records? It seems like it's built for more updating records, as the start method returns a querylocator object based on an SOQL query, meaning the records that would be operated upon in the execute method would already have to exist in order to use Batch Apex to its potential.

I've attempted to simply return a list of objects in the start method, with that list being the records I want to insert, instead of a querylocator in the hopes that it would be divided up and operated upon by the Batch, but it never seems to actually reach the execute method. 

Can somehow return a fake querylocator based on the list of records I want to insert and have it divide it up correctly or will I have to resort to an inbound email handler in order to chain separate batches together that only handle up to 5000 inserts at a time? This seems like something that should have been relatively simple to do, I just haven't found the simple method yet. 

Also, the specific objects I'm trying to insert are FeedItem records, so I would like to avoid my previously mentioned strategy as it involved inserting blank records, strictly so that the query in the batch would pick up a correct number of objects, and that would mean that blank chatter posts would show up in client's feeds. 

I have a related list on an object, "Expense_Report__c" that contains all of the "Expense_Item__c" records that have to do with that expense report. I am trying to create a button on this related list on the parent "Expense_Report__c" record that will operate on the "Expense_Item__c" records that were selected via checkboxes in the related list.

 

The button is a Custom List Button that is supposed to execute the specified Javascript when it is clicked.

This is the code I have in that button so far:

{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}
var idArray = {!GETRECORDIDS($ObjectType.Expense_Item__c)};
//alert("The Ids you have selected are: "+idArray);

var recordArray = [];

for (var i = 0; i < idArray.length; i++)
{
recordArray[i] = sforce.connection.query("SELECT ID, Name, Expense_Report__c FROM Expense_Item__c WHERE ID = '" + idArray[i] + "'").getArray('records');
alert("Object ID: " + recordArray[i]);
//alert("SELECT ID, Name, Expense_Report__c FROM Expense_Item__c WHERE ID = '" + idArray[i] + "'");
}

 

This brings up an alert dialogue with the following as the body:

Object ID: {type:'Expense_Item__c', Id:'a0Kg239939399U4iEAE', Name:'EI-00013168', Expense_Report__c:'a0Jg00000009I1QDJE', }

 The ID's represented here aren't what the page actually shows, I just filled in random values, but the ID's that it does show were correct.

 

The problem occurs when I try to access the ID, or any field really, of any Expense_Item__c records in that array, as follows:

alert("Object ID: " + recordArray[i].Id);

 

I get an alert that contains the following:

Object ID: undefined

 

Am I attempting to access these fields correctly or is there some special way I need to try to access them?

This is my first attempt to interact with Force.com through Javascript, so I'm not entirely sure how to do these things.

 

Thanks in advance.

Hello,

 

I have a VF page that is rendered as a PDF and embedded within another VF page via an iframe so that I can interact with it via Javascript. For some reason, Firefox for mac is rendering the font much bigger than it should, forcing the text down to the next line and overwritting it. The PDF renders correctly in Safari, Firefox, Chrome and IE 9 for Windows as well as Safari and Chrome for mac, but for some reason Firefox for mac renders it differently. 

 

The only way I can think to fix this is the have a separate stylesheet with a smaller font size that is used when the user is using Firefox on a Mac. Is there an easier way of fixing this than that?

Hello,

 

I'm attempting to come up with an algorithm to find the start year of a year long fiscal period that applies to a given date, based on the start month and day of the fiscal period every year.

 

Currently, I calculate the days between the date passed in and the date that the fiscal period will change in the same year. If the number of days is positive (the current date falls within the last fiscal period), then I return the current year - 1. 

Otherwise, I return the current year.

 

Here are the specific methods that I am using to calculate this:

    global Integer getIndexInListStr(List<String> strList, String strToFind)
    {
    	for (Integer j = 0; j < strList.size(); j++)
    	{
    		if (strList.get(j) == strToFind)
    		{
    			return j;
    		}
    	}
    	return null;
    }
    
    global Integer getOffPeriodStartYear(Date d, Integer periodStartMonth, Integer periodStartDay)
    {
    	Date tempPeriodStartDay = Date.newInstance(d.year(), periodStartMonth, periodStartDay);
    	
    	if (d.daysBetween(tempPeriodStartDay) > 0)
    	{
    		return (tempPeriodStartDay.year() - 1);
    	}
    	else
    	{
    		return tempPeriodStartDay.year();
    	}
    }

 

This is where I am calling on these methods in order to find this value:

Fiscal_Period_Year__c = String.valueOf(getOffPeriodStartYear(currentCalendarDate, (getIndexInListStr(monthNames, fiscalStartMonth) + 1), fiscalStartDay));

 

This is all in a loop that is within a batch Apex class, but assume that currentCalendarDate is 2/1/1990, monthNames is just a list full of the names of each month, fiscalStartMonth is February, and fiscalStartDay is the 1st. 

 

When I think through this logically, it would think that it would say that the fiscal period start year on 2/1/1990 is 1990, as it should, but for some reason, it doesn't begin to label the fiscal start year as 1990 instead of 1989 until April 1st. I have not been able to figure out why.

 

Thanks in advance to anyone that can help!

Hello,

 

I'm trying to write a batch Apex class that will generate a new record for each day between two dates that are retreived from the user with information on the day already filled in in different ways. The object, Time_Dimension__c has quite a few fields, either dates or strings for the most part, and one unique field, Date_Key_Unique__c. 

 

On the test page I've written, I have been inputting the start date as 2/28/2012 and the end date as 2/26/2013. 

The biggest problem is that every field on these records except for Name is blank. I looked at the Apex Jobs page to see what the issue was, and this is what it displays:

First error: Update failed. First exception on row 1 with id a1eg0000000CuwOAAS; first error: DUPLICATE_VALUE, duplicate value found: unknown duplicates value on record with id: a1eg0000000Cus3: []

 

 Here is the Apex class I've written to accomplish this:

global class TimeDimensionGenerator implements Database.Batchable<sObject>, Database.Stateful {
	
	Integer calendarStartYear {get; set;}
	Integer calendarEndYear {get; set;}
	String fiscalStartMonth {get; set;}
	String fiscalStartDay {get; set; }
	String actuarialStartMonth {get; set;}
	String actuarialStartDay {get; set;}
	String policyStartMonth {get; set;}
	String policyStartDay {get; set;}
	
	Date startDate {get; set;}
	Date endDate {get; set;}
	
	global final string query;
	
	Time_Dimension__c lastTimeDimensionOfLastScope {get; set;}
	
	List<String> monthNames = new List<String>();
	
	//Date counters
	Date currentCalendarDate {get; set;}
	
	global TimeDimensionGenerator(Integer calendarStartYear, Integer calendarEndYear, String fiscalStartMonth, String fiscalStartDay, String actuarialStartMonth, String actuarialStartDay, String policyStartMonth, String policyStartDay)
	{
		this.calendarStartYear = calendarStartYear;
		this.calendarEndYear = calendarEndYear;
		this.fiscalStartMonth = fiscalStartMonth;
		this.fiscalStartDay = fiscalStartDay;
		this.actuarialStartMonth = actuarialStartMonth;
		this.actuarialStartDay = actuarialStartDay;
		this.policyStartMonth = policyStartMonth;
		this.policyStartDay = policyStartDay;
		
		monthNames.add('January');
		monthNames.add('February');
		monthNames.add('March');
		monthNames.add('April');
		monthNames.add('May');
		monthNames.add('June');
		monthNames.add('July');
		monthNames.add('August');
		monthNames.add('September');
		monthNames.add('October');
		monthNames.add('November');
		monthNames.add('December');
		
		startDate = Date.newInstance(calendarStartYear, 1, 1);
		endDate = Date.newInstance(calendarEndYear, 12, 31);
		
		List<Time_Dimension__c> timeDims = new List<Time_Dimension__c>();
		for (Integer i = 0; i < startDate.daysBetween(endDate); i++)
		{
			Time_Dimension__c t = new Time_Dimension__c();
			timeDims.add(t);
		}
		insert timeDims;
		
		currentCalendarDate = startDate;
		
		query = selectAll('Time_Dimension__c');
	}
	
	global Database.queryLocator start(Database.BatchableContext context)
	{
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext context, List<SObject> scope)
	{
		
		List<Time_Dimension__c> timeDims = (List<Time_Dimension__c>)scope;
		if (lastTimeDimensionOfLastScope != null)
		{
			
		}
		else
		{
			
		}
		
		for (Integer i = 0; i < timeDims.size(); i++)
		{
			timeDims[i].Date__c = currentCalendarDate;
			timeDims[i].Year__c = String.valueOf(currentCalendarDate.year());
			timeDims[i].Day_Number_in_Month__c = currentCalendarDate.day();
			timeDims[i].Day_of_Week_Long__c = dayOfWeek(currentCalendarDate);
			timeDims[i].Day_of_Week_Short__c = timeDims[i].Day_of_Week_Long__c.substring(0, 3);
			timeDims[i].Long_Month_Description__c = String.valueOf(monthNames.get(currentCalendarDate.month() - 1));
			timeDims[i].Day_Full_Description__c = String.valueOf(timeDims[i].Day_of_Week_Long__c + ', ' + timeDims[i].Long_Month_Description__c + ' ' + currentCalendarDate.day() + ', ' + currentCalendarDate.year());
			timeDims[i].Date_Key_Unique__c = String.valueOf(currentCalendarDate.year() + currentCalendarDate.month() + currentCalendarDate.day());
			//timeDims[i].Month_Description__c = timeDims[i].Long_Month_Description__c.substring(0, 3);
			timeDims[i].Month_Key__c = String.valueOf(currentCalendarDate.year() + currentCalendarDate.month());
			timeDims[i].Month_Number__c = currentCalendarDate.month();
			timeDims[i].Calendar_End_Date__c = Date.newInstance(currentCalendarDate.year(), 12, 31);
			timeDims[i].Calendar_Start_Date__c = Date.newInstance(currentCalendarDate.year(), 1, 1);
			timeDims[i].Calendar_Month_Start_Date__c = Date.newInstance(currentCalendarDate.year(), currentCalendarDate.month(), 1);
			timeDims[i].Calendar_Month_End_Date__c = Date.newInstance(currentCalendarDate.year(), currentCalendarDate.month(), Date.daysInMonth(currentCalendarDate.year(), currentCalendarDate.month()));
			timeDims[i].Quarter_Number__c = getQuarterNumber(currentCalendarDate);			
			timeDims[i].Quarter_Description__c = 'Q' + timeDims[i].Quarter_Number__c;
			timeDims[i].Quarter_Key__c = currentCalendarDate.year() + timeDims[i].Quarter_Description__c;
			timeDims[i].Short_Month_Description__c = timeDims[i].Long_Month_Description__c.substring(0, 3);
			timeDims[i].Short_Month_and_Year__c = timeDims[i].Short_Month_Description__c + '0' + timeDims[i].Year__c.substring(2);
			
			
			//Last Things
			currentCalendarDate = currentCalendarDate.addDays(1);
			System.debug(currentCalendarDate);
			
			//update timeDims[i];
		}
		
		update timeDims;
		
		//Last Things
		lastTimeDimensionOfLastScope = timeDims[timeDims.size() - 1];
	}
	
	global void finish(Database.BatchableContext context)
	{
		
	}
	
	global String selectAll(string sfo){
	    String SOQL;
        map<String, schema.sobjecttype> allSObjects = schema.getglobaldescribe();
        schema.sobjecttype q = allsobjects.get(sfo);
        schema.describesobjectresult d = q.getdescribe();
        map<String, schema.sobjectfield> m = d.fields.getmap();
        set<String> s = m.keyset();
        string k = '';
        for(String f : s){
            k = k+f+', ';
        }
        k = k.substring(0,k.length()-2);
        SOQL = 'SELECT ' + k + ' FROM ' + sfo;
        
        return SOQL;
    }
    
    global String dayOfWeek(Date dt)
    {
    	
    	DateTime d = DateTime.newInstance(dt.year(), dt.month(), dt.day(), 0, 0, 0);
    	return d.format('EEEE');
    }
    
    global Integer getQuarterNumber(Date d)
    {
    	Integer qNum;
    	if (d.month() <= 3)
		{
			qNum = 1;
		}
		if (d.month() >= 4 && d.month() <= 6)
		{
			qNum = 2;
		}
		if (d.month() >= 7 && d.month() <= 9)
		{
			qNum = 3;
		}
		if (d.month() >= 10 && d.month() <= 12)
		{
			qNum = 4;
		}
		
		return qNum;
    }
}

 

Here is how I am calling the batch:

TimeDimensionGenerator gen = new TimeDimensionGenerator(dummy.Calendar_Start_Year__c.year(), dummy.Calendar_End_Year__c.year(), '', '', '', '', '', '');
		ID batchprocessid = Database.executeBatch(gen);

 

The dummy variable that is reference here is just an extra object I created to allow me to use the inputFields with the date picker and store the inputted data in one place. It's only used on the page I've created to test the generation of the TimeDimensions.

 

I've already wasted at least half a day trying to figure out what's going wrong and have yet to get anywhere, so any help from some more experienced Salesforce users would be amazing right now.

Hello,

 

I have an inputField set to a lookup relationship of type Contact. When the lookup button next to the inputField is pressed, it returns every contact that matches up with the name entered. I want to limit the results of that search to contacts with a specific account value. Basically what I'm trying to accomplish is to allow the user to select the contact record of the person that is escorting a visitor into our workplace. It wouldn't make sense that they could select someone that doesn't work at the company as an escort.

 

Can I do this in some way?

 

I thank anyone that can help.

Hello,

 

I recently converted a page I had that used inputText components to obtain input to using inputFields instead because those include the lookup button. In the previous rendition of the page, I could easily handle the case in which no contact records with a name matching the one entered in by the user were found just by checking to see if the text in the box was null or empty. Now, it seems that if a matching record is not found, the message "Error: No matches found." pops up below the inputField box without running the method that is suppposed to be called when a commandButton is pressed. This makes it sort of difficult to handle this if it isn't running through any of the logic I've written to attempt to handle this. What I want the page to continue to do is to make a new record with the information inputted if a matching record is not found, but I can't seem to do that when it isn't running through the code like it is supposed to. Is there a way to handle this scenario through the page's controller so that I have the freedom to handle it in any way I wish?

 

I thank anyone that is able to help.

Hello,

 

I have an object representing an entry in a visitor log. That object has a few custom fields, Brought_by_Employee__c, Checking_In__c, Contact__c, Escort__c, Time_In__c, Time_Out__c, Title__c and Visitor_Name__c. Thus far, I've built a VisualForce page that has inputText components so that the user can type in their name, the name of the company they work for, their title in the company, etc. The page is using a custom controller that I've written with the visitor's name stored as a String. I wanted to make it easier for my users to check in if they've checked in previously and the best way to do that seemed to be to use inputFields instead because they give you a lookup button next to the inputField. At first it seemed like I would have to rewrite my custom controller to be used as an extension to the Contact standard controller in order to get the inputField working right. Then I tried just creating an empty visitor log entry, because it has a contact field so I thought that perhaps that would correclty bring up the lookup list. It did, but now I can't think of a way to get just the name of the contact they selected. Even though all it seems to be doing is filling in the inputField with the name of the contact, it looks like it's really storing the contact record itself. I need the name of the contact sent back to the controller so that the rest of the logic can be executed. I tried referencing the "phantom" log entry's Contact field to see if that was where the selected record on the VF page had been stored, but this yields the error "Error: You must enter a value" underneath the inputField. Not to mention that another inputField that was previously only required if a check box was selected also gives this error if it is not filled in. Is it possible to get this to work without rewriting my controller as an extension or is my attempt to get lookup buttons working a lost cause?

 

The first line in the constructor of the controller sets the String visitorName to testLog.Contact__r.Name. This was my test to see if the selected contact had been stored in the phantom record I had created in order to access the existing contact records. 

 

I greatly thank anyone that can give me some insight here.

Hi,

 

I need to be able to print cards that have someone's name and whatnot else on it. I already have a VF page for inputting this information. I would like to be able to dynamically create a VF page from the controller in the original VF page that gathers the correct info, open the newly created VF page so that the user can see it while at the same time bringing up the print dialogue via a javascript call in the header. My current attempt at this from what I have managed to find online looks as follows:

 

public PageReference createCard(String name, String company, String title)
    {
        Component.Apex.Page card = new Component.Apex.Page();
        Component.Apex.Form form = new Component.Apex.Form();
        Component.Apex.OutputLabel visitorName = new Component.Apex.OutputLabel();
        Component.Apex.OutputLabel visitorCompany = new Component.Apex.OutputLabel();
        Component.Apex.OutputLabel visitorTitle = new Component.Apex.OutputLabel();

        visitorName.value='name';
        visitorName.style='text-align:center; font-size:24pt;';
        
        visitorCompany.value='name';
        visitorCompany.style='text-align:center; font-size:24pt;';
        
        visitorTitle.value='name';
        visitorTitle.style='text-align:center; font-size;24pt;';
        
        form.childComponents.add(visitorName);
        form.childComponents.add(visitorCompany);
        form.childComponents.add(visitorTitle);
        
        //Stop point
        
        return null;
    }

 

At this point I am stuck. Since the page object does not have a childComponents field, I'm not sure how to add the form to that. I am not even entirely sure that what I have done so far is right. 

Right now I was attempting to be able to return a PageReference so that the user would be sent to the newly created page and proceed from there, but with this I'm not sure how to attach any JavaScript either. Is there a better way to go about doing this?

Hello,

 

I have been looking around for a way to print, well anything really, to a printer when a commandButton is pressed, without bringing up a dialogue in which the user can manipulate settings and then tell the document to print. This application is only going to be used on one computer at a front desk in order to print badges anyways, so there is no need to change the print settings before printing the document. All of the solutions I have found so far to print things in general involve the javascript function "print()" being called from the window or whatever object needs to be printed but as I have come to understand, this brings up the system's print dialogue.

If there is not a way to do this from the VisualForce page itself due to security issues, would I be able to send information that is entered into the VisualForce page itself to a small java app or applet that would print the information without a dialogue?

 

I would greatly appreciate anyone's input on this.

Hello to all,

 

I am working on a VisualForce page that would serve as a visitor log at a front desk or something such as that.

This is a learning experience of sorts, so the solution to my problem may very well be simple and I just have not caught it.

The error I recieve upon opening up my VisualForce page says "Attempt to de-reference a null object". Any other errors I have encountered thus far were fixable because the error page had a little more detail than this.

 

Here is my VF page:

<apex:page controller="VisitorLogController" sidebar="false">
    <apex:sectionHeader title="Visitor Log"/>
    
    <div style="text-align:center;">
    <apex:form id="visitorLogForm">
        <div style="float:left;width:25%;">
            Visitor Name: <apex:inputText value="{!visitorName}"/>
        </div>
        <div style="float:left;width:25%;">
            Company Name: <apex:inputText value="{!company}"/>
        </div>
        <div style="float:left;width:25%;">
            Title in Company: <apex:inputText value="{!title}"/>
        </div>
        <div style="float:right;width:25%;">
            <apex:commandButton action="{!checkIn}" value="Check In"/>            
        </div>
        
        <apex:pageBlock>
            <apex:pageBlockTable value="{!logEntriesCheckedIn}" var="log" id="logEntryTable" rendered="{!recordsObtained}">
                <apex:column value="{!log.Visitor_Name__c}"/>
                <apex:column value="{!log.Company__c}"/>
                <apex:column value="{!log.Title__c}"/>
                <apex:column headerValue="Check Out">
                    <apex:commandButton value="Check Out"/>
                    <apex:actionSupport event="onclick" action="{!checkOut}" rerender="true">
                        <apex:param name="logID" value="{!log.Name}"/>
                    </apex:actionSupport>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
    </div>
</apex:page>

 

This is my controller:

public class VisitorLogController {
    
    public String visitorName {get; set;}
    public String company {get; set;}
    public String title {get; set;}
    
    public Boolean recordsObtained {get; set;}
    
    public List<Visitor_Log_Entry__c> logEntries {get; set;}
    public List<Visitor_Log_Entry__c> logEntriesCheckedIn {get; set;}
    
    public VisitorLogController() {
        recordsObtained = false;
        logEntries = [Select Name, Visitor_Name__c, Title__c, Company__c, Contact__c, Checked_In__c, Time_In__c, Time_Out__c from Visitor_Log_Entry__c limit 1000];
        for (Visitor_Log_Entry__c l : logEntries)
        {
            if (l.Checked_In__c == true)
                logEntriesCheckedIn.add(l);
        }
        recordsObtained = true;
    }
    
    public PageReference checkIn()
    {
        Account account = new Account(Name=company);
        upsert account;
        
        Contact contact = new Contact(FirstName=visitorName.split(' ', 2)[0], LastName=visitorName.split(' ', 2)[0], Job_Position__c = title, Account = account);
        upsert contact;
        
        Visitor_Log_Entry__c newEntry = new Visitor_Log_Entry__c(Checked_In__c = true, Company__c = company, Contact__c = contact.id, Time_In__c = System.now(), Title__c = title, Visitor_Name__c = visitorName);
        insert newEntry;
        
        return null;
    }
    
    public PageReference checkOut()
    {
        String entryID = ApexPages.currentPage().getParameters().get('logID');
        Visitor_Log_Entry__c focusEntry = [Select Name, Checked_In__c, Time_Out__c from Visitor_Log_Entry__c where name = :entryID limit 1];
        
        focusEntry.Checked_In__c = false;
        
        Datetime nowLocal = System.now();
        
        focusEntry.Time_Out__c = nowLocal;
        
        update focusEntry;
        return null;
    }
}

 

A great many thanks to anyone that is willing to help lead me in the right direction. I would also appreciate any other pointers that can be given as well, I am not all that sure I have taken the best approach to some of the working of this page.

Hello,

 

How would I go about using Batch Apex to insert a massive number of records? It seems like it's built for more updating records, as the start method returns a querylocator object based on an SOQL query, meaning the records that would be operated upon in the execute method would already have to exist in order to use Batch Apex to its potential.

I've attempted to simply return a list of objects in the start method, with that list being the records I want to insert, instead of a querylocator in the hopes that it would be divided up and operated upon by the Batch, but it never seems to actually reach the execute method. 

Can somehow return a fake querylocator based on the list of records I want to insert and have it divide it up correctly or will I have to resort to an inbound email handler in order to chain separate batches together that only handle up to 5000 inserts at a time? This seems like something that should have been relatively simple to do, I just haven't found the simple method yet. 

Also, the specific objects I'm trying to insert are FeedItem records, so I would like to avoid my previously mentioned strategy as it involved inserting blank records, strictly so that the query in the batch would pick up a correct number of objects, and that would mean that blank chatter posts would show up in client's feeds. 

I have a related list on an object, "Expense_Report__c" that contains all of the "Expense_Item__c" records that have to do with that expense report. I am trying to create a button on this related list on the parent "Expense_Report__c" record that will operate on the "Expense_Item__c" records that were selected via checkboxes in the related list.

 

The button is a Custom List Button that is supposed to execute the specified Javascript when it is clicked.

This is the code I have in that button so far:

{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}
var idArray = {!GETRECORDIDS($ObjectType.Expense_Item__c)};
//alert("The Ids you have selected are: "+idArray);

var recordArray = [];

for (var i = 0; i < idArray.length; i++)
{
recordArray[i] = sforce.connection.query("SELECT ID, Name, Expense_Report__c FROM Expense_Item__c WHERE ID = '" + idArray[i] + "'").getArray('records');
alert("Object ID: " + recordArray[i]);
//alert("SELECT ID, Name, Expense_Report__c FROM Expense_Item__c WHERE ID = '" + idArray[i] + "'");
}

 

This brings up an alert dialogue with the following as the body:

Object ID: {type:'Expense_Item__c', Id:'a0Kg239939399U4iEAE', Name:'EI-00013168', Expense_Report__c:'a0Jg00000009I1QDJE', }

 The ID's represented here aren't what the page actually shows, I just filled in random values, but the ID's that it does show were correct.

 

The problem occurs when I try to access the ID, or any field really, of any Expense_Item__c records in that array, as follows:

alert("Object ID: " + recordArray[i].Id);

 

I get an alert that contains the following:

Object ID: undefined

 

Am I attempting to access these fields correctly or is there some special way I need to try to access them?

This is my first attempt to interact with Force.com through Javascript, so I'm not entirely sure how to do these things.

 

Thanks in advance.

Hello,

 

I'm trying to write a batch Apex class that will generate a new record for each day between two dates that are retreived from the user with information on the day already filled in in different ways. The object, Time_Dimension__c has quite a few fields, either dates or strings for the most part, and one unique field, Date_Key_Unique__c. 

 

On the test page I've written, I have been inputting the start date as 2/28/2012 and the end date as 2/26/2013. 

The biggest problem is that every field on these records except for Name is blank. I looked at the Apex Jobs page to see what the issue was, and this is what it displays:

First error: Update failed. First exception on row 1 with id a1eg0000000CuwOAAS; first error: DUPLICATE_VALUE, duplicate value found: unknown duplicates value on record with id: a1eg0000000Cus3: []

 

 Here is the Apex class I've written to accomplish this:

global class TimeDimensionGenerator implements Database.Batchable<sObject>, Database.Stateful {
	
	Integer calendarStartYear {get; set;}
	Integer calendarEndYear {get; set;}
	String fiscalStartMonth {get; set;}
	String fiscalStartDay {get; set; }
	String actuarialStartMonth {get; set;}
	String actuarialStartDay {get; set;}
	String policyStartMonth {get; set;}
	String policyStartDay {get; set;}
	
	Date startDate {get; set;}
	Date endDate {get; set;}
	
	global final string query;
	
	Time_Dimension__c lastTimeDimensionOfLastScope {get; set;}
	
	List<String> monthNames = new List<String>();
	
	//Date counters
	Date currentCalendarDate {get; set;}
	
	global TimeDimensionGenerator(Integer calendarStartYear, Integer calendarEndYear, String fiscalStartMonth, String fiscalStartDay, String actuarialStartMonth, String actuarialStartDay, String policyStartMonth, String policyStartDay)
	{
		this.calendarStartYear = calendarStartYear;
		this.calendarEndYear = calendarEndYear;
		this.fiscalStartMonth = fiscalStartMonth;
		this.fiscalStartDay = fiscalStartDay;
		this.actuarialStartMonth = actuarialStartMonth;
		this.actuarialStartDay = actuarialStartDay;
		this.policyStartMonth = policyStartMonth;
		this.policyStartDay = policyStartDay;
		
		monthNames.add('January');
		monthNames.add('February');
		monthNames.add('March');
		monthNames.add('April');
		monthNames.add('May');
		monthNames.add('June');
		monthNames.add('July');
		monthNames.add('August');
		monthNames.add('September');
		monthNames.add('October');
		monthNames.add('November');
		monthNames.add('December');
		
		startDate = Date.newInstance(calendarStartYear, 1, 1);
		endDate = Date.newInstance(calendarEndYear, 12, 31);
		
		List<Time_Dimension__c> timeDims = new List<Time_Dimension__c>();
		for (Integer i = 0; i < startDate.daysBetween(endDate); i++)
		{
			Time_Dimension__c t = new Time_Dimension__c();
			timeDims.add(t);
		}
		insert timeDims;
		
		currentCalendarDate = startDate;
		
		query = selectAll('Time_Dimension__c');
	}
	
	global Database.queryLocator start(Database.BatchableContext context)
	{
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext context, List<SObject> scope)
	{
		
		List<Time_Dimension__c> timeDims = (List<Time_Dimension__c>)scope;
		if (lastTimeDimensionOfLastScope != null)
		{
			
		}
		else
		{
			
		}
		
		for (Integer i = 0; i < timeDims.size(); i++)
		{
			timeDims[i].Date__c = currentCalendarDate;
			timeDims[i].Year__c = String.valueOf(currentCalendarDate.year());
			timeDims[i].Day_Number_in_Month__c = currentCalendarDate.day();
			timeDims[i].Day_of_Week_Long__c = dayOfWeek(currentCalendarDate);
			timeDims[i].Day_of_Week_Short__c = timeDims[i].Day_of_Week_Long__c.substring(0, 3);
			timeDims[i].Long_Month_Description__c = String.valueOf(monthNames.get(currentCalendarDate.month() - 1));
			timeDims[i].Day_Full_Description__c = String.valueOf(timeDims[i].Day_of_Week_Long__c + ', ' + timeDims[i].Long_Month_Description__c + ' ' + currentCalendarDate.day() + ', ' + currentCalendarDate.year());
			timeDims[i].Date_Key_Unique__c = String.valueOf(currentCalendarDate.year() + currentCalendarDate.month() + currentCalendarDate.day());
			//timeDims[i].Month_Description__c = timeDims[i].Long_Month_Description__c.substring(0, 3);
			timeDims[i].Month_Key__c = String.valueOf(currentCalendarDate.year() + currentCalendarDate.month());
			timeDims[i].Month_Number__c = currentCalendarDate.month();
			timeDims[i].Calendar_End_Date__c = Date.newInstance(currentCalendarDate.year(), 12, 31);
			timeDims[i].Calendar_Start_Date__c = Date.newInstance(currentCalendarDate.year(), 1, 1);
			timeDims[i].Calendar_Month_Start_Date__c = Date.newInstance(currentCalendarDate.year(), currentCalendarDate.month(), 1);
			timeDims[i].Calendar_Month_End_Date__c = Date.newInstance(currentCalendarDate.year(), currentCalendarDate.month(), Date.daysInMonth(currentCalendarDate.year(), currentCalendarDate.month()));
			timeDims[i].Quarter_Number__c = getQuarterNumber(currentCalendarDate);			
			timeDims[i].Quarter_Description__c = 'Q' + timeDims[i].Quarter_Number__c;
			timeDims[i].Quarter_Key__c = currentCalendarDate.year() + timeDims[i].Quarter_Description__c;
			timeDims[i].Short_Month_Description__c = timeDims[i].Long_Month_Description__c.substring(0, 3);
			timeDims[i].Short_Month_and_Year__c = timeDims[i].Short_Month_Description__c + '0' + timeDims[i].Year__c.substring(2);
			
			
			//Last Things
			currentCalendarDate = currentCalendarDate.addDays(1);
			System.debug(currentCalendarDate);
			
			//update timeDims[i];
		}
		
		update timeDims;
		
		//Last Things
		lastTimeDimensionOfLastScope = timeDims[timeDims.size() - 1];
	}
	
	global void finish(Database.BatchableContext context)
	{
		
	}
	
	global String selectAll(string sfo){
	    String SOQL;
        map<String, schema.sobjecttype> allSObjects = schema.getglobaldescribe();
        schema.sobjecttype q = allsobjects.get(sfo);
        schema.describesobjectresult d = q.getdescribe();
        map<String, schema.sobjectfield> m = d.fields.getmap();
        set<String> s = m.keyset();
        string k = '';
        for(String f : s){
            k = k+f+', ';
        }
        k = k.substring(0,k.length()-2);
        SOQL = 'SELECT ' + k + ' FROM ' + sfo;
        
        return SOQL;
    }
    
    global String dayOfWeek(Date dt)
    {
    	
    	DateTime d = DateTime.newInstance(dt.year(), dt.month(), dt.day(), 0, 0, 0);
    	return d.format('EEEE');
    }
    
    global Integer getQuarterNumber(Date d)
    {
    	Integer qNum;
    	if (d.month() <= 3)
		{
			qNum = 1;
		}
		if (d.month() >= 4 && d.month() <= 6)
		{
			qNum = 2;
		}
		if (d.month() >= 7 && d.month() <= 9)
		{
			qNum = 3;
		}
		if (d.month() >= 10 && d.month() <= 12)
		{
			qNum = 4;
		}
		
		return qNum;
    }
}

 

Here is how I am calling the batch:

TimeDimensionGenerator gen = new TimeDimensionGenerator(dummy.Calendar_Start_Year__c.year(), dummy.Calendar_End_Year__c.year(), '', '', '', '', '', '');
		ID batchprocessid = Database.executeBatch(gen);

 

The dummy variable that is reference here is just an extra object I created to allow me to use the inputFields with the date picker and store the inputted data in one place. It's only used on the page I've created to test the generation of the TimeDimensions.

 

I've already wasted at least half a day trying to figure out what's going wrong and have yet to get anywhere, so any help from some more experienced Salesforce users would be amazing right now.

I have a scenario where I need to validate my created record Id is falls under a particular view of an Object. But my view has more than 10000 records where I need to validate my Id but StandardSetController getRecords() method is able to returning only 10000.

Please suggest me how can I increase this getRecords() returning record count.


Thanks in Advance.

Hello,

 

I have an inputField set to a lookup relationship of type Contact. When the lookup button next to the inputField is pressed, it returns every contact that matches up with the name entered. I want to limit the results of that search to contacts with a specific account value. Basically what I'm trying to accomplish is to allow the user to select the contact record of the person that is escorting a visitor into our workplace. It wouldn't make sense that they could select someone that doesn't work at the company as an escort.

 

Can I do this in some way?

 

I thank anyone that can help.

Hello,

 

I have an object representing an entry in a visitor log. That object has a few custom fields, Brought_by_Employee__c, Checking_In__c, Contact__c, Escort__c, Time_In__c, Time_Out__c, Title__c and Visitor_Name__c. Thus far, I've built a VisualForce page that has inputText components so that the user can type in their name, the name of the company they work for, their title in the company, etc. The page is using a custom controller that I've written with the visitor's name stored as a String. I wanted to make it easier for my users to check in if they've checked in previously and the best way to do that seemed to be to use inputFields instead because they give you a lookup button next to the inputField. At first it seemed like I would have to rewrite my custom controller to be used as an extension to the Contact standard controller in order to get the inputField working right. Then I tried just creating an empty visitor log entry, because it has a contact field so I thought that perhaps that would correclty bring up the lookup list. It did, but now I can't think of a way to get just the name of the contact they selected. Even though all it seems to be doing is filling in the inputField with the name of the contact, it looks like it's really storing the contact record itself. I need the name of the contact sent back to the controller so that the rest of the logic can be executed. I tried referencing the "phantom" log entry's Contact field to see if that was where the selected record on the VF page had been stored, but this yields the error "Error: You must enter a value" underneath the inputField. Not to mention that another inputField that was previously only required if a check box was selected also gives this error if it is not filled in. Is it possible to get this to work without rewriting my controller as an extension or is my attempt to get lookup buttons working a lost cause?

 

The first line in the constructor of the controller sets the String visitorName to testLog.Contact__r.Name. This was my test to see if the selected contact had been stored in the phantom record I had created in order to access the existing contact records. 

 

I greatly thank anyone that can give me some insight here.

Hi,

 

I need to be able to print cards that have someone's name and whatnot else on it. I already have a VF page for inputting this information. I would like to be able to dynamically create a VF page from the controller in the original VF page that gathers the correct info, open the newly created VF page so that the user can see it while at the same time bringing up the print dialogue via a javascript call in the header. My current attempt at this from what I have managed to find online looks as follows:

 

public PageReference createCard(String name, String company, String title)
    {
        Component.Apex.Page card = new Component.Apex.Page();
        Component.Apex.Form form = new Component.Apex.Form();
        Component.Apex.OutputLabel visitorName = new Component.Apex.OutputLabel();
        Component.Apex.OutputLabel visitorCompany = new Component.Apex.OutputLabel();
        Component.Apex.OutputLabel visitorTitle = new Component.Apex.OutputLabel();

        visitorName.value='name';
        visitorName.style='text-align:center; font-size:24pt;';
        
        visitorCompany.value='name';
        visitorCompany.style='text-align:center; font-size:24pt;';
        
        visitorTitle.value='name';
        visitorTitle.style='text-align:center; font-size;24pt;';
        
        form.childComponents.add(visitorName);
        form.childComponents.add(visitorCompany);
        form.childComponents.add(visitorTitle);
        
        //Stop point
        
        return null;
    }

 

At this point I am stuck. Since the page object does not have a childComponents field, I'm not sure how to add the form to that. I am not even entirely sure that what I have done so far is right. 

Right now I was attempting to be able to return a PageReference so that the user would be sent to the newly created page and proceed from there, but with this I'm not sure how to attach any JavaScript either. Is there a better way to go about doing this?

Hello,

 

I have been looking around for a way to print, well anything really, to a printer when a commandButton is pressed, without bringing up a dialogue in which the user can manipulate settings and then tell the document to print. This application is only going to be used on one computer at a front desk in order to print badges anyways, so there is no need to change the print settings before printing the document. All of the solutions I have found so far to print things in general involve the javascript function "print()" being called from the window or whatever object needs to be printed but as I have come to understand, this brings up the system's print dialogue.

If there is not a way to do this from the VisualForce page itself due to security issues, would I be able to send information that is entered into the VisualForce page itself to a small java app or applet that would print the information without a dialogue?

 

I would greatly appreciate anyone's input on this.

Hello to all,

 

I am working on a VisualForce page that would serve as a visitor log at a front desk or something such as that.

This is a learning experience of sorts, so the solution to my problem may very well be simple and I just have not caught it.

The error I recieve upon opening up my VisualForce page says "Attempt to de-reference a null object". Any other errors I have encountered thus far were fixable because the error page had a little more detail than this.

 

Here is my VF page:

<apex:page controller="VisitorLogController" sidebar="false">
    <apex:sectionHeader title="Visitor Log"/>
    
    <div style="text-align:center;">
    <apex:form id="visitorLogForm">
        <div style="float:left;width:25%;">
            Visitor Name: <apex:inputText value="{!visitorName}"/>
        </div>
        <div style="float:left;width:25%;">
            Company Name: <apex:inputText value="{!company}"/>
        </div>
        <div style="float:left;width:25%;">
            Title in Company: <apex:inputText value="{!title}"/>
        </div>
        <div style="float:right;width:25%;">
            <apex:commandButton action="{!checkIn}" value="Check In"/>            
        </div>
        
        <apex:pageBlock>
            <apex:pageBlockTable value="{!logEntriesCheckedIn}" var="log" id="logEntryTable" rendered="{!recordsObtained}">
                <apex:column value="{!log.Visitor_Name__c}"/>
                <apex:column value="{!log.Company__c}"/>
                <apex:column value="{!log.Title__c}"/>
                <apex:column headerValue="Check Out">
                    <apex:commandButton value="Check Out"/>
                    <apex:actionSupport event="onclick" action="{!checkOut}" rerender="true">
                        <apex:param name="logID" value="{!log.Name}"/>
                    </apex:actionSupport>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
    </div>
</apex:page>

 

This is my controller:

public class VisitorLogController {
    
    public String visitorName {get; set;}
    public String company {get; set;}
    public String title {get; set;}
    
    public Boolean recordsObtained {get; set;}
    
    public List<Visitor_Log_Entry__c> logEntries {get; set;}
    public List<Visitor_Log_Entry__c> logEntriesCheckedIn {get; set;}
    
    public VisitorLogController() {
        recordsObtained = false;
        logEntries = [Select Name, Visitor_Name__c, Title__c, Company__c, Contact__c, Checked_In__c, Time_In__c, Time_Out__c from Visitor_Log_Entry__c limit 1000];
        for (Visitor_Log_Entry__c l : logEntries)
        {
            if (l.Checked_In__c == true)
                logEntriesCheckedIn.add(l);
        }
        recordsObtained = true;
    }
    
    public PageReference checkIn()
    {
        Account account = new Account(Name=company);
        upsert account;
        
        Contact contact = new Contact(FirstName=visitorName.split(' ', 2)[0], LastName=visitorName.split(' ', 2)[0], Job_Position__c = title, Account = account);
        upsert contact;
        
        Visitor_Log_Entry__c newEntry = new Visitor_Log_Entry__c(Checked_In__c = true, Company__c = company, Contact__c = contact.id, Time_In__c = System.now(), Title__c = title, Visitor_Name__c = visitorName);
        insert newEntry;
        
        return null;
    }
    
    public PageReference checkOut()
    {
        String entryID = ApexPages.currentPage().getParameters().get('logID');
        Visitor_Log_Entry__c focusEntry = [Select Name, Checked_In__c, Time_Out__c from Visitor_Log_Entry__c where name = :entryID limit 1];
        
        focusEntry.Checked_In__c = false;
        
        Datetime nowLocal = System.now();
        
        focusEntry.Time_Out__c = nowLocal;
        
        update focusEntry;
        return null;
    }
}

 

A great many thanks to anyone that is willing to help lead me in the right direction. I would also appreciate any other pointers that can be given as well, I am not all that sure I have taken the best approach to some of the working of this page.