Comment convertir une pièce jointe en fichiers dans Salesforce – SFDCPanther6 minutes de lecture
Salut à tous,
Dans cet article de blog, nous verrons comment nous pouvons convertir des pièces jointes en fichiers à l’aide du code Apex.
Comme nous savons que Salesforce utilise Lightning Environment et que les pièces jointes seront obsolètes dans un proche avenir. Ainsi, la conversion de la pièce jointe en fichiers et des notes en notes améliorées est très cruciale.
Si vous ne savez pas comment les fichiers sont stockés dans Salesforce, veuillez consulter cet article.
Pour convertir les pièces jointes en fichiers, nous devons insérer le nouvel enregistrement de fichier dans Salesforce. Mais si nous insérons le nouveau disque, nous pouvons perdre Date de création, date de la dernière modification, CreatedById et dernière modification par ID. Donc, pour les conserver, nous devons activer quelques paramètres dans l’organisation Salesforce.
Activez l’autorisation « Créer des champs d’audit »
- De Installer, entrer Utilisateur dans la case Recherche rapide et sélectionnez Interface utilisateur.
- Cochez la case pour Activez les autorisations utilisateur «Définir les champs d’audit lors de la création de l’enregistrement» et «Mettre à jour les enregistrements avec des propriétaires inactifs».
- Cliquez sur sauver.
Une fois que vous avez activé l’autorisation ci-dessus, créez un ensemble d’autorisations personnalisées et activé sous les autorisations sous « Autorisations système.«
- Définir les champs d’audit lors de la création de l’enregistrement – Autorisez l’utilisateur à définir des champs d’audit (tels que «Créé par» ou «Dernière modification par») lorsque vous créez un enregistrement via des outils d’importation d’API tels que Data Loader.
- Mettre à jour les enregistrements avec des propriétaires inactifs – Permettre à l’utilisateur de mettre à jour le propriétaire de l’enregistrement et les enregistrements basés sur le partage avec des propriétaires inactifs.
Maintenant, attribuez ce jeu d’autorisations à l’utilisateur qui convertira la pièce jointe en fichiers.
Vous êtes maintenant prêt à convertir votre pièce jointe ou vos notes dans la version améliorée des deux.
Vous trouverez ci-dessous le code complet pour le même.
public class NotesAndAttachmentConverterHelper {
public static void convertAttachment(Set parentIdsSet){
Savepoint sp = Database.setSavepoint();
List lstAttachment = [SELECT Id, ParentId, Name,Description, CreatedById,
CreatedDate, LastModifiedById, LastModifiedDate,
OwnerId, isPrivate, Body
FROM Attachment where
ParentId IN:parentIdsSet
LIMIT 10000];
try{
Map> mapAttachmentIdLstBlob = new Map>();
Map mapIdAttachment = new Map();
for(Attachment attach: lstAttachment){
String bodyCont = attach.Body!=null ? String.valueOf(attach.Body).replace('&','&')
.replace('','>')
.replace('"','"').replace(''','''):'.';
Blob tmpBlob = Blob.valueOf(bodyCont);
if(!mapAttachmentIdLstBlob.containsKey(attach.Id)){
mapAttachmentIdLstBlob.put(attach.Id, new List());
}
mapAttachmentIdLstBlob.get(attach.Id).add(tmpBlob);
mapIdAttachment.put(attach.Id, attach);
}
Map> mapActIdLstCV =
createContentVersionAttachment(mapAttachmentIdLstBlob, mapIdAttachment);
List lstCVDL = updateContentDocLink(mapActIdLstCV);
}Catch(Exception ex){
Database.rollback(sp);
System.debug('Error-> '+ex.getLineNumber()+' Message : '+ex.getMessage());
throw ex;
}
}
public static void convertNotes(Set parentIdsSet){
List lstNot = [SELECT Id, ParentId, Title, Body FROM Note where
ParentId IN:parentIdsSet LIMIT 10000];
try{
Map> mapNoteIdLstBlob = new Map>();
Map mapIdNote = new Map();
for(Note n: lstNot){
String bodyCont = n.Body!=null ? String.valueOf(n.Body).replace('&','&').replace('','>').replace('"','"').replace(''','''):'.';
Blob tmpBlob = Blob.valueOf(bodyCont);
if(!mapNoteIdLstBlob.containsKey(n.Id)){
mapNoteIdLstBlob.put(n.Id, new List());
}
mapNoteIdLstBlob.get(n.Id).add(tmpBlob);
mapIdNote.put(n.Id, n);
}
Map> mapActIdLstCV = createContentVersion(mapNoteIdLstBlob, mapIdNote);
List lstCVDL = updateContentDocLink(mapActIdLstCV);
}Catch(Exception e){
}
}
public static List updateContentDocLink(Map> actIdLstCVMap){
Set cvSet = new Set();
Map cvIdMap = new Map();
for(Id accId: actIdLstCVMap.KeySet()){
for(ContentVersion cv: actIdLstCVMap.get(accId)){
cvSet.add(cv.Id);
cvIdMap.put(cv.Id, accId);
}
}
List cvLst = [SELECT ContentDocumentId FROM ContentVersion WHERE (Id IN :cvSet)];
List cdlLst = new List();
for(ContentVersion cv: cvLst){
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = cv.ContentDocumentId;
cdl.LinkedEntityId = cvIdMap.get(cv.Id);
cdl.ShareType = 'I';
cdlLst.add(cdl);
}
INSERT cdlLst;
return cdlLst;
}
public static Map> createContentVersion(Map> mapNoteIdLstBlob,
Map mapIdNote){
Map> retMap = new Map>();
List lstCV = new List();
for(Id noteId : mapNoteIdLstBlob.keySet()){
List noteBlob = mapNoteIdLstBlob.get(noteId);
for(Blob b:noteBlob){
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.VersionData = b;
cv.CreatedById = mapIdNote.get(noteId).CreatedById;
cv.Title = mapIdNote.get(noteId).Title;
cv.PathOnClient = mapIdNote.get(noteId).Title+'.snote';
lstCV.add(cv);
if(!retMap.containsKey(mapIdNote.get(noteId).ParentId)){
retMap.put(mapIdNote.get(noteId).ParentId,new List());
}
retMap.get(mapIdNote.get(noteId).ParentId).add(cv);
}
}
INSERT lstCV;
return retMap;
}
public static Map> createContentVersionAttachment(Map> mapNoteIdLstBlob,
Map mapAttachment){
Savepoint sp = Database.setSavepoint();
Map> contentVersionMap = new Map>();
List newFileVersionList = new List();
for(Id attachmentId : mapNoteIdLstBlob.keySet()){
List noteBlob = mapNoteIdLstBlob.get(attachmentId);
for(Blob b:noteBlob){
ContentVersion newFileVersion = new ContentVersion(
versionData = mapAttachment.get(attachmentId).body,
title = mapAttachment.get(attachmentId).name,
description = mapAttachment.get(attachmentId).description,
pathOnClient = '/' + mapAttachment.get(attachmentId).name,
firstPublishLocationId = mapAttachment.get(attachmentId).parentId,
sharingPrivacy = ( mapAttachment.get(attachmentId).isPrivate ? 'P' : 'N' ),
createdById = mapAttachment.get(attachmentId).ownerId,
createdDate = mapAttachment.get(attachmentId).createdDate,
lastModifiedById = mapAttachment.get(attachmentId).lastModifiedById,
lastModifiedDate = mapAttachment.get(attachmentId).lastModifiedDate
//Original_Record__c = mapAttachment.get(attachmentId).id,
//Parent_Id__c = mapAttachment.get(attachmentId).parentId
);
newFileVersionList.add(newFileVersion);
if(!contentVersionMap.containsKey(mapAttachment.get(attachmentId).ParentId)){
contentVersionMap.put(mapAttachment.get(attachmentId).ParentId,new List());
}
contentVersionMap.get(mapAttachment.get(attachmentId).ParentId).add(newFileVersion);
}
}
try{
Database.DMLOptions dmlOptions = new Database.DMLOptions();
dmlOptions.OptAllOrNone = false;
List saveReultRecords = Database.insert(newFileVersionList, dmlOptions);
For(Database.SaveResult sr : saveReultRecords){
if(sr.isSuccess()){
}else if(!sr.isSuccess()){
}
}
return contentVersionMap;
}catch(Exception ex){
Database.rollback(sp);
throw ex;
}
}
}
Description de la méthode
Sr.Non | Nom de la méthode | La description |
1 | convertAttachment (Définir parentIdsSet) | Cette méthode accepte le jeu d’ID d’enregistrement de l’objet parent qui contient des notes et des pièces jointes et convertit toutes les pièces jointes associées en fichiers et associe ces fichiers à l’enregistrement. |
2 | convertNotes (Définir parentIdsSet) | Cette méthode accepte le jeu d’ID d’enregistrement de l’objet parent qui contient des notes et des pièces jointes et convertit toutes les notes associées en note de contenu et associe ces notes à l’enregistrement. |
Remarque: – Les deux méthodes ne convertissent que 10000 pièces jointes ou notes à la fois. Si vous souhaitez convertir davantage, modifiez l’instruction de limite dans la requête SOQL.
Merci d’avoir lu 🙂 Partager c’est prendre soin
#DeveloperGeeks #Salesforce #SfdcPanther #AskPanther
Cliquez pour noter cet article!
[Total:[Total:0 Moyenne: 0]