• Jack Yu@Tokyo
  • NEWBIE
  • 80 Points
  • Member since 2016

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 5
    Likes Given
  • 0
    Questions
  • 25
    Replies
Hi all,

This is my code:

//If Parent record is undeleted , it's child records should also  be undeleted.

trigger Trg9 on Student__c (after undelete) {
     List<id> StdId=new List<id>();
    for(Student__c s: trigger.new){
        StdId.add(s.id);
  
        }
    list<StudentChild__c> childRecords=[select id,College_of_Student__c,Name from  StudentChild__c where College_of_Student__c in :StdId all rows];
    undelete childRecords;
}

I am getting Error when Undeleing parent record:

User-added image

Please can any one help me out , how to resolve this.
Thanks In Advance.
I have an AfterUpdate user trigger.  The test class is below but I keep getting the following error at the UPDATE line...
System.DmlException: Update failed. First exception on row 0 with id 00560000001A1zeAAC; first error: INSUFFICIENT_ACCESS_OR_READONLY, Cannot insert a user with this profile: []

I have tried without runAS and with runAs and both give the same error!  I need to create an active user then I need to deactive that user which would fire my trigger that is the business requirement.

Any ideas?  I thought I found and Idea that asks to allow updating user records in a test (ones that are created by the test itself).  Is there a way to resolve this issue? Thanks in advance.

@isTest
public class SM_User_Trigger_Test {
    @testSetup static void createUsers() {
        Profile pf= [Select Id from profile where Name='Standard User'];
        List<User> UserList = new List<User>();
        User user = new User();
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User u = new User(firstname = 'Test1', 
                         lastName = 'Tester', 
                         email = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         Username = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         isActive = true,
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        UserList.add(u);
        insert UserList;        
    }    

    static testMethod void testCase1() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
         User u1 = new User(Alias = 'newUser', Email='newuser@testorg.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com');

          System.runAs(u1) {
            User User =  [SELECT id, isActive FROM User LIMIT 1];
            System.debug('User: ' + user);
            User.isActive = false;        
            test.startTest();
            Update User;
            test.stopTest();
        }
    }
}
trigger casetotal on Case (after insert) {
        list<caseshare>share=new list<caseshare>();
    user u=[select id,name from user where name =:'karthik'];
    for(case c:trigger.new){
if(c.priority=='high'&&c.origin=='email'){
            caseshare cs=new caseshare();
                cs.caseid=c.id;
                cs.UserOrGroupId=u.id;
                cs.RowCause='manual';
                cs.CaseAccessLevel='all';
                share.add(cs);  
            }
}
insert share;
}  



could you correct this code because I am getting the following errors
field is not writable caseid;
field is not writable userorgroupid;
field is not writable caseaccesslevel;
field is not writable rowcause;
 
I wrote account handler class which will update contact phone number,other street, description by changing the account phone number,billing street, description.

public class Accounttriggerhandlert {
public static void afterupdate(map<id,account>newmap){
        list<contact>cons=new list<contact>();
        map<id,account>accsmap=new map<id,account>();
        list<account>acclist=[select id,phone,billingstreet,description, (select id,phone,description,otherstreet from contacts)
                          from account where id in:accsmap.keyset()];
        for(account a:acclist){
            for(contact c:a.contacts){
                c.phone=a.Phone;
                c.description=a.description;
                c.otherstreet=a.billingstreet;
                cons.add(c);
            }
        }
        update cons;
    }
}



trigger:

trigger acctottrigger on Account (after update) {
accounttriggerhandlert.afterupdate(trigger.newmap);
}


could you correct this code.
Hi all,

This is my code:

//If Parent record is undeleted , it's child records should also  be undeleted.

trigger Trg9 on Student__c (after undelete) {
     List<id> StdId=new List<id>();
    for(Student__c s: trigger.new){
        StdId.add(s.id);
  
        }
    list<StudentChild__c> childRecords=[select id,College_of_Student__c,Name from  StudentChild__c where College_of_Student__c in :StdId all rows];
    undelete childRecords;
}

I am getting Error when Undeleing parent record:

User-added image

Please can any one help me out , how to resolve this.
Thanks In Advance.
Hi,

I have a trigger for Round Robin and working as expected, now there is a request to handle if Lead country is "India" then it should route to a specific Queue. This request should be addressed without code changes as it is a manged package but via Custom settings. 

I am very new to Coding. please suggest
参照関係で結ばれているオブジェクトをワークフローで更新したいのですが、可能でしょうか。
親:カスタムオブジェクトAと子:カスタムオブジェクトBについて、
カスタムオブジェクトBの項目1(数値型)の値が変更されたら、カスタムオブジェクトAの項目2(チェックボックス型)をチェックなしに更新したいです。

項目自動更新では、主従関係の項目しか更新できず、上手く行う方法がないかを考えています。
プロセスビルダーやVisualWorkフローは、ガバナ制限を考慮する必要があるため、極力使用したくないです。
もし何か良い案がありましたら、ご教示いただけると助かります。
よろしくお願いします。
I have a controller method which returns a list based on a dynamic SOQL query. This method is called by apex:repeat, which iterates over the returned list and displays checkboxes accordingly. For each apex:repeat, I want to pass a different String keyword which is used for the SOQL query. Is there a way how this is possible. 

Can anyone suggest a solution?
Apex Trigger : 

trigger preventChangeOfAccountName on Order (before insert) {
    
    Map<String, String> mapSourceOrderIdToAccount = new Map<String, String>();
    
Profile p = [SELECT Id, Name FROM Profile WHERE Name LIKE 'Thailand%' OR Name LIKE 'System Administrator' LIMIT 1];
if(p.Id != UserInfo.getProfileId())
return;
    
for (Order obj : trigger.new){

        mapSourceOrderIdToAccount.put(obj.getCloneSourceId(), null);

    }

    for(Order objOrder : [Select id, AccountId from Order where id in : mapSourceOrderIdToAccount.keySet() Limit 5000]){

        mapSourceOrderIdToAccount.put(objOrder.id, objOrder.AccountId);

    }

     

    for (Order o : trigger.new){

       If  (o.isClone() && mapSourceOrderIdToAccount.get(o.getCloneSourceId()) <> o.AccountId)

       {

           o.addError('Account Name for Cloned records cant be changed');

       }

    }

}


Test Class : 

@isTest
public class preventChangeOfAccountNameTestClass {
    

    static testmethod void profileDetails(){
        
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        
            User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
        
    }
    
    static testmethod void preventAccNameChange(){  
        
        

Account acc = new Account();
        acc.name='TestAccount1';
        insert acc;
Order ord = new Order();
           ord.AccountId = acc.Id;
           ord.EffectiveDate = System.Today();
          ord.EndDate = System.Today()+5;
        ord.Status = 'NA';
        ord.Offer_Status__c = 'Open';
       insert ord;
      
        try{
            
            Account objNewAc = new Account();
            objNewAc.Name = 'Test account record';
            insert objNewAc;

            Order objNewOrder = ord.clone(false, true);
            objNewOrder.AccountId= objNewAc.Id;
            insert objNewOrder;

        }
        catch(DMLexception e){
           Boolean expectedExceptionThrown =  e.getMessage().contains('Account Name for Cloned records cant be changed') ? true : false;
           System.AssertEquals(expectedExceptionThrown, true);
    }
}
}


However, It covers only 36% code.

 
I have an AfterUpdate user trigger.  The test class is below but I keep getting the following error at the UPDATE line...
System.DmlException: Update failed. First exception on row 0 with id 00560000001A1zeAAC; first error: INSUFFICIENT_ACCESS_OR_READONLY, Cannot insert a user with this profile: []

I have tried without runAS and with runAs and both give the same error!  I need to create an active user then I need to deactive that user which would fire my trigger that is the business requirement.

Any ideas?  I thought I found and Idea that asks to allow updating user records in a test (ones that are created by the test itself).  Is there a way to resolve this issue? Thanks in advance.

@isTest
public class SM_User_Trigger_Test {
    @testSetup static void createUsers() {
        Profile pf= [Select Id from profile where Name='Standard User'];
        List<User> UserList = new List<User>();
        User user = new User();
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User u = new User(firstname = 'Test1', 
                         lastName = 'Tester', 
                         email = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         Username = 'test1.tester' + '@somecompany' + orgId + '.org', 
                         isActive = true,
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        UserList.add(u);
        insert UserList;        
    }    

    static testMethod void testCase1() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
         User u1 = new User(Alias = 'newUser', Email='newuser@testorg.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com');

          System.runAs(u1) {
            User User =  [SELECT id, isActive FROM User LIMIT 1];
            System.debug('User: ' + user);
            User.isActive = false;        
            test.startTest();
            Update User;
            test.stopTest();
        }
    }
}
Hi everyone, 

I have multiple simple Process Builders that are failing (sometimes). The error in the emails says:
 
Error element myRule_1_A1 (FlowRecordUpdate).
This error occurred when the flow tried to update records: Too many SOQL queries: 101. For details, see API Exceptions.

I originally thought that it could be caused by one of 2 Apex Triggers, or 3 Classes that were built by a contractor before I started at the company. I have de-activated and commented out the triggers, and commented out the Classes, because the function they performed is less important than these processes builders working correctly.  The errors are still happening with my Process Builder processes. This leads me to believe it may be Apex from a managed package?

We have many managed packages. I found an article that we could get debug logs enabled for the managed package with their permission, but does anyone have any suggestion on how I could pinpoint which one may be the problem? Or do I need to contact every managed package provider and have them submit a case on my behalf to enable the logs? (That is what SFDC support told me to have them do). 

Second, even if those logs are enabled, I don't know if I'll be able to figure out the debug logs on my own. I have only done the "Developer Console Basics" trailhead module. Any suggestions/ help would be appreciated. 
I created a QUick action which open the Visualforce page. On opening that dialog, I want to perform some operation and, close the dialog. But, I'm unable to close the dialog.  Here is my code:
<apex:page standardController="Order__c">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="/resource/jquery"></script>
  <script type="text/javascript">
    Sfdc.onReady(function() {
        alert();
        $('.uiModal').style.display = 'none';
    });
  </script>
  <p>Uncancelling...</p>
</apex:page>

If I execute $('.uiModal').style.display = 'none'; from browser console, it is closing dilog, but not from the visualforce page. Please help me.
Time field data type is Time
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

try{
    var accToUpdate = new sforce.SObject("Account");

    accToUpdate.Id = "{!Account.Id}";
    var today = new Date();

   function fixTime(time){
       if(time < 10) {time = "0" + time};
         return time;
    }

    function fixDate(date){
          var Month = fixTime(date.getMonth() + 1);
          var Day = fixTime(date.getDate());
          var UTC = date.toUTCString();
          var Time = UTC.substring(UTC.indexOf(':')-2, UTC.indexOf(':')+6);
          var Minutes = fixTime(date.getMinutes());
          var Seconds = fixTime(date.getSeconds());
          return date.getHours() + ":"+date.getMinutes();
       }
    accToUpdate.Current_Time__c= fixDate(today);
    
    var result = 
        sforce.connection.update([accToUpdate]);

    if(result[0].success == "true"){
        location.reload();
    }
    else{
        alert("An Error has Occurred. Error: " + 
            result[0].errors.message
        );
    }
}
catch(e){
    alert(
        "An Error has Occurred. Error: " + 
        e
    );
}
hi guys,

I will try getting Inactive roles using soql .I unable to do this.If you know kindly share to me .


Thanks ,
Somu
Hi All,

I need to get the account Id and return the same to Visualforce page. Below is the method I am using.

I am getting an empty array list instead of parrticular Account ID. Have provided the output below for reference.

Any help is appreciated.

Code:

 public List<Account> getaccount() {
        account = [SELECT id FROM Account where Name = :contactName Limit 1];
        return account;
                                    }

Output:

https://XXXXXX.my.salesforce.com/[]?IDforaccountname=ZZZZ
  • April 24, 2018
  • Like
  • 1
Hi Guys,

this is my code :
public class CreateMultiExtraBoost {

	public List<cBoost> boostList {get; set;}
    Integer listSize {get;set;}
    public Id opportunityId {get;set;}
    public ID finalBoostId {get; set;}
        
    // Constructor 
    public CreateMultiExtraBoost (){
    	opportunityId =  ApexPages.currentPage().getparameters().get('oppId');
    }

	//Methode
	public List<cBoost> getBoosts() {
		if(boostList == null) {
			boostList = new List<cBoost>();
			for(FinalBoost__c c: [select Id, Name from FinalBoost__c ]) {
				boostList.add(new cBoost(c));
			}
		}
		return boostList;
	}

	public PageReference save() {
 
		List<FinalBoost__c> selectedContacts = new List <FinalBoost__c>();
        List<BoostOpp__c> boostItems = new List <BoostOpp__c>(); 
        pagereference oppPage = new pagereference('/' + opportunityId);

		for(cBoost cCon: getBoosts ()) {
			if(cCon.selected == true ) {
				selectedContacts.add(cCon.con);
			}
		}

		System.debug('These are the selected ...');
		for(FinalBoost__c con: selectedContacts) {
			system.debug(con);
		}
        
        for (FinalBoost__c con: selectedContacts) {
            	boostItems.add(new BoostOpp__c());
            	finalBoostId = con.Id;
            
            		for(BoostOpp__c boostIteminList : boostItems) {
                        boostIteminList.Opportunity__c = opportunityId;
                        boostIteminList.FinalBoost__c = finalBoostId;
       	 }
       }
        insert boostItems;
        return oppPage;
	}
    
   
   // WrapperClass
	public class cBoost {
		public FinalBoost__c con {get; set;}
		public Boolean selected {get; set;}

		// Constructor 
        public cBoost(FinalBoost__c c) {
			con = c;
			selected = false;
		}
	}
}

A visualforcepage shows the table of FinalBoost records. I can select records and use them in the save methode.  The BoostOpp__c object is a junction object. It is related to the opportunity and the FinalBoost Object. 

In my loop, i want to create for each selected record one child record and assign the parent id (FinalBoost) to the masterDetail field. At the moment, it creates for each selection one record but allways with the same finalBoostId.  Is there a simple solution for that ? 


Cheers Sandra
Hi Guys,
I have the following code and want a test method to cover the for loop.Please give the test method so as to cover the for loop

Public class CreateDummyAccount{

Public static void dummyMethod(List<Account> accList){
try{
    if(accList != NULL && !accList.isEmpty()){
        List<Contact> conList = new List<Contact>();
        for(Account acc : accList){
        conList.add(new  Contact(LastName = 'Larry'))
        }
        
        insert conList;
    }
    
    }

}

}


Thanks,
Abhilash
I created a QUick action which open the Visualforce page. On opening that dialog, I want to perform some operation and, close the dialog. But, I'm unable to close the dialog.  Here is my code:
<apex:page standardController="Order__c">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="/resource/jquery"></script>
  <script type="text/javascript">
    Sfdc.onReady(function() {
        alert();
        $('.uiModal').style.display = 'none';
    });
  </script>
  <p>Uncancelling...</p>
</apex:page>

If I execute $('.uiModal').style.display = 'none'; from browser console, it is closing dilog, but not from the visualforce page. Please help me.
Hi All

I would like to get backup of Eventlog.
There are many way,however i would like to do on command prompt.

I think to use REST API (using cURL).
but i can't conect SFDC command prompt.

please help me, how do you get backup of Eventlog