Search In This Blog

Showing posts with label Apex. Show all posts
Showing posts with label Apex. Show all posts

2023-08-08

Not Admin User, How to delete/insert FinServ__FinancialAccount by Apex

Apex should be "without sharing".

Remove sObject.SObjectType.getDescribe().isDeletable() or sObject.SObjectType.getDescribe().isUpdateable() or sObject.SObjectType.getDescribe().isCreateable()

Inactive record in FinServ__RollupByLookupConfig__c, if need.


To Delete

Before delete, update "OwnerId" to current user. Like: FinServ__FinancialAccount.OwnerId = UserInfo.getUserId(). Then user can delete FinServ__FinancialAccount record.


To insert

If you want the special user can edit this FinServ__FinancialAccount record, don't forget to update "OwnerId" to the special user's id after insert.

2022-11-29

Delete by record id use Schema SObjectType

public without sharing class CustomDeleteCmpController {

    @AuraEnabled(cacheable=true)

    public static String init(Id recordId) {

        // object name

        return recordId.getSobjectType().getDescribe().getLabel();

   }

 

    @AuraEnabled

    public static String doDelete(Id recordId) {

        try {

            String objApiName;

            RecordDelete.deleteLists(new List<SObject>{recordId.getSobjectType().newSObject(recordId)});

            if (String.isNotBlank(recordId)) {

                objApiName = String.valueOf(recordId.getSObjectType());

            }

            return objApiName;

        } catch (Exception ex) {

            throw ex;

        }

    }

}

2020-07-03

Upload file/attachment | Apex Visualforce | Salesforce

template:
<apex:form>
    <apex:inputFile value="{!file}" />
<apex:commandbutton action="{!upload}" value="Upload" />
</apex:form>
Apex:
// file
public blob file {get;set;}
pubilc PageReference upload(){
    ContentVersion photofile = new ContentVersion();
    if(file != null){
        photofile.VersionData = file;
        photofile.Title='title';
        photofile.IsMajorVersion = false;
        photofile.PathOnClient='/title';
        insert photofile;
    }
    try{
        insert photofile;
    } catch(Exception Ex){
        System.debug('Ex==>'+Ex);
    }
    photofile = [select id, ContentDocumentId from ContentVersion WHERE Id =: photofile.Id];

    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = photofile.ContentDocumentId;
    cdl.LinkedEntityId = [parentId]; 
    cdl.ShareType = 'V';
    cdl.Visibility = 'AllUsers';

    try{
        insert cdl;
    } catch(Exception Ex){
        System.debug('Ex==>'+Ex); 
    }
}
// Attachment
public blob file {get;set;}
pubilc PageReference upload(){
    try {
        if(file != null){
            attachment.body = file;
            attachment.name='title';
            attachment.OwnerId = UserInfo.getUserId();
            attachment.ParentId = [parentId];
            attachment.IsPrivate = true;

            insert attachment;
        }else{
            attachment = new Attachment();
        }
    } catch (Exception e) {
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'error'));
        return null;
    }
}

2016-09-27

How to write Apex test class


An Apex test class is used to confirm if instructions and methods in an application or program are working correctly as desired. Tests can be written for many classes.

Since Salesforce require at least 75% of the code to be tested before it can be deployed to the organization. There are different test classes run to achieve the 75% minimum requirement tests on task codes.

To create an Apex class: [Setup]-[Develop]-[Apex Classes]-[New].
It can also be create through develop console, [You username]-[Develop console]-[File]-[New]-[Apex Class]

Basic strunction of test class
@isTest 
public class BaseTest { 
    // Test Method 
    public static testmethod void Test1(){ 
        // Prepara data for test
        List<Account> accounts = new List<Account>{};
        for(Integer i = 0; i < 200; i++){
            Account a = new Account(Name = 'Test ' + i);
            accounts.add(a);
        }
        Test.startTest(); 
        // Put test target here
        insert accounts;
        Test.stopTest();  
    } 
} 

2016-09-26

Loops in Apex class

For now(2016/9/26), Apex supports do-while, while, and for loops.

do-while:
Integer count = 1;
do {
    System.debug('count' + count);
    count++;
} while (count < 3);

while:
Integer count = 1;
while (count < 4) {
    System.debug('count' + count);
    count++;
}

for(loop in array):
Integer[] is = new Integer[]{1,2,3,4,5};
for (Integer i: is) {
 System.debug(i);
}
Queries can also be embedded in the special for syntax.
for (Test__c tmp : [SELECT Id FROM Test__c]) {
   // ...
}

2016-09-17

How to validate email address with Regex expression in Visualforce page by Apex

When user input email address in Visualforce page, normally need to input the email address again as a confirm email address to make cross check.

If you create a field to save confirm email address. For example, this email address will be saved to Field(Email) in object(Contact), and use inputField tag will be convenient.
<apex:inputField value="{!Contact.Email}"/>
When you try to save, Salesforce will make the format check for you.

But if confirm email address is not a field in object, you may need to check format of confirm email address by Apex. Use Pattern.matches() will be a choice.
Regex foremail format check:
'^([0-9a-zA-Z+_.-]*[0-9a-zA-Z]+[@][0-9a-zA-Z+_.-]+\\.[0-9a-zA-Z+_.-]*)$'
*example email: huang.hai@randsfdc.blogspot.jp

Return the result of format check:
return Pattern.matches('^([0-9a-zA-Z+_.-]*[0-9a-zA-Z]+[@][0-9a-zA-Z+_.-]+\\.[0-9a-zA-Z+_.-]*)$', val); 
*val is the value of email address

To check are these two email address same, you can use String.equals(). Like: emailOne.equals(emailTwo).

String.equals(): Upper char and lower char will be treated as different char.

How to get random strings by Apex?

This post will introduce how to make a random string for using as a token or as a special code.

First, make sure what string you want to get. If you just want a random string within all number, use Math.random() and do for loop will be a easy way. But if you want to pick up the chars or numbers from a special list, try below.

// the list that you want to pick chars and numbers from
String CharList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';

// position in list, count will start from 0. EX. 'a' is in position 0, 'b' is in position 1
Integer position;

// length of random strings, ex. 20
Integer LengthRequired = '20';

// get 20 chars from list randomly
for(Integer i = 0; i <= LengthRequired; i++) {

    position = Integer.valueof(String.valueof(Math.roundToLong(CharList.length()*Math.random()))) -1;

    // the random Strings
    String Res += CharList.substring(position,position+1);

}

2016-09-02

Use Apex class to redirect page

Use Apex class to do this action: When open page 'RedirectPage', move to 'TargetPage' directly.

RedirectPage is name of Visualforce page
Code:
<apex:page controller="RedirectCtrl" action="{!doRedirect}">
    Redirect to TargetPage directly...
</apex:page>

RedirectCtrl is name of Apex class that use to control 'RedirectPage'
Code:
public class RedirectCtrl {
   // create redirect function
   public PageReference doRedirect() {
        // set target page
        PageReference pageRef = Page.TargetPage;
        // set a parameter to url, format 'site.com?PARAME_TYPE=PARAME_TYPE_STR'
        pageref.getParameters().put('PARAME_TYPE','PARAME_TYPE_STR');
        // do page redirect
        pageRef.setRedirect(true);
       // begin to redirect
        return pageRef;
    }
}

TargetPage is name of Visualforce page that 'RedirectPage' will redirect to.
Code:
<apex:page>
    This is target page of redirect action.
</apex:page>

That is all.

2016-08-12

Prevent double submission of forms.

When save customize form data with apex:commandButton, double submission is needed to be attention.

If you use standard control and standard save function, salesforce may help you to prevent double submission. But when you use a customize button action to save data, you will need to do by yourself.

Double submission can be prevented by JavaScript easily and efficiently.

Put code below inside <head></head>
<script type="text/javascript"> 
var isSave = false; 
function check(){ 
if (!isSave) { 
isSave = true; 
return true; 
} 
return false; 
} 
</script> 

Then put <apex:commandbutton> inside of <apex:form></apex:form>.
<apex:commandButton action="{!test}" value="Refresh" onclick="return check();"/>
*value is the button's name; when click this button, function check() will be called and return boolean value.