• Øyvind Borgersen 10
  • NEWBIE
  • 100 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 25
    Questions
  • 14
    Replies
Hi,

I have a scenario where I need to paste one single value from a flow to an apex class and run a query and return the result back to the flow to be used as a picklist choice. The code below does not work sufficiently. Can anyone advice?

public class ProductArrangementCollection {
    @InvocableMethod(Label='Terms' description='Insert Terms value')    
    public static List<ID> FindProductArrangement(List<string> Terms) {
        List<ID> Ids = new List<ID>();
        Product_Arrangement__c c = [Select id from Product_Arrangement__c where Actual_start_date__c = 'Terms' limit 10];
        if(c != null) { 
            Ids.add(c.Id);
        }
        return Ids;
    }
}
Hi,

We have a CTI intregration and need to get the phone number once we have answered the call. We have a couple of records created, but that's once the call is ended and we need it at the start of the call.

We will use this phone to lookup to an account and create a case.
Hi,

I need a simple code snippet for a VFP for CTI with screenpop to execute a flow with the callers numbers. We're using Puzzle CTI.
Hi,

I working with lightning flow and needs to run a SOQL with IN clause. Does anyone have an apex sample to be used in flow which can use a variable flow the flow and return a collection to be used as a picklist?
 
Hi,

I have a VFP for uploading CSV files. This is working ok, but times out if the number of rows exceeds around 1000 lines. In order to prevent this I'm planning to convert the VFP to a LC. 

Can someone help me converting the following code? The function is to call the class and upload all data. Add error message if the file is not according to correct format and display the uploaded line count.

<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="2">
                <apex:inputFile value="{!csvFileBody}" filename="{!csvAsString}" />
                <div align="center" draggable="false">
                    <apex:commandButton value="Import salesnumbers" action="{!importCSVFile}" />
                </div>
                <!--<div align="center" draggable="false">
                    <apex:commandButton value="Upload sales numbers" action="{!uploadCSVFile}" />
                </div>-->
            </apex:pageBlockSection>
        </apex:pageBlock>

        <apex:pageBlock >
            <p> Number of uploaded salesnumbers: </p>
            <apex:outputText value="{!vidlist.size}" />
        </apex:pageBlock>
    </apex:form>
</apex:page>
Hi,

I have a basic apex leadAutoConvert class which is triggered with a PB. This is working fine when lead is created in Salesforce. However, when I use the web-to-lead it only works when adding lastname and fails when adding email.

The debug log shows no error, and it also shows that it's been creating an opportunity, but no records are created in Salesforce.

Has anyone any similar experience?


Here's the apex class:

Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                //Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion 
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}
 
Hi,

I have a simple trigger and test class where I need some help to get from the 62% coverage and up to at least 90%.  The lines which are not covered are the ones after the 'IF' statement. 

Can someone please help me with the remaining test class code?

The trigger is as follows:

trigger contactCreateCommunityUser on Contact (before insert) {
    String currentuser = UserInfo.getUserId();
    String emailAddress = UserInfo.getUserEmail();
    
    ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
    List <User> systemAdm = [SELECT Id
                               FROM User
                              WHERE Name like '%Systemadministrator%'];
    system.debug('Systemadmin ID ' + systemAdm);
    If(contactId != null) {
        ID AccID = [Select AccountID from Contact where id =: contactid].AccountId;
        for(Contact con : trigger.new){
            con.OwnerId = systemAdm.get(0).Id;
        }
    }
}


Test class:
@isTest
private class contactCreateCommunityUserTest {       
    static testmethod void contactCreateCommunity() {
        Account acc = [SELECT Id
                        FROM  Account
                        Limit 1];
        
        Contact con = new contact();
        con.lastName = 'TestLastName';
        con.AccountId = acc.Id;
        Insert con;
    }
}
Hi, 

I've created the following code to create a csv file with all records. However, due to limitations in the visualforce page I've created for uploading the file, I need to have the csv file split with 1000 records in each file. 

How do I modify the code below to make such split?

public class createVideogramFile {
@Auraenabled
public static void sendNewFile() {
//Create variables
String currentuser = UserInfo.getUserId();
String emailAddress = UserInfo.getUserEmail();
ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
List <String> videogramRecType = new List <String> ();
List <String> videogramActive = new List <String> ();
//List <String> distId = new List <String> ();
//Add static value to variable
videogramRecType.add('Videogram');
videogramActive.add('Trykt merke');
videogramActive.add('Trykt merke + VOD');
videogramActive.add('VOD');
//distId.add('1867');
System.debug( 'Email address: ' + emailAddress);
System.debug('Videogramactive ' + videogramActive);
//System.debug('distId ' + distId);
//Logic to run if current user is a community user
//Check if there is a contactrecord link on user profile
If(contactId != null) {
ID AccID = [Select AccountID from Contact where id =: contactid].AccountId;
system.debug('ContactID ' + contactID);
system.debug('AccId ' + AccID);
//Create list with videogramcases based on current users account
List < Case > caslist = [SELECT id,
Registration_number__c,
original_title__c
FROM Case
WHERE accountid =: AccID
AND case.RecordType.DeveloperName IN:videogramRecType
//and case.Distributor_ID__c IN:distid
AND case.Active_with__c IN:videogramActive];
system.debug('List of cases IF ' + caslist);
//Logic for email creating
//Add blank column to prevent read of integer in last field
string header = 'Record Id, Registration Number, Originial Title, Number of sales, \n';
string finalstr = header;
for (Case cs: caslist) {
//Create string with @ for later replacement
string recordString = '"' + cs.id + '"@"' + cs.Registration_number__c + '"@"' + cs.original_title__c + '"@"' + '' + '"@"' + '' + '"@"' + '"\n';
//Replace all commas in text field to avoid split errors in upload
string newstring = recordString.replaceAll(',', '').replaceAll('@',',');
finalstr = finalstr + newstring;
//string recordString = '"' + cs.id + '","' + cs.Registration_number__c + '","' + cs.original_title__c + '","' + '' + '","' + '' + '","' + '"\n';
//finalstr = finalstr + recordString;
//csvFieldString.replaceAll(',', '').replaceAll('+',',')
}
Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname = 'Videogram.csv';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new list <string>();
toAddresses.add(emailAddress);
String subject = 'Videogram CSV';
email.setsenderdisplayname ('Medietilsynet');
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setPlainTextBody('Videogram CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[] {
csvAttc
});
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
Hi,

I have a trigger for contentdocument which I'm unable to get a 100% cover on. Can someone help me complete this class to a 100%? Right now, it's around 69%. The part marked in bold is not covered in the test class.

This is the class:

trigger contentDocumentTrigger on contentdocument(before delete) {

    List <Id> contentDocId      = new List <Id> ();
    List <Case> caseList        = new List <Case> ();
    List <String> caseRecType   = new List <String> ();
    Set <Id>  contDocLinkedSet  = new Set <Id> ();

    //Add static records to list
    caseRecType.add('Videogram');
    
    
    //Check if trigger isdelete
    if (trigger.IsDelete) {
        for (ContentDocument con: Trigger.old) {
            System.debug('Trigger old has started' + Trigger.old);
            contentDocId.add(con.Id);
            System.debug('This is id for contentdocument' + con.Id);
        }
        // Find LinkedEntityId in from contentdocumentlink
        for (ContentDocumentLink cdl: [SELECT ContentDocumentId,
                                              LinkedEntityId
                                         FROM ContentDocumentLink
                                        WHERE ContentDocumentId IN: contentDocId]) {
                                              contDocLinkedSet.add(cdl.LinkedEntityId);
                                              System.debug('Set contdoclinkedset' + contDocLinkedSet);

            // Find case from ID saved in query above(contDocLinkedSet)
            for (List < Case > cas: [SELECT Id,
                                    (SELECT Id FROM ContentDocumentLinks LIMIT 1)
                                       FROM case
                                      WHERE Id IN:contDocLinkedSet
                                        AND case.RecordType.DeveloperName IN:caseRecType 
                                      ]) {

                                    system.debug('Cas list' + cas);

                // Update case with false in File_exist__c
                for (Case cs: cas) {
                    if (cs != null) {
                        cs.File_exist__c = false;
                        caseList.add(cs);
                    }
                    // Create map to prevent duplicates in delete
                    map<id, case> casmap = new map<id, case>();

                    // Add all values from caselist to map
                    casmap.putall(caseList);
                    system.debug('casmap ' + casmap);

                    // Check if casmap has values
                    if(casmap.size()>0){

                    // Update casmap values and remove checkmark for fileexist field        
                    UPDATE casmap.values();

                    }
                }
            }
        }
    }
}

Test class:
@isTest
private class contentDocumentLinkTriggerTest {
    static testMethod void newcontentDocument() {
        Case testCase = new Case();
        testCase.Subject = 'Test Case';
        insert testCase;

        ContentVersion contentVersion = new ContentVersion(
            Title = 'Penguins',
            PathOnClient = 'Penguins.jpg',
            VersionData = Blob.valueOf('Test Content'),
            IsMajorVersion = true
        );
        insert contentVersion;
        List < ContentDocument > documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];

        //create ContentDocumentLink  record 
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = testCase.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;

        If(testCase != null) {
            testcase.File_exist__c = false;
            update testcase;
            
            delete documents;
        }
    }    
}
Hi,

I have a test class which I'm struggling to get a 100% cover. I have the following test class: 

@isTest
public class ImportDataFromCSVControllerTest {
    static String str = 'Case_ID__c,Number_of_copies__c,Registration_date__c\n a031X000002TdIBQA0,40,2019-05-18\n a031X000002TdIBQA0,40,2019-05-19';       

    public static String[] csvFileLines;
    public static Blob csvFileBody;

    static testmethod void testfileupload(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegative(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
    static testmethod void testfileuploadalt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        importData.importCSVFile();
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegativealt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
}


The lines below are the ones which are not covered by the class. Can someone help me with the necessary code to add to the test class?



                vidObj.Case_ID__c = csvRecordData[0];
                vidObj.RegistrationNumberDummy__c = csvRecordData[1];
                //vidObj.RegistrationNumberDummy__c = dateString;
                vidObj.Titledummy__c = csvRecordData[2];
                vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[3].trim());
                vidObj.Registration_date__c = date.today();
                vidList.add(vidObj);
                }
            }
            insert vidList;
            if(!vidList.isempty()){
                system.debug('vidlist' + vidlist);

                ApexPages.Message successMessage = new ApexPages.Message(ApexPages.severity.CONFIRM,' File successfully uploaded');
                ApexPages.addMessage(successMessage);}
                            else {
                ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,' An error has occured while importing data Please make sure input csv file is correct nad that salesnumber not already is uploaded in this quarter');
                ApexPages.addMessage(errorMessage);}
 
Hi,

I've created a code for uploading a csv file. But I need to enhance this code with a duplicate check to prevent a record in the csv file is uploaded if the related case has been uploaded already this quarter.

From the code below, I've added a query to to check if record's registration date is in within current quarter. If so, then the record should be excluded from the upload. However, this does not work correctly as it does not exclude all of the records which has already been uploaded this quarter. Does anyone has a good idea of why it's failing and how to correct it? Or any other way I could try this code?

public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<Videogram_sales_number__c> vidList{get;set;}
//Public List<String> showList{get;set;}
public importDataFromCSVController(){
csvFileLines = new String[]{};
vidList = New List<Videogram_sales_number__c>();
}
public void importCSVFile(){
try{
csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');
Date lastPerEnd = [Select EndDate From Period Where type = 'Quarter' and StartDate = THIS_FISCAL_QUARTER].EndDate;
Date lastPerStart = [Select StartDate From Period Where type = 'Quarter' and StartDate = THIS_FISCAL_QUARTER].StartDate;

List<Videogram_sales_number__c> vidListDat = [SELECT id,
Regstration
FROM Videogram_sales_number__c
WHERE Registration_date__c <:lastPerEnd
AND Registration_date__c >:lastPerStart];
system.debug('vidListDat' + vidListDat);
for(Integer i=1;i<csvFileLines.size();i++){
Videogram_sales_number__c vidObj = new Videogram_sales_number__c();
//Create date as string
String dateFormatString = 'yyyy-MM-dd';
Date d = Date.today();
Datetime dt = Datetime.newInstance(d.year(), d.month(),d.day());
String dateString = dt.format(dateFormatString);
//Split by comma or semicolon
string[] csvRecordData = csvFileLines[i].split(',|\\;');
if(!(csvRecordData[3] =='') && !string.valueof(vidListDat).contains(string.valueof(csvRecordData[0]))){
//&& !string.valueof(vidListDat).contains(string.valueof(csvRecordData[0]))
vidObj.Case_ID__c = csvRecordData[0];
vidObj.RegistrationNumberDummy__c = csvRecordData[1];
//vidObj.RegistrationNumberDummy__c = dateString;
vidObj.Titledummy__c = csvRecordData[2];
vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[3].trim());
vidObj.Registration_date__c = date.today();
vidList.add(vidObj);
}
}
insert vidList;
if(!vidList.isempty()){
system.debug('vidlist' + vidlist);
ApexPages.Message successMessage = new ApexPages.Message(ApexPages.severity.CONFIRM,'Fil er korrekt lastet opp // File successfully uploaded');
ApexPages.addMessage(successMessage);}
else {
ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'En feil har oppstått, vennligst sjekk at filen er korrekt og at salgstall ikke allerede er rapportert i dette kvartal // An error has occured while importing data Please make sure input csv file is correct nad that salesnumber not already is uploaded in this quarter');
ApexPages.addMessage(errorMessage);}
}
catch (Exception e)
{
ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data Please make sure input csv file is correct');
ApexPages.addMessage(errorMessage);
}
}
Hi,

I've created a lightning component list to view some fields from case. One of this field is a checkbox field, but this appears as true/false instead of the checkbox. How can I add the checkbox tick box with value in the list?

<aura:iteration items="{!v.caselist}" var="cas">
<tr>
<th scope="row">
<div class="slds-truncate" title="{!cas.Id}">{!cas.Id}</div>
</th>
<td>
<div class="slds-truncate" title="{!cas.CaseNumber}">{!cas.CaseNumber}</div>
</td>
<td>
<div class="slds-truncate" title="{!cas.Account.Name}">{!cas.Account.Name}</div>
</td>
<td>
<div class="slds-truncate" title="{!cas.Contact.Name}">{!cas.Contact.Name}</div>
</td>
<td>
<div class="slds-truncate" title="{!cas.Status}">{!cas.Status}</div>
</td>
<td>
<div class="slds-truncate" title="{!cas.CreatedDate}">{!cas.CreatedDate}</div>
</td>
<td>
<div class="slds-truncate" title="{!cas.CaseCloned__c}" type="boolean">{!cas.CaseCloned__c}
</div>
</td>
<td>
<form class="clone-form" onsubmit="{!c.cloneCaseAction}">
<input type="hidden" value="{!cas.Id}" class="clone-name" />
<!-- Use a Lightning Base Component To display an icon next to the label -->
<lightning:button label="Clone" iconName="utility:download" iconPosition="left"
variant="brand" type="submit" />
</form>
</td>
<td>
<form class="goto-form" onsubmit="{!c.gotoCase}">
<input type="hidden" value="{!cas.Id}" class="goto-name" />
<!-- Use a Lightning Base Component To display an icon next to the label -->
<lightning:button label="GoTo" iconPosition="left" variant="Success" type="submit" />
</form>
</td>
</tr>
</aura:iteration>

 
Hi,

Can someone help me with a test class for the below code?
It's a list view with a cloned functionality.

public with sharing class cloneCaseApplication {
@AuraEnabled
public static List < Case > cloneCaseApp() {
//Create variables
String currentuser = UserInfo.getUserId();
String emailAddress = UserInfo.getUserEmail();
Id userContactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
List < String > caseRecordtype = new List <String> ();
List < Case > casListCommunity = new List <case>();
List < Case > casListInternal = new List <case>();
system.debug('currentuser' + currentuser);
system.debug('userContactId' + userContactId);
// Add recordtype to list
caseRecordtype.add('Produksjonstilskudd');
caseRecordtype.add('Produksjonstilskudd_ny');
// Create list of all accounts which current user is linked to
List < Account > userAccounts = [SELECT Id,
name
FROM Account
WHERE Id IN(SELECT accountId FROM AccountContactRelation WHERE contactId =: userContactId)];
System.debug('userAccounts' + userAccounts);
// List all cases for accounts linked to user
if (userContactId != null) {
List < Case > cas = [SELECT Id,
Casenumber,
FROM Case
WHERE AccountId IN: userAccounts
AND RecordTypeId IN: caseRecordtype];
return cas;
}
else {
List < Case > casempt = [SELECT Id,
CaseNumber,
Account.Name
FROM Case
//WHERE RecordTypeId IN : caseRecordtype
LIMIT 20];
System.debug('casempt' + casempt);
return casempt;
}
}
@AuraEnabled
public static Boolean cloneRecord(String recId) {
system.debug('RecordToClone' + recid);
List < Case > toBeCloned = new List < Case > ();
Case cloneThis = [SELECT Id, CaseCloned__c FROM Case WHERE ID =: recId];
system.debug('clonethis' + cloneThis);
system.debug('this fires');
if (clonethis != null && Clonethis.CaseCloned__c != true) {
Case CloneTest = cloneThis.clone();
cloneThis.CaseCloned__c = true;
insert clonetest;
update clonethis;
system.debug('clontest' + clonetest);
return true;
} else if (Clonethis.CaseCloned__c == true) {}
return false;
}
}
Hi,

I've created a CSV file upload code, but need to enhance the code to skip the whole line if one field is blank.

For the code below I want to skip the line if csvRecordData[1]  is blank. 


csvAsString = csvFileBody.toString();
csvFileLines = csvAsString.split('\n');
for(Integer i=1;i<csvFileLines.size();i++){
Videogram_sales_number__c vidObj = new Videogram_sales_number__c();
//Create date as string
String dateFormatString = 'yyyy-MM-dd';
Date d = Date.today();
Datetime dt = Datetime.newInstance(d.year(), d.month(),d.day());
String dateString = dt.format(dateFormatString);
//Split by comma or semicolon
string[] csvRecordData = csvFileLines[i].split(',|\\;');
if(csvRecordData[1] != null){
vidObj.Case_ID__c = csvRecordData[0];
vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[1]);
vidObj.Registration_date__c = date.today();
vidObj.RegistrationNumberDummy__c = dateString;
vidObj.Titledummy__c = csvRecordData[2];
vidObj.RegistrationNumberDummy__c = csvRecordData[3];
vidList.add(vidObj);
}
}
Hi,

I've created an csv import file VFP page where we should display the filevalues to be imported and also a couple of values which is not imported.
I'm able to get the VFP to show the values shown in the csv file and should be uploaded, but not the values that should only be shown.

VFP:

<apex:pageblocktable value="{!vidList}" var="vid">
<apex:column value="{!vid.Case_ID__c}" />
<apex:column value="{!vid.Number_of_copies__c}" />
<apex:column value="{!vid.Registration_date__c}" />
</apex:pageblocktable>

Controller:
for(Integer i=1;i<csvFileLines.size();i++){
Videogram_sales_number__c vidObj = new Videogram_sales_number__c();
Case cas = new Case();
//Split by comma or semicolon
string[] csvRecordData = csvFileLines[i].split(',|\\;');
vidObj.Case_ID__c = csvRecordData[0] ;
vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[1]);
vidObj.Registration_date__c = date.today();
vidList.add(vidObj);
Hi,

I've created a lightning component as a list view of cases. From that listview I have a button which should navigate to the record on the listview.
I've tried a couple of version with :navigateToUrl without any luck.

How do I create the controller which navigates to the selected record?

 
Hi,

I've created a simple class to retrieve several custom metadata settings. How do I create a test class for this? I've tried a couple of different variations with no luck.

public with sharing class deadlineDatesController {
    @AuraEnabled
    public static List <CustomMeta__mdt> getProdDates() {

        List < CustomMeta__mdt> prodList = [SELECT MasterLabel,
                                                             value1__c,
                                                             Value2__c

                                                       FROM CustomMeta__mdt
                                                        ]; {

            system.debug('prodList' + prodList);
            return prodList;
        }
    }
Hi,

I've created an controller to show the custom metadata values in a lightning component. The apex controller works fine, but the values are not shown in the list. Can someone please check where the error is in this code:

Apex class:
public with sharing class deadlineDatesController {
    @AuraEnabled
    public static List <DeadlineDate__mdt> getDeadlineDates() {
        
        List<DeadlineDate__mdt> dlist =   
            [select  label
                        value1__c, 
                        value2__c 
               from DeadlineDate__mdt
            limit 100];{
        
        system.debug('Listvalues' + dlist);
        return dlist;  
                   
            }
    }
}


Lightning component controller:

({
      doInit: function(component, event, helper) {
        // Fetch the account list from the Apex controller
        var action = component.get("c.getDeadlineDates");
          
          action.setCallback(this, function(data) {
              component.set("v.dates", data.getReturnValue());
              console.log('Returnvalue' + data.getReturnValue());
          });
          $A.enqueueAction(action);
      
      },
    })

Lightning component:
<aura:component controller="deadlineDatesController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    
    <aura:attribute name="deadline" type="DeadlineDate__mdt[]" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <!-- Use a data table from the Lightning Design System: https://www.lightningdesignsystem.com/components/data-tables/ -->
        <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
          <thead>
            <tr class="slds-text-heading_label">
              <th scope="col"><div class="slds-truncate" title="Year">Year</div></th>
              <th scope="col"><div class="slds-truncate" title="value1">value1</div></th>
              <th scope="col"><div class="slds-truncate" title="value1">value2</div></th>
            </tr>
          </thead>
          <tbody>
            <!-- Use the Apex model and controller to fetch server side data -->
            <aura:iteration items="{!v.dates}" var="date">
                <tr>
                    <th scope="row">
                        <div class="slds-truncate" title="{!date.label}">{!date.label}</div></th>
                    <td><div class="slds-truncate" title="{!date.value1_c}">{!date.value1__c}</div></td>
                    <td><div class="slds-truncate" title="{!date.value2__c}">{!date.value2__c}</div></td>
                    <td>
                    </td>
                </tr>
            </aura:iteration>
          </tbody>
        </table>
</aura:component>
 
Hi,

I need to display a warning or error message on lightning page based on various logic from an apex class. This should be updated dynamically based on the different logic. 

F.ex the apex class runs a check on  a custom email field on the case record to check if the email exist in a contact related to the account. If it exist but no portal user is created for that account we should display a warning message as a lightning component. If custom email address does not match any contacts then there should be an error message.

How can we setup a dynamically error/warning  message for this?
Hi,

I'm trying to setup a simple lightning component with radio buttons, which will call an apex class to update the current users language. 

Does anyone has a lightning component + apex class example for this?
Hi,

I have a scenario where I need to paste one single value from a flow to an apex class and run a query and return the result back to the flow to be used as a picklist choice. The code below does not work sufficiently. Can anyone advice?

public class ProductArrangementCollection {
    @InvocableMethod(Label='Terms' description='Insert Terms value')    
    public static List<ID> FindProductArrangement(List<string> Terms) {
        List<ID> Ids = new List<ID>();
        Product_Arrangement__c c = [Select id from Product_Arrangement__c where Actual_start_date__c = 'Terms' limit 10];
        if(c != null) { 
            Ids.add(c.Id);
        }
        return Ids;
    }
}
Hi,

I need a simple code snippet for a VFP for CTI with screenpop to execute a flow with the callers numbers. We're using Puzzle CTI.
Hi,

I working with lightning flow and needs to run a SOQL with IN clause. Does anyone have an apex sample to be used in flow which can use a variable flow the flow and return a collection to be used as a picklist?
 
Hi,

I have a simple trigger and test class where I need some help to get from the 62% coverage and up to at least 90%.  The lines which are not covered are the ones after the 'IF' statement. 

Can someone please help me with the remaining test class code?

The trigger is as follows:

trigger contactCreateCommunityUser on Contact (before insert) {
    String currentuser = UserInfo.getUserId();
    String emailAddress = UserInfo.getUserEmail();
    
    ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
    List <User> systemAdm = [SELECT Id
                               FROM User
                              WHERE Name like '%Systemadministrator%'];
    system.debug('Systemadmin ID ' + systemAdm);
    If(contactId != null) {
        ID AccID = [Select AccountID from Contact where id =: contactid].AccountId;
        for(Contact con : trigger.new){
            con.OwnerId = systemAdm.get(0).Id;
        }
    }
}


Test class:
@isTest
private class contactCreateCommunityUserTest {       
    static testmethod void contactCreateCommunity() {
        Account acc = [SELECT Id
                        FROM  Account
                        Limit 1];
        
        Contact con = new contact();
        con.lastName = 'TestLastName';
        con.AccountId = acc.Id;
        Insert con;
    }
}
Hi,

I have a test class which I'm struggling to get a 100% cover. I have the following test class: 

@isTest
public class ImportDataFromCSVControllerTest {
    static String str = 'Case_ID__c,Number_of_copies__c,Registration_date__c\n a031X000002TdIBQA0,40,2019-05-18\n a031X000002TdIBQA0,40,2019-05-19';       

    public static String[] csvFileLines;
    public static Blob csvFileBody;

    static testmethod void testfileupload(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegative(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
    static testmethod void testfileuploadalt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        importData.importCSVFile();
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegativealt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
}


The lines below are the ones which are not covered by the class. Can someone help me with the necessary code to add to the test class?



                vidObj.Case_ID__c = csvRecordData[0];
                vidObj.RegistrationNumberDummy__c = csvRecordData[1];
                //vidObj.RegistrationNumberDummy__c = dateString;
                vidObj.Titledummy__c = csvRecordData[2];
                vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[3].trim());
                vidObj.Registration_date__c = date.today();
                vidList.add(vidObj);
                }
            }
            insert vidList;
            if(!vidList.isempty()){
                system.debug('vidlist' + vidlist);

                ApexPages.Message successMessage = new ApexPages.Message(ApexPages.severity.CONFIRM,' File successfully uploaded');
                ApexPages.addMessage(successMessage);}
                            else {
                ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,' An error has occured while importing data Please make sure input csv file is correct nad that salesnumber not already is uploaded in this quarter');
                ApexPages.addMessage(errorMessage);}
 
Hi,

Can someone help me with a test class for the below code?
It's a list view with a cloned functionality.

public with sharing class cloneCaseApplication {
@AuraEnabled
public static List < Case > cloneCaseApp() {
//Create variables
String currentuser = UserInfo.getUserId();
String emailAddress = UserInfo.getUserEmail();
Id userContactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
List < String > caseRecordtype = new List <String> ();
List < Case > casListCommunity = new List <case>();
List < Case > casListInternal = new List <case>();
system.debug('currentuser' + currentuser);
system.debug('userContactId' + userContactId);
// Add recordtype to list
caseRecordtype.add('Produksjonstilskudd');
caseRecordtype.add('Produksjonstilskudd_ny');
// Create list of all accounts which current user is linked to
List < Account > userAccounts = [SELECT Id,
name
FROM Account
WHERE Id IN(SELECT accountId FROM AccountContactRelation WHERE contactId =: userContactId)];
System.debug('userAccounts' + userAccounts);
// List all cases for accounts linked to user
if (userContactId != null) {
List < Case > cas = [SELECT Id,
Casenumber,
FROM Case
WHERE AccountId IN: userAccounts
AND RecordTypeId IN: caseRecordtype];
return cas;
}
else {
List < Case > casempt = [SELECT Id,
CaseNumber,
Account.Name
FROM Case
//WHERE RecordTypeId IN : caseRecordtype
LIMIT 20];
System.debug('casempt' + casempt);
return casempt;
}
}
@AuraEnabled
public static Boolean cloneRecord(String recId) {
system.debug('RecordToClone' + recid);
List < Case > toBeCloned = new List < Case > ();
Case cloneThis = [SELECT Id, CaseCloned__c FROM Case WHERE ID =: recId];
system.debug('clonethis' + cloneThis);
system.debug('this fires');
if (clonethis != null && Clonethis.CaseCloned__c != true) {
Case CloneTest = cloneThis.clone();
cloneThis.CaseCloned__c = true;
insert clonetest;
update clonethis;
system.debug('clontest' + clonetest);
return true;
} else if (Clonethis.CaseCloned__c == true) {}
return false;
}
}
Hi,

I've created an controller to show the custom metadata values in a lightning component. The apex controller works fine, but the values are not shown in the list. Can someone please check where the error is in this code:

Apex class:
public with sharing class deadlineDatesController {
    @AuraEnabled
    public static List <DeadlineDate__mdt> getDeadlineDates() {
        
        List<DeadlineDate__mdt> dlist =   
            [select  label
                        value1__c, 
                        value2__c 
               from DeadlineDate__mdt
            limit 100];{
        
        system.debug('Listvalues' + dlist);
        return dlist;  
                   
            }
    }
}


Lightning component controller:

({
      doInit: function(component, event, helper) {
        // Fetch the account list from the Apex controller
        var action = component.get("c.getDeadlineDates");
          
          action.setCallback(this, function(data) {
              component.set("v.dates", data.getReturnValue());
              console.log('Returnvalue' + data.getReturnValue());
          });
          $A.enqueueAction(action);
      
      },
    })

Lightning component:
<aura:component controller="deadlineDatesController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    
    <aura:attribute name="deadline" type="DeadlineDate__mdt[]" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <!-- Use a data table from the Lightning Design System: https://www.lightningdesignsystem.com/components/data-tables/ -->
        <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
          <thead>
            <tr class="slds-text-heading_label">
              <th scope="col"><div class="slds-truncate" title="Year">Year</div></th>
              <th scope="col"><div class="slds-truncate" title="value1">value1</div></th>
              <th scope="col"><div class="slds-truncate" title="value1">value2</div></th>
            </tr>
          </thead>
          <tbody>
            <!-- Use the Apex model and controller to fetch server side data -->
            <aura:iteration items="{!v.dates}" var="date">
                <tr>
                    <th scope="row">
                        <div class="slds-truncate" title="{!date.label}">{!date.label}</div></th>
                    <td><div class="slds-truncate" title="{!date.value1_c}">{!date.value1__c}</div></td>
                    <td><div class="slds-truncate" title="{!date.value2__c}">{!date.value2__c}</div></td>
                    <td>
                    </td>
                </tr>
            </aura:iteration>
          </tbody>
        </table>
</aura:component>
 
Hi,

I need to display a warning or error message on lightning page based on various logic from an apex class. This should be updated dynamically based on the different logic. 

F.ex the apex class runs a check on  a custom email field on the case record to check if the email exist in a contact related to the account. If it exist but no portal user is created for that account we should display a warning message as a lightning component. If custom email address does not match any contacts then there should be an error message.

How can we setup a dynamically error/warning  message for this?
Hi,

I'm trying to setup a simple lightning component with radio buttons, which will call an apex class to update the current users language. 

Does anyone has a lightning component + apex class example for this?
Hi,

I have a challenge that I want to share the related contacts to the other accounts contact. This is in a community scenario where a community user should be able to select any of the related contacts to the account.

As per now they are only able to select the contacts which has a direct relationship and not on related contacts.

Does anyone have a apex sharing for this scenario?
Hi!
I have a scenario where I need to check if a file has been added to a record. Does anyone have a sample code for this?

If there's an file attachment to the record, I'll update a checkbox.
Hi,

I'm creating a trigger to get the profile name from account owner in the account record. This should be a fairly simple task, but I'm stuck with no results in the code. Do anyone have a quick code for this?