• Peter Bölke
  • NEWBIE
  • 160 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 52
    Questions
  • 38
    Replies
Hello,

i try to execute an apex class with anonymous code during scratch org setup via sfdx-cli. But it fails with following error.
 
ERROR: System.DmlException: Insert failed. First exception on row 0; first
 !    error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: this ID value isn't
 !    valid for the user:
Is it executed with admin rights so the recordtype should be accessible.

What might be the issue?

thanks
Peter
 
Hello,

i tried 
sfdx force:source:deploy -m ApexClass:Whatever.cls -c -l RunAllTestsInOrg
i get this error:
 
ERROR running force:source:deploy:  The ApexClass named Whatever.cls was not found in the workspace.

Whats wrong? It works fine when i use a package.xml.

thanks
Peter
 
Hello,

i have an lightning component which holds an VF-Page as iframe. I want to read a specific field in this iframe.

it is simple HTML Textfield:
<input id="textfield" type="text" name="testtext" value="test"/>

is that possible?

In the component controller i tried simply:
var iframe = component.find("vfframe");
    console.log("IFRAME", iframe.getElement("textfield"));
but it is not working.

any ideas?

Thanks
Peter


​​​​​​​
Hello,

since our Sandboxes have get Winter'20 all test classes which use FeatureManagement.checkPermission() fail.
As Example:
If you try to execute this in Anonymous Apex on a preview Sandbox:
 
if(!FeatureManagement.checkPermission('blabla')){

System.debug('Is not exsisting');

}

You will get the flowing issue:

System.NoDataFoundException: Data Not Available: The data you were trying to access could not be found. It may be due to another user deleting the data or a system error. If you know the data is not deleted but cannot access it, please look at our https://help.salesforce.com/apex/htdoor?body=%2Ftrain%2FonlineSupport.jsp&loc=support&language=en_US&release=222.4.4&instance=CS108&showSplash=true', 'Help', 1024, 768, 'width=1024,height=768,resizable=yes,toolbar=yes,status=yes,scrollbars=yes,menubar=yes,directories=no,location=yes,dependant=no', false, false);" title="support (New Window)">support page.

Does anyone have a workaround?

thanks

 
Hello,

we want to import Translations for FSL Flows but unfortunatly the flows arent selectable in the translation workbench. How can we import them?

thanks
Peter

 
Hello,

we have one problem with Flexipages. When we create a Flexipage and assign Profiles to to we can retrieve it with force:sourcepull. If we add Profiles later on and try to retrieve it again, then a message shows up saying there were no changes.

How can we retrieve the changes?

regards
Peter
Hello,

during a recent deployment we came across a problem. We tried to delete a role (e.g. named "Role") and a subordinate role (e.g. name "Sub-Role").

Role
|-Sub-Role

first version of our file for destructive changes:
 
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>Role</members>
<members>Sub_Role</members>
        <name>Role</name>
    </types>
</Package>
this failed with the message
Your attempt to delete the role Role could not be completed because users are currently assigned to that role or at least one role reports to that role.: Role: Sub-Role
then we changed the order of the roles 
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>Sub_Role</members>
<members>Role</members>
        <name>Role</name>
    </types>
</Package>

This failes with the same message.

Is it possible to define an order of deletion?

Thanks
Peter

 
Hello,

i created an order (order number 00123456) which is shared programmatically with other users. When i use "login as" on a user which have the order to be shared and type in 123456 in the global search, no result appears in the preview. Typing 00123456 shows the record.

What is the issue on this? Is there a way around?

Thanks
Peter
Hello,

i try to backup my code with Jekins and ANT but it failes with follwoing error
 
Should provide a valid retrieve manifest 'unpackaged'

it failes at this point of my build.xml
 
<target name="retrieve">
	  <sf:retrieve username="${Sandbox1.username}"
				   password="${Sandbox1.password}"
				   serverurl="${sf.serverurl}"
				   retrieveTarget="src"
				   metadataType="Report"
				   unpackaged="unpackaged"
				   
				   />
        <echo message="Commiting all changes with message ${gt.commitMessage}" />
		<git command="add" dir="${Sandbox1.gitDirectory}">
			<args>
				<arg value="." />
			</args>
		</git>
		<git command="commit" dir="${Sandbox1.gitDirectory}">
			<args>
				<arg value="-am ${gt.commitMessage}" />
			</args>
		</git>
	</target>

Any suggestions for fxing this?

thanks
Peter​​​​​​​
Hello,

i try to implement in a Visualforce-Page but i cant get it work.  It seems that pagination is for StandardControllers or Extensions only. Or there any change to get it with fully custom controller?

Page:
<apex:page title="Production Figures" id="thePage" sidebar="false" docType="html-5.0" applyBodyTag="true" controller="CtrlProduction">
	
	<head>
		<link type="text/css" rel="stylesheet" href="{!$Resource.CtrlProductionCss}" />
		<link type="text/css" rel="stylesheet" href="{!URLFOR($Resource.jQueryResource, '/artDialog/skins/twitter.css')}" />
		<style type="text/css">
			th {
				white-space: inherit !important;
			}
		</style>
		
		
		<apex:includeScript value="{!URLFOR($Resource.jQueryResource, '/jquery1.11/jquery-1.11.0.min.js')}" />
		<script src="{!URLFOR($Resource.jQueryResource, '/glob-cultures/globalize.js')}" type="text/javascript"></script>
		<script src="{!URLFOR($Resource.jQueryResource, lc.jsPath)}" type="text/javascript"></script>
		
		<script src="{!URLFOR($Resource.jQueryResource, '/Utils.js')}"></script>
		<script src="{!$Resource.CtrlProductionJs}" type="text/javascript"></script>
		<script src="{!URLFOR($Resource.jQueryResource, '/artDialog/artDialog.min.js')}"></script>
        <script src="{!URLFOR($Resource.jQueryResource, '/artDialog/artDialog.plugins.min.js')}"></script>
		<script type="text/javascript">
			;function setFocusOnLoad(){}
        	var CUSTOM_LABEL = {
        		'save' : '{!$Label.Save_Message}', 
        		'cancel' : '{!$Label.Production_Cancel_Message}',
        		'nopm': '{!$Label.No_Permission}'
        	};
			addListener(window, 'load', initDocument, {'locale':'{!lc.locale}'});
        </script>

	</head>
	<body>
		<apex:form >
			<apex:sectionHeader title="{!$Label.Production_Figures}" />
			<apex:inputHidden id="isGroup" value="{!Competence}"/>
			<apex:actionFunction name="save" action="{!save}" oncomplete="saveComplete()" reRender="bodyContentId, themsg" />
			
			<div id="dmsgid"><apex:pageMessages id="themsg"/></div>
			<div id="pageLoading" class=""></div>
			<div id="popupLoading" style="display: none;"></div>

			<div class="content" id="contentAll">
			
				<div class="headerButtonDiv tc">
					<input type="button" class="commonButton Btn_save" value="{!$Label.Save_Button}" />
					<input type="button" class="commonButton Btn_cancel" value="{!$Label.Cancel_Button}" />
				</div>
				
				<div class="tableDiv">
					<c:CompProductionBody pageCtrl="{!this}" id="comptableid"></c:CompProductionBody>
				</div>
				
				<div class="footerButtonDiv tc">
					<input type="button" class="commonButton Btn_save" value="{!$Label.Save_Button}" />
					<input type="button" class="commonButton Btn_cancel" value="{!$Label.Cancel_Button}" />
				</div>
				
			</div>
			            <apex:panelGrid columns="7">
                <apex:commandButton status="fetchStatus" reRender="pb" value="|<" action="{!first}" disabled="{!Not(hasPrevious)}" title="First Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value="<" action="{!previous}" disabled="{!Not(hasPrevious)}" title="Previous Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">" action="{!next}" disabled="{!Not(hasPrevious)}" title="Next Page"/>
                <apex:commandButton status="fetchStatus" reRender="pb" value=">|" action="{!last}" disabled="{!Not(hasPrevious)}" title="Last Page"/>
                <apex:outputText >{!(pageNumber * size)+1-size}-{!IF((pageNumber * size)>noOfRecords, noOfRecords,(pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton status="fetchStatus" reRender="pb" value="Refresh" action="{!refresh}" title="Refresh Page"/>
                <apex:outputPanel style="color:#4AA02C;font-weight:bold">
                    <apex:actionStatus id="fetchStatus" startText="Fetching..." stopText=""/>
                </apex:outputPanel>
            </apex:panelGrid>
		</apex:form>
	</body>

</apex:page>
Component with data:
<apex:component >
    <apex:attribute name="pageCtrl" type="CtrlProduction" required="true" description="the root page controller reference" />
    <apex:outputPanel layout="block" id="bodyContentId">
        <apex:inputHidden id="saveJsonList" value="{!pageCtrl.saveJson}"/>
        <div class="divcomponentbox">
            <table class=" table_fix oemTable" border="0" cellspacing="0" cellpadding="0">
                <colgroup class="currentColgroup">
                    <apex:repeat var="column" value="{!pageCtrl.columnlist}">
                        <col class="{!column.name}" />
                    </apex:repeat>             
                </colgroup> 
                
                <thead>
                    <tr>
                        <th class="thheight tc blcolor btcolor thbr"></th>
                        <th class="thheight tc btcolor brcolor" colspan="{!pageCtrl.columnyearmap['currentyear'].colspan}">{!pageCtrl.columnyearmap['currentyear'].value}</th>
                        <th class="thheight tc space"></th>
                        <th class="thheight tc btcolor" colspan="{!pageCtrl.columnyearmap['nextyear'].colspan}">{!pageCtrl.columnyearmap['nextyear'].value}</th>
                    </tr>
                    <tr >
                        <apex:repeat var="column" value="{!pageCtrl.columnlist}">
                            <th class="thheight1 thbr tc {!column.name}"> 
                                <span class="field" >{!column.displayName}</span>
                            </th>
                        </apex:repeat>
                    </tr>
                </thead>
                
                
                <tbody id="actbodyid">
                    <!-- START each account list -->
                    <apex:variable value="{!0}" var="indextr" />
                    
                    <apex:repeat var="act" value="{!pageCtrl.accountlist}">
                        <tr data-value="{!act.valueJson}" data-id="{!act.accid}" data-cid="{!act.currentpfid}" data-nid="{!act.nextpfid}" 
                            data-name="{!act.name}" class="{!if(mod(indextr, 2) == 1, 'trOddStyle', '')} trbodycls">
                            <apex:variable value="{!indextr + 1}" var="indextr" />
                            <apex:variable value="{!0}" var="index" />
                            <apex:repeat var="column" value="{!pageCtrl.columnlist}">
                                <td class="tdheight thbr {!if(index = 0, '', 'tr')} ov {!column.name}" data-field="{!column.fieldname}">
                                    <div>
                                        <!-- //updated by Steven Qiao<rui.qiao@oinio.com> 2016-09-27 -->
                                        <span class="textspan">{!if(index = 0, act.name, '')}</span>
                                        <apex:inputText rendered="{!column.isInput}" styleClass="{!column.name}_input tr inputw" />
                                        <span class="percentspan"></span>
                                    </div>
                                </td>
                                <apex:variable value="{!index + 1}" var="index" />
                            </apex:repeat>
                        </tr>
                    </apex:repeat>
                    <!-- END each account list -->
                </tbody>
            </table>
        </div>

    </apex:outputPanel>
</apex:component>


Can someone give me an advise?

thanks
Peter
 
Hello,

we want to use the Inline Account Hierarchy (from Salesforce Labs installiert) in a Salesforce Lightning Community. But it shows
Insufficient Privileges
You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary. For more information, see Insufficient Privileges Errors.

I checked everthing about permissions but can't see anthing what would prevent access.

Can someone help?

thanks
Peter
Hello,

i am getting this error when i try to save a lightning component:
 
FIELD_INTEGRITY_EXCEPTION

Failed to save LtngCustomNewVisitReportCmp.cmp: The API version of this bundle must be set to '45' or later to use component 'markup://lightning:eventBusAPI': Source

Developer-Org has API45 but prooduction has 44. Every Component and Apex-Class has an lower API than 45 defined.

I need help! :)

thanks
Peter
Hello,

i have some trouble deploying a trigger and an approval process. The Process exists in an older version in the production environment.
The changeset includes the Trigger, Testclass and new version of approval process.
When i run the test-class in production, i am getting this error:
 
System.DmlException: Process failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Too many retries of batch save in the presence of Apex triggers with failures: when triggers are present partial save requires that some subset of rows save without any errors in order to avoid inconsistent side effects from those triggers. Number of retries: 2: [] 
Stack Trace: Class.TrgKnowledgeSendNotificationTest.test01: line 80, column 1

It runs in our sandbox without any errors.

Do i need to deploy the new version of approval process seperatly in advace of deploying the trigger?

thanks
PEter
Hello,

we need a trigger which executes when a file is uploaded to opportunity. File needs to be linked to the account which is related to the opportunity.
Want to check the LinkedEntityId of the ContentDocumentLink created by the upload if its an Opportunity or nor. The problem is that LinkedEntityId includes the id of the uploading user but not the of the opportunity to which the file is uploaded.

But i need the opportunity-id.

My Trigger runs on ContentVersion and uses following helper:
 
public class TrgContentVersionHelper {
    
    public void updateAccountFiles(List<ContentVersion> lcv){
        System.debug('TrgContentVersionHelper UPDATE:: ' + lcv);
    }
    
    public void insertAccountFiles(List<ContentVersion> lcv){
        System.debug('TrgContentVersionHelper INSERT:: '+lcv);
        Set<Id> contentDocumentIdSet = new Set<Id>();
        
        for(ContentVersion cv:lcv)
        {
            System.debug(cv);
            if(cv.ContentDocumentId != null)
            {
                contentDocumentIdSet.add(cv.ContentDocumentId);
            }
        }
        
        ContentDocumentLink cd = [SELECT ContentDocumentId, LinkedEntityId, ShareType FROM ContentDocumentLink WHERE ContentDocumentId = :lcv[0].ContentDocumentId Limit 1];
        id checkId = cd.LinkedEntityId;
        Map<Id, ContentVersion> historyMap = new Map<Id, ContentVersion>(lcv);
        System.debug('HI '+ historyMap);
        System.debug(checkId.getSobjectType());
        if(checkId.getSobjectType() == Opportunity.sObjectType){
            System.debug('Links ' + cd);
            List<ContentDocumentLink> cdl = new List<ContentDocumentLink>();
            try{

                Opportunity lOp = [SELECT Id, AccountId From Opportunity WHERE Id =:cd.LinkedEntityId][0];
                List<ContentVersion> cvList = [SELECT Id, ContentDocumentId FROM ContentVersion where Id IN: historyMap.keySet()];
                
                for(ContentVersion cv:cvList)
                {
                    if(lOp != Null)
                    {
                        ContentDocumentLink c = new ContentDocumentLink();
                        c.ContentDocumentId = cd.ContentDocumentId;
                        c.LinkedEntityId = lOp.AccountId;
                        c.ShareType = cd.ShareType;
                        cdl.add(c);
                    }
                }
                upsert cdl;
                
            }
            catch(Exception e){
                System.debug(e);
            }
        }
    }
}

Can anyone give an advise?

thanks
Peter
 
Hello,

we are on lightning and on a custom record page i have button which is linked to VF-Page. This page hold two lightning componenten and two VF-componnent.
I have an issue with the lightning components there is another button which shouuld open another component, but i fails with:
 
TypeError: Cannot read property 'setParams' of undefined

and this is the code what causes this exception:
 
var action1 = $A.get("e.force:navigateToComponent");
action1.setParams({
    componentDef: "c:LtngBusinessPotentialsViewAllComp", 
    componentAttributes: { 
        rId : component.get('v.recordId')
    }
});
action1.fire();

I don't know why this action is 'undefined'. This code work in other components.

Can you give me an advise?

thanks
Peter
Hello,

we are using gmail (with company-domain addresses) and Salesforce with "Lightning For Gmail" but facing a problem. A Trigger sends an mail to some recipients when a Knowledge article is released. The problem is that internal persons with addresses dont get the notification. Those emails seems bounced by gmail with the message "sender authorization check failed". While external contact with non-gmail-addresses get the notification.

What is the problem?

regards
Peter
Hello,

i need to return a list of Campaigns which fullfill following requirement

WHERE Campaign.StartDate <= Today AND Campaign.EndDate + 7Days > Today

How can i do this in SOQL?

Thanks
Peter
Hello,

i have problem, with my Triggern. It sends all Emails twice, and i can't find a reason for this behaviour

trigger:
trigger TrgKnowledgeSendNotification on Knowledge__kav (after update, after insert) {
    System.debug('TRIGGER :: ' + Trigger.New);
    System.debug('TRIGGER :: ' + Trigger.Old);
    System.debug('TRIGGER COMP ' + (Trigger.Old == Trigger.New));
    id acId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('abc').getRecordTypeId();
    System.debug('ACID :: ' + acId);
    id kaId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('xyz').getRecordTypeId();
    System.debug('KaID :: ' + kaId);
    System.debug('PUBLISH COMPARE :: ' + (Trigger.New[0].PublishStatus =='Online'));
    if(KnowledgebaseMailTriggerHandler.isFirstTime && Trigger.New[0].Approved__c == true){    
        KnowledgebaseMailTriggerHandler.isFirstTime =false;
        if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == acId){ //Trigger.New[0].ValidationStatus == 'Validated' &&
            KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
            try{
                kmth.sendAcPartnerPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            try{
                kmth.sendAcInternalPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                
                System.debug('SEND FAIL ' + ex.getStackTraceString());
                
            }  
        }
        else if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == kaId ){//&& Trigger.New[0].PublishStatus == 'Online'
            KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
            try{
                kmth.sendKartPartnerPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            try{
                kmth.sendKartInternalPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            
        }
    }
}

trigger handler
 
public class KnowledgebaseMailTriggerHandler {
    
    public static Boolean isFirstTime = true;
    
    
    public void sendAcPartnerPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setCcAddresses(null);
        mail.setToAddresses(null);
        mail.setBccAddresses(getEmailAddresses('abc Partners'));
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='AC_AUTO_ArticlePublication'];
        
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null || article.Publication_Type__c != '') {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', host+'portalLightning/s/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        
        mail.setHtmlBody(htmlBody);
        System.debug('MAIL ' + mail);
        if (mail.getBccAddresses().size() != null && mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
                else{
                    User[] usr = [SELECT email FROM user WHERE Username like '%abilex%' Limit 1];
                    List<String> mailToAddresses = new List<String>();
                    for (User u : usr){
                        mailToAddresses.add(u.Email);
                    }
                    mail.setBccAddresses(mailToAddresses);
                    System.debug(usr);
                    System.debug(mailToAddresses);
                    System.debug('tesmtail '+ mail);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
        
    }
    
    public void sendAcInternalPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setCcAddresses(null);
        mail.setToAddresses(null);
        mail.setBccAddresses(getEmailAddresses('abc Business'));
        mail.setTargetObjectId(userinfo.getUserId());
        //mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject  from EmailTemplate where Name='AC_AUTO_ArticlePublication_Internal'];
        
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        System.debug('MAIL ' + mail);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
        
    }
    
    public void sendKartPartnerPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //mail.setAddresses(false);
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setBccSender(true);
        //mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccAddresses(getEmailAddresses('xyz Partners'));
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='KA_AUTO_ArticlePublication'];
        mail.setTemplateId(et.id);
        
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', article.Link_to_Knowledge_Article__c);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
    }
    
    public void sendKartInternalPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='KA_AUTO_ArticlePublication_Internal'];
        mail.setBccAddresses(getEmailAddresses('xyz Business'));
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', article.Link_to_Knowledge_Article__c);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
    }
    
    public List<String> getEmailAddresses(String groupname) {
        
        List<String> idList = new List<String>();
        List<String> mailToAddresses = new List<String>();
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupname];
        for (GroupMember gm : g.groupMembers) {
            
			//System.debug('object is '+ gm.userOrGroupId.getsobjecttype());
            idList.add(gm.userOrGroupId);
        }
        
        User[] usr = [SELECT id, email FROM user WHERE id IN :idList];
        for (User u : usr) {
            if(UserInfo.getUserId() != u.id){
                mailToAddresses.add(u.email);
            }
        }
        Set<String> myset = new Set<String>();
        List<String> result = new List<String>();
        myset.addAll(mailToAddresses);
        result.addAll(myset);
        system.debug('MAIL RECIEPTS :: ' + result.size());
        system.debug('MAIL RECIEPTS :: ' + result);
        return result;
        
    }
}
Can someone give an advise

thanks!
 
Hello,

i have an issue with appoval process on Knowledge Articles. It runs through the approval process but it is not calling the trigger when ValidationStatus is  'Validated' and PublishStatus is 'Online' as it should.
 
public testMethod static void testKartKnowledge(){

        Knowledge__kav art = new Knowledge__kav();
        art.Title = 'Test';
        art.Summary = 'Test Summary';

        art.RecordTypeId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('Kart').getRecordTypeId();
        art.IsVisibleInCsp = true;
        art.IsVisibleInPkb = true;
        art.IsVisibleInPrm = true;
        art.UrlName = 'ttttttttttttttt';
        art.Article_Body__c = 'wergwgwegq rfewrg aerg ear ge r';
        insert art;



        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
        req.setComments('Submitted for Approval. Please Review');
        req.setNextApproverIds(new Id[] {UserInfo.getUserId()});
        req.setObjectId(art.Id);
        req.setSkipEntryCriteria(true);
        req.setProcessDefinitionNameOrId('Approval_of_Knowledge_Articles_new');

        //Knowledge__kav art4 = [Select Id, PublishStatus, KnowledgeArticleId, Language, ValidationStatus, RecordType.DeveloperName  FROM Knowledge__kav WHERE Id = :art3.Id];
        Approval.ProcessResult result =  Approval.process(req);
        System.debug(result);

        System.assert(result.isSuccess());
        List<Id> newWorkItemIds = result.getNewWorkitemIds();

        // Instantiate the new ProcessWorkitemRequest object and populate it
        Approval.ProcessWorkitemRequest req2 =
                new Approval.ProcessWorkitemRequest();
        req2.setComments('Approving request.');
        req2.setAction('Approve');
        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});

        // Use the ID from the newly created item to specify the item to be worked
        req2.setWorkitemId(newWorkItemIds.get(0));

        // Submit the request for approval
        Approval.ProcessResult result2 =  Approval.process(req2);

        // Verify the results
        System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());

        System.assertEquals(
                'Approved', result2.getInstanceStatus(),
                        'Instance Status'+result2.getInstanceStatus());

        Knowledge__kav art4 = [Select Id, PublishStatus, KnowledgeArticleId, Language, ValidationStatus, RecordType.DeveloperName  FROM Knowledge__kav WHERE Id = :art.Id];
        System.debug('ART 4 :: ' + art4);
        //KbManagement.PublishingService.publishArticle(art4.KnowledgeArticleId, true);

    }

trigger:
trigger TrgKnowledgeSendNotification on Knowledge__kav (after update) {
    System.debug('TRIGGER :: ' + Trigger.New);

    id kartId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('Kart').getRecordTypeId();


    if(Trigger.Old != null){
        
 if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == kartId && Trigger.New[0].PublishStatus == 'Online'){
                
                KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
                kmth.sendKartPartnerPublicationNotification(Trigger.New[0].Id);
                kmth.sendKartInternalPublicationNotification(Trigger.New[0].Id);
                
            }
            
        //}
        
    }
}

As i understand the log, the trigger is not called when the article passed the approval process and is published. 

How can i solve this issue?

thanks
Peter
 
Hello,

i have trigger on Knowledge_kav but i can not test it properly.

This my Test:
@isTest(SeeAllData=True)
public class TrgKnowledgeSendNotificationTest {
	
    public testMethod static void testAircraftKnowledge(){

        Knowledge__kav art = new Knowledge__kav();
        art.Title = 'Test';
        art.Summary = 'Test Summary';

        art.RecordTypeId = [Select RecordTypeId From Knowledge__kav WHERE RecordType.DeveloperName= 'Plane' Limit 1].RecordTypeId;
        //art.ValidationStatus = 'Validated';
        art.IsVisibleInCsp = true;
        art.IsVisibleInPkb = true;
        art.IsVisibleInPrm = true;
        art.UrlName = 'ttttttttttttttt';
        art.Article_Body__c = 'wergwgwegq rfewrg aerg ear ge r';
        insert art;
        Knowledge__kav art2 = [Select Id, PublishStatus, KnowledgeArticleId, Language, ValidationStatus, RecordType.DeveloperName  FROM Knowledge__kav WHERE Id = :art.Id];
        art2.ValidationStatus = 'Validated';
        update art2;
        System.debug('TEST2 :: ' + art2);
        Knowledge__kav art3 = [Select Id, PublishStatus, KnowledgeArticleId, Language, ValidationStatus, RecordType.DeveloperName  FROM Knowledge__kav WHERE Id = :art2.Id];
        System.debug('TEST3 :: ' + art3);
        update art3;
        KbManagement.PublishingService.publishArticle(art2.KnowledgeArticleId, true);

        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
        req.setObjectId(art2.KnowledgeArticleId);
        req.setProcessDefinitionNameOrId(UserInfo.getUserId());
        Knowledge__kav art4 = [Select Id, PublishStatus, KnowledgeArticleId, Language, ValidationStatus, RecordType.DeveloperName  FROM Knowledge__kav WHERE Id = :art3.Id];
        //Approval.ProcessResult result =  Approval.process(req);
        //System.debug(result);
		System.debug('TEST4 :: ' +art4);
        
    }
    
}

My problem ist, that the field ValidationStatus is not changed to 'Validated' after i save "art2". When i do a debug for art3 ValidationStatus is 'Not Validated' again.

How can i solve this?

regards
Peter
Hello,

i need to get the picklist value for Field Reason of the Case-Objekt. Those vary depending on the record type. I found this on the net, but i am getting an Error 401

function:
@AuraEnabled
    public static List<reasonObject> getReasonRest(Id eId){
        System.debug(eId);
        Map<String,String> sessionAttributes = Auth.SessionManagement.getCurrentSession();
        System.debug('Session '+sessionAttributes.get('SessionId'));
        Id rType = [SELECT id, RecordTypeId FROM Case WHERE ID = :eId].RecordTypeId;
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        String host = System.Url.getSalesforceBaseURL().toExternalForm();
        String url = host + '/services/data/v43.0/ui-api/object-info/Case/picklist-values/'+rType+'/Reason';
        //String url = host + '/ui-api/object-info/Case/picklist-values/'+rType+'/Reason';
        System.debug(url);
        request.setEndpoint(url);
        request.setMethod('GET');  
        request.setHeader('Authorization', 'OAuth '+sessionAttributes.get('SessionId'));
        HttpResponse response;        
        response = http.send(request);
        System.debug('response ' + response);
        Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
        system.debug(meta);
		List<reasonObject> optionsList = new List<reasonObject>();
        //optionsList.add(new SelectOption('--None--', ''));
        if(meta.containsKey('values')){                                
                for(Object o: (List<Object> )meta.get('values')){
                    Map<String, object > temp = (Map<String, object>)o;        
                    System.debug((String)temp.get('label')+ ' ' + (String)temp.get('value'));
                    reasonObject ro = new reasonObject();
                    ro.label=(String)temp.get('label');
                    ro.value=(String)temp.get('value');
                    //optionsList.add(new SelectOption((String)temp.get('label'), (String)temp.get('value')));
                    optionsList.add(ro);
                }
            }
        return optionsList;
    }
Error
System.HttpResponse[Status=Unauthorized, StatusCode=401]
Any suggestions on this?
Is there a better solution for Lightning components?

regards
Peter
Hello,

 i am getting an Error "Too many SOQL queries: 101".
 
public class WarengruppenZuordnung {
    /********************* Properties used by getRootNodeOfUserTree function - starts **********************/
    // map to hold roles with Id as the key
    private static Map <Id, Warengruppen_Struktur__c> warengruppeMap;
    
    // map to hold child roles with parentRoleId as the key
    private static Map <Id, List<Warengruppen_Struktur__c>> parentWarengruppeMap;
    
    // List holds all subordinates
    private static List<Warengruppen_Struktur__c> allProducts {get; set;}
    
    // Global JSON generator
    private static JSONGenerator gen {get; set;}
    public static String folderId{get;set;}
    public static String folderName{get;set;}
    public static String endpointId{get;set;}
    /********************* Properties used by getRootNodeOfUserTree function - ends **********************/
    
    
    /********************* Properties used by getSObjectTypeById function - starts ********************* */
    // map to hold global describe data
    private static Map<String,Schema.SObjectType> gd;
    
    // map to store objects and their prefixes
    private static Map<String, String> keyPrefixMap;
    
    // to hold set of all sObject prefixes
    private static Set<String> keyPrefixSet;
    /********************* Properties used by getSObjectTypeById function - ends **********************/
    
    public static String redirUrl{get;set;}
    public String contactId {get;set;}
    
    /* // initialize helper data */ 
    static {
        // initialize helper data for getSObjectTypeById function
        Map<String, String> UrlParameterMap = ApexPages.currentPage().getParameters();
        //redirUrl = getRedirUrl();
        gen = JSON.createGenerator(true);
        init1();
        gen = JSON.createGenerator(true);
        // initialize helper data for getRootNodeOfUserTree function
        init2();
    }
    
    /* // init1 starts <to initialise helper data> */
    private static void init1() {
        // get all objects from the org
        gd = Schema.getGlobalDescribe();
        // to store objects and their prefixes
        keyPrefixMap = new Map<String, String>{};
            
            //get the object prefix in IDs
            keyPrefixSet = gd.keySet();
        
        // fill up the prefixes map
        for(String sObj : keyPrefixSet) {
            Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
            String tempName = r.getName();
            String tempPrefix = r.getKeyPrefix();
            keyPrefixMap.put(tempPrefix, tempName);
        }
    }
    /* // init1 ends */
    
    /* // init2 starts <to initialise helper data> */
    private static void init2() {
        
        // Create a blank list
        allProducts = new List<Warengruppen_Struktur__c>();

        for(AggregateResult wsc : [SELECT Name, RecordTypeId, RecordType.DeveloperName FROM Warengruppen_Struktur__c GROUP BY RecordTypeId, RecordType.DeveloperName, Name ORDER BY Name]) {
            if(String.valueOf(wsc.get('DeveloperName')).contains('Ordner')){
                folderId = String.valueOf(wsc.get('RecordTypeId'));
                folderName = String.valueOf(wsc.get('Name'));
            }
            if(String.valueOf(wsc.get('DeveloperName')).contains('Endpunkt')){
                endpointId = String.valueOf(wsc.get('RecordTypeId'));
                
            }
        }
        
        warengruppeMap = new Map<Id, Warengruppen_Struktur__c>([select Id, Name, Parent_Warengruppe__c, RecordTypeId from Warengruppen_Struktur__c order by Name]);
        // populate parent role - child roles map
        parentWarengruppeMap = new Map <Id, List<Warengruppen_Struktur__c>>();        
        for (Warengruppen_Struktur__c r : warengruppeMap.values()) {
            List<Warengruppen_Struktur__c> tempList;
            if (!parentWarengruppeMap.containsKey(r.Parent_Warengruppe__c)){
                tempList = new List<Warengruppen_Struktur__c>();
                tempList.Add(r);
                parentWarengruppeMap.put(r.Parent_Warengruppe__c, tempList);
            }
            else {
                tempList = (List<Warengruppen_Struktur__c>)parentWarengruppeMap.get(r.Parent_Warengruppe__c);
                tempList.add(r);
                parentWarengruppeMap.put(r.Parent_Warengruppe__c, tempList);
            }
        }
    } 
    /* // init2 ends */
    
    /* // public method to get the starting node of the RoleTree along with user list */
    public static RoleNodeWrapper getRootNodeOfUserTree (Id userOrRoleId) {
        return createNode(userOrRoleId);
    }
    
    /* // createNode starts */
    private static RoleNodeWrapper createNode(Id objId) {
        RoleNodeWrapper n = new RoleNodeWrapper();
        Id roleId;
        if (isRole(objId)) {
            roleId = objId;
            if (!(warengruppeMap.get(objId).Parent_Warengruppe__c == null)) {
                List<Warengruppen_Struktur__c> tempFolderList = new List<Warengruppen_Struktur__c>();
                Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId, RecordType.DeveloperName from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
                tempFolderList.add(tempFolder);
                if(tempFolderList.size()== 1){
                    if(tempFolderList[0].RecordType.DeveloperName.contains('Ordner')){
                        n.hasFolders = false;
                        n.myFolders = tempFolderList;
                        n.isLeafNode = false;
                        allProducts.addAll(n.myFolders);
                    }
                    else{
                        n.hasFolders = false;
                        n.myFolders = tempFolderList;
                        n.isLeafNode = true;
                        allProducts.addAll(n.myFolders);
                    }
                }
            }
        }
        else {
            List<Warengruppen_Struktur__c> tempFolderList = new List<Warengruppen_Struktur__c>();
            Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
            tempFolderList.add(tempFolder);
            n.myFolders = tempFolderList;
            roleId = tempFolder.Parent_Warengruppe__c;
        }
        n.myRoleId = roleId;
        n.myRoleName = warengruppeMap.get(roleId).Name;
        n.myParentRoleId = warengruppeMap.get(roleId).Parent_Warengruppe__c;
        n.RecordTypeId = warengruppeMap.get(roleId).RecordTypeId;
        if (parentWarengruppeMap.containsKey(roleId)){
            n.hasChildren = true;
            n.isLeafNode = false;
            List<RoleNodeWrapper> lst = new List<RoleNodeWrapper>();
            for (Warengruppen_Struktur__c r : parentWarengruppeMap.get(roleId)) {
                lst.add(createNode(r.Id));
            }           
            n.myChildNodes = lst;
        }
        else {
            n.isLeafNode = true;
            n.hasChildren = false;
            
        }
        return n;
    }
    
    public static List<Warengruppen_Struktur__c> getAllProducts(Id warengruppeId){
        createNode(warengruppeId);
        return allProducts;
    }
    
    public static String getTreeJSON(Id userOrRoleId) {
        gen = JSON.createGenerator(true);
        RoleNodeWrapper node = createNode(userOrRoleId);
        gen.writeStartArray();
        convertNodeToJSON(node);
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    public static String getTreeJSON() {
        gen = JSON.createGenerator(true);
        List<Warengruppen_Struktur__c> wRoots = [Select Id, Name, RecordTypeId From Warengruppen_Struktur__c Where Parent_Warengruppe__c = '' ORDER BY Name];
        gen.writeStartArray();
        for(Warengruppen_Struktur__c ws : wRoots){
            RoleNodeWrapper node = createNode(ws.Id);
            convertNodeToJSON(node);
        }
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    private static void convertNodeToJSON(RoleNodeWrapper objRNW){
        gen.writeStartObject();
        gen.writeStringField('title', objRNW.myRoleName);
        gen.writeStringField('key', objRNW.myRoleId);
        gen.writeStringField('RecordTypeID', String.valueOf(objRNW.RecordTypeId));
        gen.writeBooleanField('unselectable', false);
        gen.writeBooleanField('expand', true);
        gen.writeBooleanField('isFolder', true);
        if (objRNW.hasFolders || objRNW.hasChildren)
        {
            gen.writeFieldName('children');
            gen.writeStartArray();
            if (objRNW.hasFolders)
            {
                for (Warengruppen_Struktur__c u : objRNW.myFolders)
                {
                    gen.writeStartObject();
                    gen.writeStringField('title', u.Name);
                    gen.writeStringField('key', u.Id);
                    gen.writeStringField('RecordTypeID', String.valueOf(objRNW.RecordTypeId));
                    gen.writeBooleanField('isFolder', false);
                    gen.WriteEndObject();
                }
            }
            if (objRNW.hasChildren)
            {
                
                for (RoleNodeWrapper r : objRNW.myChildNodes)
                    
                {
                    convertNodeToJSON(r);
                    
                }
            }
            gen.writeEndArray();
        }
        gen.writeEndObject();
    }
    
    /* // general utility function to get the SObjectType of the Id passed as the argument, to be used in conjunction with */ 
    public static String getSObjectTypeById(Id objectId) {
        String tPrefix = objectId;
        tPrefix = tPrefix.subString(0,3);
        String objectType = keyPrefixMap.get(tPrefix);
        return objectType;
    }
    /* // utility function getSObjectTypeById ends */
    
    /* // check the object type of objId using the utility function getSObjectTypeById and return 'true' if it's of Role type */
    public static Boolean isRole (Id objId) {
        if (getSObjectTypeById(objId) == String.valueOf(Warengruppen_Struktur__c.sObjectType)) {
            return true;
        }
        else if (getSObjectTypeById(objId) != String.valueOf(Warengruppen_Struktur__c.sObjectType)) {
            return false;
        } 
        return false;
    }
    /* // isRole ends */
    
    public class RoleNodeWrapper {
        
        // Role info properties - begin
        public String myRoleName {get; set;}
        
        public Id myRoleId {get; set;}
        public Id RecordTypeId {get; set;}
        public String myParentRoleId {get; set;}
        // Role info properties - end
        
        
        // Node children identifier properties - begin
        public Boolean hasChildren {get; set;}
        
        public Boolean isLeafNode {get; set;}
        
        public Boolean hasFolders {get; set;}
        // Node children identifier properties - end
        
        
        // Node children properties - begin
        public List<Warengruppen_Struktur__c> myFolders {get; set;}
        
        public List<RoleNodeWrapper> myChildNodes {get; set;}
        // Node children properties - end   
        
        public RoleNodeWrapper(){
            hasFolders = false;
            hasChildren = false;
        }
    }
    
    public static String getRedirUrl(){
        Map<String, String> UrlParameterMap = ApexPages.currentPage().getParameters();
        redirUrl = UrlParameterMap.values()[1];
        return redirUrl;        
    }
    
    public String getContactId()
    {
        return Apexpages.currentPage().getParameters().get('id');
        
    }

}

This Error occur in this line
 
Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId, RecordType.DeveloperName from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
How to change this to get it working?

Any Ideas :(?

Thanks
Peter
Hello,

we want to import Translations for FSL Flows but unfortunatly the flows arent selectable in the translation workbench. How can we import them?

thanks
Peter

 
Hello,

during a recent deployment we came across a problem. We tried to delete a role (e.g. named "Role") and a subordinate role (e.g. name "Sub-Role").

Role
|-Sub-Role

first version of our file for destructive changes:
 
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>Role</members>
<members>Sub_Role</members>
        <name>Role</name>
    </types>
</Package>
this failed with the message
Your attempt to delete the role Role could not be completed because users are currently assigned to that role or at least one role reports to that role.: Role: Sub-Role
then we changed the order of the roles 
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>Sub_Role</members>
<members>Role</members>
        <name>Role</name>
    </types>
</Package>

This failes with the same message.

Is it possible to define an order of deletion?

Thanks
Peter

 
Hello,

we want to use the Inline Account Hierarchy (from Salesforce Labs installiert) in a Salesforce Lightning Community. But it shows
Insufficient Privileges
You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary. For more information, see Insufficient Privileges Errors.

I checked everthing about permissions but can't see anthing what would prevent access.

Can someone help?

thanks
Peter
Hello,

i am getting this error when i try to save a lightning component:
 
FIELD_INTEGRITY_EXCEPTION

Failed to save LtngCustomNewVisitReportCmp.cmp: The API version of this bundle must be set to '45' or later to use component 'markup://lightning:eventBusAPI': Source

Developer-Org has API45 but prooduction has 44. Every Component and Apex-Class has an lower API than 45 defined.

I need help! :)

thanks
Peter
Hello,

i have some trouble deploying a trigger and an approval process. The Process exists in an older version in the production environment.
The changeset includes the Trigger, Testclass and new version of approval process.
When i run the test-class in production, i am getting this error:
 
System.DmlException: Process failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Too many retries of batch save in the presence of Apex triggers with failures: when triggers are present partial save requires that some subset of rows save without any errors in order to avoid inconsistent side effects from those triggers. Number of retries: 2: [] 
Stack Trace: Class.TrgKnowledgeSendNotificationTest.test01: line 80, column 1

It runs in our sandbox without any errors.

Do i need to deploy the new version of approval process seperatly in advace of deploying the trigger?

thanks
PEter
Hello,

i need to return a list of Campaigns which fullfill following requirement

WHERE Campaign.StartDate <= Today AND Campaign.EndDate + 7Days > Today

How can i do this in SOQL?

Thanks
Peter
Hello,

i have problem, with my Triggern. It sends all Emails twice, and i can't find a reason for this behaviour

trigger:
trigger TrgKnowledgeSendNotification on Knowledge__kav (after update, after insert) {
    System.debug('TRIGGER :: ' + Trigger.New);
    System.debug('TRIGGER :: ' + Trigger.Old);
    System.debug('TRIGGER COMP ' + (Trigger.Old == Trigger.New));
    id acId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('abc').getRecordTypeId();
    System.debug('ACID :: ' + acId);
    id kaId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get('xyz').getRecordTypeId();
    System.debug('KaID :: ' + kaId);
    System.debug('PUBLISH COMPARE :: ' + (Trigger.New[0].PublishStatus =='Online'));
    if(KnowledgebaseMailTriggerHandler.isFirstTime && Trigger.New[0].Approved__c == true){    
        KnowledgebaseMailTriggerHandler.isFirstTime =false;
        if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == acId){ //Trigger.New[0].ValidationStatus == 'Validated' &&
            KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
            try{
                kmth.sendAcPartnerPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            try{
                kmth.sendAcInternalPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                
                System.debug('SEND FAIL ' + ex.getStackTraceString());
                
            }  
        }
        else if(Trigger.New[0].ValidationStatus == 'Validated' && Trigger.New[0].RecordTypeId == kaId ){//&& Trigger.New[0].PublishStatus == 'Online'
            KnowledgebaseMailTriggerHandler kmth = new KnowledgebaseMailTriggerHandler();
            try{
                kmth.sendKartPartnerPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            try{
                kmth.sendKartInternalPublicationNotification(Trigger.New[0]);
            }
            catch(Exception ex){
                
                System.debug('SEND FAIL ' + ex.getStackTraceString());
            }
            
        }
    }
}

trigger handler
 
public class KnowledgebaseMailTriggerHandler {
    
    public static Boolean isFirstTime = true;
    
    
    public void sendAcPartnerPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setCcAddresses(null);
        mail.setToAddresses(null);
        mail.setBccAddresses(getEmailAddresses('abc Partners'));
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='AC_AUTO_ArticlePublication'];
        
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null || article.Publication_Type__c != '') {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', host+'portalLightning/s/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        
        mail.setHtmlBody(htmlBody);
        System.debug('MAIL ' + mail);
        if (mail.getBccAddresses().size() != null && mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
                else{
                    User[] usr = [SELECT email FROM user WHERE Username like '%abilex%' Limit 1];
                    List<String> mailToAddresses = new List<String>();
                    for (User u : usr){
                        mailToAddresses.add(u.Email);
                    }
                    mail.setBccAddresses(mailToAddresses);
                    System.debug(usr);
                    System.debug(mailToAddresses);
                    System.debug('tesmtail '+ mail);
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
        
    }
    
    public void sendAcInternalPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setCcAddresses(null);
        mail.setToAddresses(null);
        mail.setBccAddresses(getEmailAddresses('abc Business'));
        mail.setTargetObjectId(userinfo.getUserId());
        //mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject  from EmailTemplate where Name='AC_AUTO_ArticlePublication_Internal'];
        
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        System.debug('MAIL ' + mail);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
        
    }
    
    public void sendKartPartnerPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //mail.setAddresses(false);
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setBccSender(true);
        //mail.setSenderDisplayName('Salesforce Support');
        mail.setUseSignature(false);
        mail.setBccAddresses(getEmailAddresses('xyz Partners'));
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='KA_AUTO_ArticlePublication'];
        mail.setTemplateId(et.id);
        
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', article.Link_to_Knowledge_Article__c);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
    }
    
    public void sendKartInternalPublicationNotification(Knowledge__kav article) {
        List<Messaging.SingleEmailMessage> mailingList = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTargetObjectId(userinfo.getUserId());
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);
        EmailTemplate et = [Select id, HtmlValue, Subject from EmailTemplate where Name='KA_AUTO_ArticlePublication_Internal'];
        mail.setBccAddresses(getEmailAddresses('xyz Business'));
        mail.setTemplateId(et.id);
        mail.setSubject(article.Title);
        String htmlBody = et.HtmlValue;
        htmlBody = htmlBody.replace('{!knowledge__kav.Article_Body__c}', article.Article_Body__c);
        
        if (article.Publication_Type__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', article.Publication_Type__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Type__c}', '');
        }
        if (article.Publication_Year__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', article.Publication_Year__c);
        } else {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Year__c}', '');
        }
        if (article.Publication_Number__c != null) {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', article.Publication_Number__c);
        }
        else
        {
            htmlBody = htmlBody.replace('{!knowledge__kav.Publication_Number__c}', '');
        }
        if(article.Link_to_Knowledge_Article__c != null){
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}','https://anydomain.force.com/portalLightning/s/article/'+article.id);
            //htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c', article.Link_to_Knowledge_Article__c);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article__c}', '');
        }
        if(article.Link_to_Knowledge_Article_Internal__c != null){
            
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', 'https://anydomain.lightning.force.com/lightning/r/Knowledge__kav/'+article.id);
        }
        else{
            htmlBody = htmlBody.replace('{!knowledge__kav.Link_to_Knowledge_Article_Internal__c}', '');
        }
        mail.setHtmlBody(htmlBody);
        if (mail.getBccAddresses().size() != null &&mail.getBccAddresses().size() > 0) {
            try {
                if (!System.Test.isRunningTest()) {
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                }
            } catch (Exception ex) {
                System.debug(ex.getStackTraceString());
            }
        }
    }
    
    public List<String> getEmailAddresses(String groupname) {
        
        List<String> idList = new List<String>();
        List<String> mailToAddresses = new List<String>();
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupname];
        for (GroupMember gm : g.groupMembers) {
            
			//System.debug('object is '+ gm.userOrGroupId.getsobjecttype());
            idList.add(gm.userOrGroupId);
        }
        
        User[] usr = [SELECT id, email FROM user WHERE id IN :idList];
        for (User u : usr) {
            if(UserInfo.getUserId() != u.id){
                mailToAddresses.add(u.email);
            }
        }
        Set<String> myset = new Set<String>();
        List<String> result = new List<String>();
        myset.addAll(mailToAddresses);
        result.addAll(myset);
        system.debug('MAIL RECIEPTS :: ' + result.size());
        system.debug('MAIL RECIEPTS :: ' + result);
        return result;
        
    }
}
Can someone give an advise

thanks!
 
Hello,

i need to get the picklist value for Field Reason of the Case-Objekt. Those vary depending on the record type. I found this on the net, but i am getting an Error 401

function:
@AuraEnabled
    public static List<reasonObject> getReasonRest(Id eId){
        System.debug(eId);
        Map<String,String> sessionAttributes = Auth.SessionManagement.getCurrentSession();
        System.debug('Session '+sessionAttributes.get('SessionId'));
        Id rType = [SELECT id, RecordTypeId FROM Case WHERE ID = :eId].RecordTypeId;
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        String host = System.Url.getSalesforceBaseURL().toExternalForm();
        String url = host + '/services/data/v43.0/ui-api/object-info/Case/picklist-values/'+rType+'/Reason';
        //String url = host + '/ui-api/object-info/Case/picklist-values/'+rType+'/Reason';
        System.debug(url);
        request.setEndpoint(url);
        request.setMethod('GET');  
        request.setHeader('Authorization', 'OAuth '+sessionAttributes.get('SessionId'));
        HttpResponse response;        
        response = http.send(request);
        System.debug('response ' + response);
        Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
        system.debug(meta);
		List<reasonObject> optionsList = new List<reasonObject>();
        //optionsList.add(new SelectOption('--None--', ''));
        if(meta.containsKey('values')){                                
                for(Object o: (List<Object> )meta.get('values')){
                    Map<String, object > temp = (Map<String, object>)o;        
                    System.debug((String)temp.get('label')+ ' ' + (String)temp.get('value'));
                    reasonObject ro = new reasonObject();
                    ro.label=(String)temp.get('label');
                    ro.value=(String)temp.get('value');
                    //optionsList.add(new SelectOption((String)temp.get('label'), (String)temp.get('value')));
                    optionsList.add(ro);
                }
            }
        return optionsList;
    }
Error
System.HttpResponse[Status=Unauthorized, StatusCode=401]
Any suggestions on this?
Is there a better solution for Lightning components?

regards
Peter
Hello,

i have another problem. I have an fileupload field. After finishing the upload the attachtmentid should be returned and a relation to a custom object dataset should be created. My problem is, that lightning scripts are async. So the dataset is created, while upload is still proceeding. How can i fullfill my requierement?

Helper.save() is the method to store the file and is called in a controller. I tried to store the attachementid in a helper variable, but didnt work either.
snippet of controller:
var fileobj = cmp.find("fileinput").get("v.files");
                            $A.getCallback(function () {
                                helper.save(cmp);
                                console.log("444", engine['Document_Id__c']);
                                console.log(engine);
                            });

                            var saveEngineObj = cmp.get("c.saveEngine");
                            engine['Document_Id__c'] = helper.attachId;
                            console.log("444", helper.attachId);
                            console.log("444", engine['Document_Id__c']);
                            console.log(engine);
                            $A.getCallback(function () {
                                saveEngineObj.setParams({saveEngineData: engine});
                                saveEngineObj.setCallback(this, function(responseEngine){
                                    //cmp.set("v.customSettings", responseEngine.getReturnValue());
                                    var engineData = responseEngine.getReturnValue();
                                    console.log('EE 4', engineData);
                                    
                                    $A.get('e.force:refreshView').fire();
                                    $A.get("e.force:closeQuickAction").fire()
                                    
                                });
                                
                                $A.enqueueAction(saveEngineObj);
                            });
                        }


Helper:
({
    fileId : '',
    attachId: '',
    save : function(component) {
        //var fileInput = component.find("fileinput").getElement();
        console.log('start save');
        var fileInput = component.find("fileinput").get("v.files");
        console.log(fileInput[0]);
        var file = fileInput[0];
        var MAX_FILE_SIZE = 750000;
        if (file.size > this.MAX_FILE_SIZE) {
            alert('File size cannot exceed ' + this.MAX_FILE_SIZE + ' bytes.\n' +
                  'Selected file size: ' + file.size);
            return;
        }
        
        var fr = new FileReader();
        
        var self = this;
        
        fr.onload = function() {
            var fileContents = fr.result;
            var base64Mark = 'base64,';
            var dataStart = fileContents.indexOf(base64Mark) + base64Mark.length;
            fileContents = fileContents.substring(dataStart);
            self.upload(component, file, fileContents);
        };
        
        fr.readAsDataURL(file);
        console.log("FILE 1", file)

    },
    upload: function(component, file, fileContents) {
        console.log("upload helper function");
        var action = component.get("c.saveTheFile"); 
        if(this.fileId == ''){
            this.fileId = component.get("v.recordId");
        }
        action.setParams({
            //parentId: component.get("v.recordId"),
            parentId: this.fileId,
            fileName: file.name,
            base64Data: encodeURIComponent(fileContents), 
            contentType: file.type
        });
        
        action.setCallback(this, function(a) {
            this.attachId = a.getReturnValue();
            
            console.log("att", a.getReturnValue());
        });
        
        
        $A.enqueueAction(action); 
        
    }

})


thanks for any help
Peter
 
Hello,

i have this upload field but drag'n'drop is not working.

            <div class="slds-form-element slds-size--1-of-2">
                <div class="slds-form-element__control">
                    <div class="slds-file-selector slds-file-selector_files">
                        <div class="slds-file-selector__dropzone slds-has-drag-over">
                            <input type="file" class="slds-file-selector__input slds-assistive-text" accept="image/png, .pdf" recordId="{!v.recordId}" id="fileinput" aria-labelledby="file-selector-primary-label file-selector-secondary-label" aura:id="fileinput"/>
                            <label class="slds-file-selector__body" for="fileinput" id="file-selector-secondary-label">
                                <span class="slds-file-selector__button slds-button slds-button_neutral">
                                   Select Files</span>
                                <span class="slds-file-selector__text slds-medium-show">Drop files here</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

I need a hint :)

thanks
Peter
Hello,

i have an related list on contacts for an custom object. Until Summer 18 new new button submitted the contact.id, but its submits the name. And spaces are filled with +. Like: 
Name: Peter Boelke
Submitted: Peter+Boelke

I have dialog which parses the url String, early i got the ID from it, now i need to change to work with the name. But because of the replacement it doesnt really work.
ich do "Peter+Boelke".replace('+', ' ')  its ok
but "Peter+Boelke+somewhat".replace('+', ' ') it returns Peter Boelke+somewhat

How can i solve my matter?
Part of my script
<script type="text/javascript">
        sforce.connection.sessionId = '{!$Api.Session_ID}';
    var conn = new jsforce.Connection({ accessToken: '{!$Api.Session_Id}' });
    var url_string = window.location.href;
    var url = new URL(url_string);
    console.log(url);
    var c = url.searchParams.get('href');
    var contact = window.location.search.substr(1).split('&')[1].split('=')[1].replace('+', ' ');
    console.log(contact);
    var queryCon = "SELECT Id, Name, Account.Name from Contact WHERE Name LIKE '" + contact + "'";
    var recordsCon = sforce.connection.query(queryCon).getArray('records');
    console.log(recordsCon[0].Id);
    var query = "SELECT Warengruppe__c, Kontakt__c from Warengruppen_Zuordnung__c WHERE Kontakt__c = '" + recordsCon[0].Id + "'"; 
    var records = sforce.connection.query(query).getArray('records');
    var selKeys;
    var unselKeys = [];
    var path = '/services/data/v41.0';
    var queryCon = "SELECT Name, Account.Name from Contact WHERE Name = '" + contact + "'";

</>

 
Hello,
i want to use tabset-element (sample code from salesforce), but doesnt seem to have a default style. How can i add styling to this?

 
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <lightning:tabset variant="scoped">
        <lightning:tab label="Item One">
            Sample Content One
        </lightning:tab>
        <lightning:tab label="Item Two">
            Sample Content Two
        </lightning:tab>
    </lightning:tabset>
    
</aura:component>

Result:


User-added image
thanks
Peter
Hello,

i have created lighting quickaction. Can anyone tell me how i can change the title/header of the appearing modal? I need to have it different from the label i have specified for the button.

thanks
Peter
Hello,

i have a problem with my lightning component. Yesterday all input element had shown up. But today they dont. HTML is generated correctly.

What is the problem?
 
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,lightning:actionOverride,force:lightningQuickActionWithoutHeader" access="global" controller="CtrlCreateAttendeeContact">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="contact" type="Contact" 
                    default="{ 'sobjectType': 'Contact' }"/>
    <aura:attribute name="registrationId" type="Id" />
    <div role="dialog" tabindex="-1" aria-labelledby="header99" class="slds-modal">
            <div class="slds-modal__container">
                    <ui:outputText class="slds-hide" aura:id="attendeeRecordTypeId" value="{!v.contact.RecordTypeId}"/>
                    <ui:outputText class="slds-hide" aura:id="eventregistrationId" value="{!v.registrationId}"/>
                    <div class="slds-select_container">
                        <ui:inputSelect aura:id="conSalutation" class="slds-select"  change="{!c.onPicklistChange}" value="{!v.contact.Salutation}"/>
                    </div>
                    <lightning:input value="{!v.contact.FirstName}" name="FirstName" label="Firstname" required="true"/>
                    <lightning:input value="{!v.contact.LastName}" name="LastName" label="Lastname" required="true"/>
                    <lightning:input type="email" value="{!v.contact.Email}" label="email" required="true"/>
                    <div class="slds-modal__footer">
                        <lightning:button class="slds-button slds-button--brand" label="save" onclick="{!c.createContact}"/>
                    </div>
        </div>
    </div>
</aura:component>

thanks for any advise.
Peter

 
Hello,

 i am getting an Error "Too many SOQL queries: 101".
 
public class WarengruppenZuordnung {
    /********************* Properties used by getRootNodeOfUserTree function - starts **********************/
    // map to hold roles with Id as the key
    private static Map <Id, Warengruppen_Struktur__c> warengruppeMap;
    
    // map to hold child roles with parentRoleId as the key
    private static Map <Id, List<Warengruppen_Struktur__c>> parentWarengruppeMap;
    
    // List holds all subordinates
    private static List<Warengruppen_Struktur__c> allProducts {get; set;}
    
    // Global JSON generator
    private static JSONGenerator gen {get; set;}
    public static String folderId{get;set;}
    public static String folderName{get;set;}
    public static String endpointId{get;set;}
    /********************* Properties used by getRootNodeOfUserTree function - ends **********************/
    
    
    /********************* Properties used by getSObjectTypeById function - starts ********************* */
    // map to hold global describe data
    private static Map<String,Schema.SObjectType> gd;
    
    // map to store objects and their prefixes
    private static Map<String, String> keyPrefixMap;
    
    // to hold set of all sObject prefixes
    private static Set<String> keyPrefixSet;
    /********************* Properties used by getSObjectTypeById function - ends **********************/
    
    public static String redirUrl{get;set;}
    public String contactId {get;set;}
    
    /* // initialize helper data */ 
    static {
        // initialize helper data for getSObjectTypeById function
        Map<String, String> UrlParameterMap = ApexPages.currentPage().getParameters();
        //redirUrl = getRedirUrl();
        gen = JSON.createGenerator(true);
        init1();
        gen = JSON.createGenerator(true);
        // initialize helper data for getRootNodeOfUserTree function
        init2();
    }
    
    /* // init1 starts <to initialise helper data> */
    private static void init1() {
        // get all objects from the org
        gd = Schema.getGlobalDescribe();
        // to store objects and their prefixes
        keyPrefixMap = new Map<String, String>{};
            
            //get the object prefix in IDs
            keyPrefixSet = gd.keySet();
        
        // fill up the prefixes map
        for(String sObj : keyPrefixSet) {
            Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
            String tempName = r.getName();
            String tempPrefix = r.getKeyPrefix();
            keyPrefixMap.put(tempPrefix, tempName);
        }
    }
    /* // init1 ends */
    
    /* // init2 starts <to initialise helper data> */
    private static void init2() {
        
        // Create a blank list
        allProducts = new List<Warengruppen_Struktur__c>();

        for(AggregateResult wsc : [SELECT Name, RecordTypeId, RecordType.DeveloperName FROM Warengruppen_Struktur__c GROUP BY RecordTypeId, RecordType.DeveloperName, Name ORDER BY Name]) {
            if(String.valueOf(wsc.get('DeveloperName')).contains('Ordner')){
                folderId = String.valueOf(wsc.get('RecordTypeId'));
                folderName = String.valueOf(wsc.get('Name'));
            }
            if(String.valueOf(wsc.get('DeveloperName')).contains('Endpunkt')){
                endpointId = String.valueOf(wsc.get('RecordTypeId'));
                
            }
        }
        
        warengruppeMap = new Map<Id, Warengruppen_Struktur__c>([select Id, Name, Parent_Warengruppe__c, RecordTypeId from Warengruppen_Struktur__c order by Name]);
        // populate parent role - child roles map
        parentWarengruppeMap = new Map <Id, List<Warengruppen_Struktur__c>>();        
        for (Warengruppen_Struktur__c r : warengruppeMap.values()) {
            List<Warengruppen_Struktur__c> tempList;
            if (!parentWarengruppeMap.containsKey(r.Parent_Warengruppe__c)){
                tempList = new List<Warengruppen_Struktur__c>();
                tempList.Add(r);
                parentWarengruppeMap.put(r.Parent_Warengruppe__c, tempList);
            }
            else {
                tempList = (List<Warengruppen_Struktur__c>)parentWarengruppeMap.get(r.Parent_Warengruppe__c);
                tempList.add(r);
                parentWarengruppeMap.put(r.Parent_Warengruppe__c, tempList);
            }
        }
    } 
    /* // init2 ends */
    
    /* // public method to get the starting node of the RoleTree along with user list */
    public static RoleNodeWrapper getRootNodeOfUserTree (Id userOrRoleId) {
        return createNode(userOrRoleId);
    }
    
    /* // createNode starts */
    private static RoleNodeWrapper createNode(Id objId) {
        RoleNodeWrapper n = new RoleNodeWrapper();
        Id roleId;
        if (isRole(objId)) {
            roleId = objId;
            if (!(warengruppeMap.get(objId).Parent_Warengruppe__c == null)) {
                List<Warengruppen_Struktur__c> tempFolderList = new List<Warengruppen_Struktur__c>();
                Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId, RecordType.DeveloperName from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
                tempFolderList.add(tempFolder);
                if(tempFolderList.size()== 1){
                    if(tempFolderList[0].RecordType.DeveloperName.contains('Ordner')){
                        n.hasFolders = false;
                        n.myFolders = tempFolderList;
                        n.isLeafNode = false;
                        allProducts.addAll(n.myFolders);
                    }
                    else{
                        n.hasFolders = false;
                        n.myFolders = tempFolderList;
                        n.isLeafNode = true;
                        allProducts.addAll(n.myFolders);
                    }
                }
            }
        }
        else {
            List<Warengruppen_Struktur__c> tempFolderList = new List<Warengruppen_Struktur__c>();
            Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
            tempFolderList.add(tempFolder);
            n.myFolders = tempFolderList;
            roleId = tempFolder.Parent_Warengruppe__c;
        }
        n.myRoleId = roleId;
        n.myRoleName = warengruppeMap.get(roleId).Name;
        n.myParentRoleId = warengruppeMap.get(roleId).Parent_Warengruppe__c;
        n.RecordTypeId = warengruppeMap.get(roleId).RecordTypeId;
        if (parentWarengruppeMap.containsKey(roleId)){
            n.hasChildren = true;
            n.isLeafNode = false;
            List<RoleNodeWrapper> lst = new List<RoleNodeWrapper>();
            for (Warengruppen_Struktur__c r : parentWarengruppeMap.get(roleId)) {
                lst.add(createNode(r.Id));
            }           
            n.myChildNodes = lst;
        }
        else {
            n.isLeafNode = true;
            n.hasChildren = false;
            
        }
        return n;
    }
    
    public static List<Warengruppen_Struktur__c> getAllProducts(Id warengruppeId){
        createNode(warengruppeId);
        return allProducts;
    }
    
    public static String getTreeJSON(Id userOrRoleId) {
        gen = JSON.createGenerator(true);
        RoleNodeWrapper node = createNode(userOrRoleId);
        gen.writeStartArray();
        convertNodeToJSON(node);
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    public static String getTreeJSON() {
        gen = JSON.createGenerator(true);
        List<Warengruppen_Struktur__c> wRoots = [Select Id, Name, RecordTypeId From Warengruppen_Struktur__c Where Parent_Warengruppe__c = '' ORDER BY Name];
        gen.writeStartArray();
        for(Warengruppen_Struktur__c ws : wRoots){
            RoleNodeWrapper node = createNode(ws.Id);
            convertNodeToJSON(node);
        }
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    private static void convertNodeToJSON(RoleNodeWrapper objRNW){
        gen.writeStartObject();
        gen.writeStringField('title', objRNW.myRoleName);
        gen.writeStringField('key', objRNW.myRoleId);
        gen.writeStringField('RecordTypeID', String.valueOf(objRNW.RecordTypeId));
        gen.writeBooleanField('unselectable', false);
        gen.writeBooleanField('expand', true);
        gen.writeBooleanField('isFolder', true);
        if (objRNW.hasFolders || objRNW.hasChildren)
        {
            gen.writeFieldName('children');
            gen.writeStartArray();
            if (objRNW.hasFolders)
            {
                for (Warengruppen_Struktur__c u : objRNW.myFolders)
                {
                    gen.writeStartObject();
                    gen.writeStringField('title', u.Name);
                    gen.writeStringField('key', u.Id);
                    gen.writeStringField('RecordTypeID', String.valueOf(objRNW.RecordTypeId));
                    gen.writeBooleanField('isFolder', false);
                    gen.WriteEndObject();
                }
            }
            if (objRNW.hasChildren)
            {
                
                for (RoleNodeWrapper r : objRNW.myChildNodes)
                    
                {
                    convertNodeToJSON(r);
                    
                }
            }
            gen.writeEndArray();
        }
        gen.writeEndObject();
    }
    
    /* // general utility function to get the SObjectType of the Id passed as the argument, to be used in conjunction with */ 
    public static String getSObjectTypeById(Id objectId) {
        String tPrefix = objectId;
        tPrefix = tPrefix.subString(0,3);
        String objectType = keyPrefixMap.get(tPrefix);
        return objectType;
    }
    /* // utility function getSObjectTypeById ends */
    
    /* // check the object type of objId using the utility function getSObjectTypeById and return 'true' if it's of Role type */
    public static Boolean isRole (Id objId) {
        if (getSObjectTypeById(objId) == String.valueOf(Warengruppen_Struktur__c.sObjectType)) {
            return true;
        }
        else if (getSObjectTypeById(objId) != String.valueOf(Warengruppen_Struktur__c.sObjectType)) {
            return false;
        } 
        return false;
    }
    /* // isRole ends */
    
    public class RoleNodeWrapper {
        
        // Role info properties - begin
        public String myRoleName {get; set;}
        
        public Id myRoleId {get; set;}
        public Id RecordTypeId {get; set;}
        public String myParentRoleId {get; set;}
        // Role info properties - end
        
        
        // Node children identifier properties - begin
        public Boolean hasChildren {get; set;}
        
        public Boolean isLeafNode {get; set;}
        
        public Boolean hasFolders {get; set;}
        // Node children identifier properties - end
        
        
        // Node children properties - begin
        public List<Warengruppen_Struktur__c> myFolders {get; set;}
        
        public List<RoleNodeWrapper> myChildNodes {get; set;}
        // Node children properties - end   
        
        public RoleNodeWrapper(){
            hasFolders = false;
            hasChildren = false;
        }
    }
    
    public static String getRedirUrl(){
        Map<String, String> UrlParameterMap = ApexPages.currentPage().getParameters();
        redirUrl = UrlParameterMap.values()[1];
        return redirUrl;        
    }
    
    public String getContactId()
    {
        return Apexpages.currentPage().getParameters().get('id');
        
    }

}

This Error occur in this line
 
Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId, RecordType.DeveloperName from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
How to change this to get it working?

Any Ideas :(?

Thanks
Peter