I have partly created an apex trigger that randomly selects a contact that is in a specific campaign. This works and I can cycle through the contacts at random. When i refresh the page however I am still allowed to cycle through the contacts again. I should be able to generate the contact once.
I now have a checkbox named 'Mascot_Winner__c' that is unchecked. Is there a way at all to check this checkbox when the contact has been generated at all? Does this checkbox need to be on the contacts object or does it need to be on the campaign or accounts?
Thanks for you help
Controller:
public class MascotController
{
public List<Contact> contacts{get;set;}
public MascotController()
{
getContacts();
}
public void getContacts()
{
Integer count = [SELECT COUNT() FROM Contact];
Integer rand = Math.floor(Math.random() * count).intValue();
Set<Id> contactIds = new Set<Id>();
contacts = new List<Contact>();
for(CampaignMember cm : [Select Id, ContactId from CampaignMember where Status = 'To be Called' and Campaign.Name = '2014/15 Mascot Data'])
{
contactIds.add(cm.ContactId);
}
List<String> orderBys = new List<String>{'Email Asc','Email Desc','Lastname Asc','Firstname Desc','LastModifiedDate Desc','LastModifiedDate Asc','CreatedDate Asc','CreatedDate Desc','Id Asc','Id Desc'};
String orderBy = orderBys.get(Math.mod(rand,orderBys.size()));
contacts = Database.query('Select Name From Contact where ID in :contactIds Order By ' + orderBy + ' Limit 1 OFFSET :rand');
}
}
VF Page:
<apex:page showHeader="true" sideBar="true" controller="MascotController">
<apex:form >
<apex:pageblock id="pb" title="Mascot Winner">
<apex:commandButton value="Generate Winner" action="{!getContacts}" rerender="randomContacts"/>
<apex:outputPanel id="randomContacts">
<apex:pageblock >
<apex:PageBlockTable value="{!contacts}" var="item">
<apex:column headerValue="Contact Name" value="{!item.Name}"/>
</apex:PageBlockTable>
</apex:pageblock>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>