+ Start a Discussion
Dippan PatelDippan Patel 

Error while changing the page layout using Post install script while the package is upgraded?

global without sharing class addSectionScript implements InstallHandler {
	global void onInstall(InstallContext context) {
		
		try{
	        if(context.isUpgrade() || context.isPush()){
	        	System.debug(LoggingLevel.ERROR,'Instllation is Upgrade or Push. Adding secion to layout.');
	        	
	            //Add Section Through the Metadata API
	            List<String> componentNameList = new List<String>{'Custom_Object_Analysis__c-Custom_Object Analysis Layout'};
		        List<Metadata.Metadata> components = Metadata.Operations.retrieve(Metadata.MetadataType.Layout, componentNameList);     
	            Metadata.Layout la =(Metadata.Layout) components.get(0); 

	            // Create Section
	            Metadata.LayoutSection sec = new Metadata.LayoutSection();
	            sec.customLabel = true;
	            sec.detailHeading = true;
	            sec.editHeading = true;
	            sec.label = 'RingLead Data Quality Score';
	            sec.style = metadata.LayoutSectionStyle.OneColumn;

	            // Create Layout Field
	            Metadata.LayoutItem layoutField = new Metadata.LayoutItem();
	            layoutField.page_x = 'Custompage';
	            layoutField.height = 550;
	            layoutField.width = '100%';

	            // Add Layout Field and Column to Section
	            Metadata.LayoutColumn col1 = new Metadata.LayoutColumn();
	            col1.layoutItems.add(layoutField);
	            sec.layoutColumns.add(col1);
	            la.layoutSections.add(sec);

	            // Deploy it to Layout of User.
	            Metadata.DeployContainer dc = new Metadata.DeployContainer();
	            addSectionScriptCallback callback = new addSectionScriptCallback();
	            dc.addMetadata(la);
	            if(!Test.isRunningTest()){
	            	
	            	Id jobid = Metadata.Operations.enqueueDeployment(dc,callback);
	            	System.debug(LoggingLevel.ERROR,'id is:'+jobid);
	            	
	        	}
	        }
    	} catch(Exception e){
    		System.debug(LoggingLevel.ERROR,'Error in Post Script.');
    		sendTestEmail('Error in post install script.' + e.getStackTraceString());
    	}
    }

    public void sendTestEmail(String body){
        
    }
}

I am trying to change the page layout of the custom object when a user upgrades the package using Metadata. 

I am using this code to upgrade the page layout. But when tried to enque the deployment it gives this error. 

Fatal Error
INSUFFICIENT_ACCESS: insufficient access rights on cross-reference id