Apex Class Controller Random Contact Records - salesforce

I am looking on selecting a small group of random contacts from a specific view. The records are in that view if their campaign status is set to sent. I have created an apex class that I think would work, however I am trying make this class a controller and build a visual force page. I am knew to salesforce and apex. After doing some research i think i will have to use getters and setters to call the information. My apex class is
public class MyController {
Integer count = [SELECT COUNT() FROM Contact];
Integer rand = Math.floor(Math.random() * count).intValue();
Set<Id> contactIds = new Set<Id>();{
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()));
List<Contact> contacts = (List<Contact>)Database.query('Select Name From Contact where ID in :contactIds Order By ' + orderBy + ' Limit 5 OFFSET :rand');
}
}
}
Many thanks

Try the following code:
Visualforce Page:
<apex:page controller="MyController">
<apex:form>
<apex:pageblock id="pb" title="Contact Information">
<apex:commandButton value="Get Random Contacts" action="{!getContacts}" rerender="randomContacts"/>
<apex:outputPanel id="randomContacts">
<apex:pageblock>
<apex:PageBlockTable value="{!contacts}" var="item">
<apex:column headerValue="Contact Name" value="{!item.Name}"/>
--display columns you wish to show.
</apex:PageBlockTable>
</apex:pageblock>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Class:
public class MyController
{
public List<Contact> contacts{get;set;}
public MyController()
{
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 100 OFFSET :rand');
}
}
First time it load data when page loaded and click on the button to get next random contacts.
Hope it helps you.

Related

Map and List values from APEX SALESFORCE

I have question on my Salesforce WebService and Apex Code.
In a relationship, we have one Notice and multiple attachments in my salesforce. But I don't know how to fix below requirements:
when "GET" webservices incoming thru specific URL API, it supposed to return with JSON format
JSON Format should {Notice1 : attach1{link},attach2{link} , etc }
#RestResource(urlMapping='/API/V1/notice/*')
global with sharing class API_Notice {
#HttpGet(UrlMapping='/API/V1/notice/all')
global static List<String> getNotice(){
Set<Id> NoticeIds = new Set<Id>();
Set<Id> VersionIds = new Set<Id>();
String compares;
List<String> returnJSON = new List<String>();
List<Notice__c> reConts = [select Id, ClosingDate__c ,Name, Contents__c from notice__c];
Map<Id,Notice__c> addMap = new Map <Id,Notice__c>();
Map<Map<Id,Notice__c>,Map<Id,contentdistribution>> addsMap = new Map<Map<Id,Notice__c>,Map<Id,contentdistribution>>();
//SET NOTICE ID
if(!reConts.isEmpty()){
for(Notice__c nc : reConts){
NoticeIds.add(nc.Id);
addMap.put(nc.id,nc);
}
}
//GET public Image URL
if(!NoticeIds.isEmpty()){
Map<Id,ContentDocumentLink> contentMap = new Map<Id,ContentDocumentLink>([
select contentDocumentid,LinkedEntityId from ContentDocumentLink where LinkedEntityId IN:NoticeIds
]);
for(ContentDocumentLink Key : contentMap.values()){
VersionIds.add(Key.ContentDocumentId);
}
if(!VersionIds.isEmpty()){
Map<Id, contentdistribution> cdb = new Map <Id, contentdistribution> ([
select DistributionPublicUrl from contentdistribution where contentDocumentid IN:VersionIds
]);
addsMap.put(addMap,cdb);
}
}
return null;
}
}

How to write Test class to test a field on an attachment or file insert?

Below is the trigger update a field on an attachment or file insert , can some one suggest a test class for this trigger?
Can some one please help in writing a #isTest class for below trigger to achieve 100 % code completion
trigger ContentDocumentLinkTrigger on ContentDocumentLink (after insert) {
if(trigger.isAfter) {
if(trigger.isInsert) {
ContentDocumentLinkTriggerHandler.onAfterInsert(trigger.new);
}
}
}
here is the class
public class ContentDocumentLinkTriggerHandler {
public static void onAfterInsert(list<ContentDocumentLink> lstCntLinks) {
set<Id> setTaskIds = new set<Id>();
list<task> lstTask=new list<task>();
Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('ERT_Task_Record_Type').getRecordTypeId();
for(ContentDocumentLink clIterator : lstCntLinks) {
setTaskIds.add(clIterator.LinkedEntityId);//Set all task id
}
if(!setTaskIds.isEmpty()) {
lstTask= [SELECT Id, Name,Attachment_Indicator__c FROM task WHERE Id IN :setTaskIds and recordtypeid=: recordTypeId ]; //Get all the task
}
for(task varTsk: lstTask){
varTsk.Attachment_Indicator__c=true;//Set Attachment Indicator Flag true
}
if(lstTask.size()>0){
update lstTask; //update task
}
}
}
Thanks in advance.
Carolyn
We aren't really a code writing service, you might want to hire some consultancy or even post the job on https://appexchange.salesforce.com/developers (it should be vetted by SF themselves, haven't used that part of appexchange personally). It's different if you have specific problem, wrote some code, got stuck with particular problem...
This should give you some ideas how it could be attacked. No promises it'll even compile. It's not pixel perfect, there's no negative test case (linking to task of different record type should not set the flag etc)
but it's a start.
#isTest
public with sharing class ContentDocumentLinkTriggerTest {
#isTest
public static void testSettingTaskFlag(){
Task t = new Task(
Subject = 'unit test here we go',
RecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('ERT_Task_Record_Type').getRecordTypeId()
);
insert t;
ContentVersion cv = new ContentVersion(
Title = 'Some document',
PathOnClient = 'some document.txt',
VersionData = Blob.valueOf('Lorem ipsum dolor sit amet...')
);
insert cv;
ContentDocument cd = [SELECT Id FROM ContentDocument WHERE LatestPublishedVersionId = :cv.Id];
ContentDocumentLink cdl = new ContentDocumentLink(
ContentDocumentId = cd.Id,
LinkedEntityId = t.Id
);
Test.startTest();
insert cdl;
Test.stopTest();
Task newTask = [SELECT Attachment_Indicator__c FROM Task WHERE Id = :t.Id];
System.assert(newTask.Attachment_Indicator__c);
}
}

SpringBoot : RestAPI display the unique record

Table :
this is table name
Requirement :
Using RestAPI call populate unique cateID, categoryName , but I am getting the whole record.
Table
Table Data which I am using
Code Description :
Repository :
#Repository
public interface CategoryRepository extends JpaRepository<xCategory,Integer>
{
// #Query("SELECT DISTINCT a.catID,a.categoryName FROM ccCategory a order by categoryName asc")
#Query("SELECT DISTINCT a.catID, a.categoryName FROM xCategory a order by categoryName asc")
List<ccCategory> getCategoryName();
}
Rest Controller:
#RestController
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
public class HomeResource {
private final Logger log = LoggerFactory.getLogger(HomeResource.class);
#Autowired
CategoryRepository categoryRepository;
#GetMapping("/getAllCategory")
public List<ccCategory> getAllCategory() {
// public List<String> getAllCategory() {
System.out.println("***** Call : API getAllCategory() ******");
List<ccCategory> cCategory = categoryRepository.findAll();
return cCategory;
}
Angular Code :
<label class="control-label">Category: </label>
<select [(ngModel)]="listAllCategory" name="xxcategory" class="form-control" required>
<option *ngFor="let xxcategory of listAllCategory" [value]="xxcategory.catID">
{{xxcategory.categoryName}}
</option>
</select>
Problem :
Drop Down populating all the table value but I want only the UNIQUE value like only one time catID , categoryName.
You have to add a variable to keep the selected element in your select and then change your [(ngModel)]="listAllCategory" with [(ngModel)]="selectedCategory"

Cannot validate on saving new record

Salesforce Guru:
I am writing a Salesforce visualforce page extension controller to implement validation and other biz logic in it. However, my code doesn't work as expected. It seems the code validating sub category and serial number is never reached. The system debug log shows the sub category is always null though I have input values in VF page. Can you pls help? thank you very much!
public class CaseCreationExtension {
ApexPages.StandardController stdCtrl;
Case newCase;
public CaseCreationExtension(ApexPages.StandardController controller){
if (!Test.isRunningTest()){
controller.addFields(new List<String>{'Categ__c', 'Sub_Category__c', 'Id', 'Serial_Number__c', 'Refund_Required__c', 'Total_Value__c', 'Per_Month__c'});
system.debug('AddFields');
}
system.debug('Initial Controller');
this.stdCtrl = controller;
newCase = (Case)stdCtrl.getRecord();
system.debug('AccountId' + newCase.AccountId);
}
public PageReference validateSaveRedirect(){
system.debug('Sub Category:' + newCase.Sub_Category__c);
system.debug('Serial Number:' + newCase.Serial_Number__c);
if(newCase.Sub_Category__c == 'Cancellations' && newCase.Serial_Number__c == null){
system.debug('Adding error message');
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Serial Number must be specified for cancellation case.');
ApexPages.addMessage(myMsg);
system.debug('finished Adding error message');
return null;
}else{
if(null==stdCtrl.save()){
return null;
}
/*try{
stdCtrl.save();
}
catch(system.Exception e){
ApexPages.Message msg = new apexPages.Message(Apexpages.Severity.ERROR, e.getdmlMessage(0));
ApexPages.addMessage(msg);
return null;
}*/
stdCtrl.save();
system.debug('New Case Id:' + newCase.Id);
PageReference pr = new PageReference('/' + newCase.Id);
pr.setRedirect(true);
return pr;
}
}
public PageReference cancelRedirect(){
stdCtrl.cancel();
system.debug('New Case Id:' + newCase.Contact);
PageReference pr = new PageReference('/' + newCase.Contact);
pr.setRedirect(true);
return pr;
}
}
What did you base your VF form on? <apex:inputField value="{!case.Sub_Category__c}"/>? It seems the newCase variable is private + it doesn't have any getter/setter.
From what I remember the act of calling (Case)stdCtrl.getRecord(); "decouples" the variables. It's more of a copy than a reference to same object. So it's likely the stdCtrl has then values you've set but they weren't passed on to the newCase because it was "cloned" out of stdCtrl before the user has edited the data. Insert a System.debug(stdCtrl); into your method; if I'm right - you'll see your new values in there.
You could move the (Case)stdCtrl.getRecord(); into that method.
Or - change your apex to say public Case newCase {get;set;} and modify the VF form to reference {!newCase.Sub_Category__c} etc.

read zip attachment in visualforce page

Hi all I am developing an app on salesforce.
I want to read the content of the file which is inside the zip attachment in visualforce page but without extracting the zip file.
How can I achieve this? Is there any way to do this?
Update for modified question:
Have a look at Handling Office Files and Zip Files in Apex – Part 2 by Andrew Fawcett.
There is a basic Knowledge Article on how to do this with an image that is stored in an Attachment. See How can I Display Base64 Data on page layout?
In this example the AttachmentID is passed via a query string paramemter, but you could look it up however works best for your requirement.
Visualforce page:
<apex:page controller="ViewImage" cache="true">
<img src="data:{!att.ContentType};base64,{!image}" />
</apex:page>
Controller:
public class ViewImage {
public Attachment att {
get {
if (att == null) {
String id = ApexPages.currentPage().getParameters().get('AttachmentID');
att = [SELECT Body, ContentType, Name FROM Attachment WHERE ID = :id];
}
return att;
}
private set;
}
public String image {
get {
return EncodingUtil.Base64Encode(att.body);
}
}
}
Hi all I have achieved this using JSzip library here is my code --
In apex page I have written javascript function --
function viewContent(){
var zip = null;
var zipFileName = null;
var zipFileNames = null;
data = "{!contentAsText}";
zip = new JSZip(data, {base64:true});
zipFileName = 'files.zip';
zipFileNames = [];
for(var zipfileName in zip.files){
zipFileNames.push(zipfileName);
if(zipfileName == 'index.html'){
var file = zip.files[zipfileName];
var data = file.data;
document.getElementById('contentdiv').innerHTML = data;
//var data = JSZipBase64.encode(file.data);
}
}
In controller --
public String contentAsText {get;set;}
List<Attachment> atts = [Select Id, Body from Attachment where name='files.zip' limit 1];
contentAsText = EncodingUtil.base64Encode(atts[0].Body);
This link will help you --
http://andyinthecloud.com/2012/12/09/handling-office-files-and-zip-files-in-apex-part-2/

Resources