I need to add an statement into this custom button so that it only runs if it meets a certain, how would I do this?  The statement essentially needs to say if the logged in user is equal to the R_D_Service_Owner__c or the project_owner__c then it can run, or if the logged in user profile equals 'system administrator' it can run, or if the logged in user equals a specific user id, or another specific user id it can run.  {!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")}    var proName = '{!$Profile.Name}';     var userId = '{!$User.Id}';    var proOwnerId = '{!Product2.Project_Owner__c}';    var serOwnerId = '{!Product2.R_D_Service_Owner__c}';  if(proName.includes("Administrator")||proOwnerId==userId||serOwnerId==userId){  var r = new sforce.SObject("Product2"); r.id = "{!Product2.Id}"; r.Convert_to_Service_Catalogue__c = true; result = sforce.connection.update([r]);   if ( result[0].getBoolean( "success" ) ) {  window.location.reload(); // refresh page  } else {  var errors = result[0].errors; var errorMessages = "The Lifecycle Status must be Beta, and the following fields must be populated; Name, Unique ID, Jisc Directorate, Include in    Dashboard, Service/Project Owner or else this record won't be converted to a     Service Catalogue record";  for ( var i = 0; i &lt; errors.length; i++ ) { errorMessages += errors[i].message + '\n'; }  alert( errorMessages ); // display all validation errors  } } else{     alert("You are not eligible for this operation!");  }
120976
I have a custom button on the Product object that I only want to run if the current logged in user is either the record owner, a specific user id, or a sys admin profile. How would I do that? Below is my current code  {!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")}  var r = new sforce.SObject("Product2");  r.id = "{!Product2.Id}";  r.Convert_to_Service_Catalogue__c = true;  result = sforce.connection.update([r]);  window.location.reload();  if ( result[0].getBoolean( "success" ) ) {      location.reload( true ); // refresh page  } else {      var errors = result[0].errors;     var errorMessages = "The Lifecycle Status must be Beta, and the following fields must be populated; Name, Unique ID, Jisc Directorate, Include in Dashboard, Service/Project Owner or else this record won't be converted to a Service Catalogue record";      for ( var i = 0; i &lt; errors.length; i++ ) {         errorMessages += errors[i].message + '\n';     }      alert( errorMessages ); // display all validation errors  }
6335
I have situation here, where I want to lock all the fields and buttons on a quote__c (custom object) where the status of the quote is changed to 'Sent' so that nothing can be editable on the quote.  Any ideas how to do this?
323
I'm having issues with creating a pretty simple test Utility Class. I want to create two records: an account and a related child contact. The error I see in the developer console is:     Variable does not exist: a.ID   My code, based on the Salesforce Apex Workbook, is as follows. I've played around with various things, but it's not working. Where am I going wrong? Thanks in advance.  @isTest public class AccountSaveTestSuite {      public static Account createOneAccount(){           Account testAccount = createAcct('ABC Computing inc.');              Contact testContact = createContact();          return testAccount;             }      // Helper methods //     //        private static Account createAcct(string accountName) {          Account a = new Account(             Name=accountName);         insert a;         return a;     }      private static Contact createContact(){         Contact c = new Contact (             FirstName = 'Jane'              , LastName = 'Smith'             , Account = a.ID); // *** Error is here ***         insert c;         return c;      }  }
99589
I am stuck on the prevent SOQL injection trailhead, where I am looking to determine which portions of the code I would need to invoke escapeSingleQuotes or whitelist to enable. I've made several attempts at investigation to little avail. I have appended my code are there any steps I would need to take. My goal is to assess the code to see how it works and what I would need to do.  public class Prevent_SOQL_Injection_Challenge {  public string textOne {get; set;} public string textTwo {get; set;} public string comparator {get; set;} public string numberOne {get; set;}  public List&lt;Supply__c&gt; whereclause_records {get; set;}   public PageReference stringSearchOne(){     string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';     string whereClause = '';      if(textOne != null &amp;&amp; textOne!=''){             whereClause += 'name like  \'%'+string.escapeSingleQuotes(textOne)+'%\' ';     }      if(whereClause != ''){         whereclause_records = database.query(query+' where '+whereClause+' Limit 10');     }      return null; }   public PageReference stringSearchTwo(){     string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';     string whereClause = '';      if(textTwo != null &amp;&amp; textTwo!=''){             whereClause += 'Storage_Location__r.name like  \'%'+string.escapeSingleQuotes(textTwo)+'%\' ';     }      if(whereClause != ''){         whereclause_records = database.query(query+' where '+whereClause+' Limit 10');     }      return null; }   public PageReference numberSearchOne(){     string query = 'SELECT Id,Name,Quantity__c,Storage_Location__c,Storage_Location__r.Castle__c,Type__c FROM Supply__c';     string whereClause = '';      if(numberOne != null &amp;&amp; comparator != null){         whereClause += 'Quantity__c '+comparator+' '+string.ValueOf(numberOne)+' ';     }      if(whereClause != ''){         whereclause_records = database.query(query+' where '+string.ValueOf(whereClause)+' Limit 10');     }      return null; } }
58931
I am trying to create a hook that when a user login, it check the user role.. if the user role is jsa_contributor then it redirect into specific page. but it seems my code didn't work.  This is the code..  function my_login_redirect($login) {     $data_login = get_option('axl_jsa_login_wid_setup');     $redirect_page = $data_login[0];      $logout_redirect_page = $data_login[1];      $current_user = get_user_by('login',$login);     if($current_user-&gt;roles == 'jsa_contributor'){         wp_redirect(get_permalink($redirect_page)); /* Redirect browser */         exit();     } }  add_action('wp_login', 'my_login_redirect', 99);   does anyone have an idea about this? thanks in advance...
60861
I have an AJAX button that should update form fields according to data already provided by user:   'ajax_button' =&gt; array(     '#type' =&gt; 'button',     '#value' =&gt; t("Scan for tags"),     '#ajax' =&gt; array(       'callback' =&gt; 'ajax_tag',       'wrapper' =&gt; 'dynamic-tags-fieldset',       'method' =&gt; 'replace',       'event' =&gt; 'click',       'prevent' =&gt; 'submit click mousedown',     ),   ),   It works, but only if form is valid. Of course I do not want to validate it just yet. I don't care if all fields are filled, I only need my form to be updated at this very moment. How can I make form api not to invoke hook_form_validate() and not test #required fields?
120972
My application has javascript button that call Apex code.  Exceptions from web services are sometimes thrown and the user is shown a detailed exception message like this:  A problem with the OnClick JavaScript for this button or link was encountered: {faultcode:'soapenv:Client', faultstring:'HttpException: Example Error Message Class.BananaWebService.fetchBanana: line 22, column 1', }   Is there a simple way to create friendly error messages for my users when exceptions are thrown like this:  Example Error Message   Exception Class  public class HttpException extends Exception{}   Web Service Class   @RestResource(urlMapping='/BananaWebService/*') global class BananaWebService {   webservice static void fetchBanana(Id accountId) {      throw new HttpException('Example Error Message');   } }   Javascript code   {!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}  {!REQUIRESCRIPT("/soap/ajax/28.0/apex.js")}   var accountId = "{!Account.Id}"; sforce.apex.execute("BananaWebService","fetchBanana", { accountId: accountId });  window.location.reload();
75780
Here is the situation:  I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows services, but has no built-in method to query their states.  Fortunately, it allows you to create custom actions in Java which can be called at any time during the installation process (by way of what I consider to be a rather convoluted API).    I just need something that will tell me if a specific service is started or stopped.  The IDE also allows calling batch scripts, so this is an option as well, although once the script is run, there is almost no way to verify that it succeeded, so I'm trying to avoid that.  Any suggestions or criticisms are welcome.
61928
A little bit of context:  I'm using the jQuery Validation plugin to validate a sign-up form. I now want to implement an ajax call to check whether the user name is available in the system, and I want to make this ajax call only if the userName value is a valid one as per the rules set in $(form).validate();  I want something like:  $("#userName").keyup(function () {     if ($("#userName").isValid()) {         //make ajax called     } });   I searched the documentation but i couldn't identify the solution to my problem.
80369
I want to create one SP dialogue box at home page which load the new item form of list or survey if current login user is not created any item previously.  Is there any way to do that ?  I tried using query but it takes time to load data.  My Code is as below :  &lt;script type="text/javascript"&gt; ExecuteOrDelayUntilScriptLoaded(init,'sp.js'); var context; var web; var user; var siteUrl = _spPageContextInfo.siteServerRelativeUrl ; //var userId= _spPageContextInfo.userId; var userId= 123; var flag=true; //var options = { title: "Announcements - New Item",url:"../Lists/Announcements/NewForm.aspx"}; var options = { title: "Announcements - New Item",url:"http://webtest:3333/Lists/test/NewForm.aspx"};  function init() { context = SP.ClientContext.get_current(); web = context.get_web(); //alert(flag); getCurrentUser(); retrieveListItems();  }  function getCurrentUser() { user = web.get_currentUser(); context.load(user); context.executeQueryAsync(onGetUserNameSucces, onGetUserNameFail); } function onGetUserNameSucces() { // TODO: implement your own succes handler     //alert(user.get_title()); } function onGetUserNameFail(sender, args) { // TODO: implement your own fail handler and do some logging }  function retrieveListItems() {       var oList = context.get_web().get_lists().getByTitle("test");      var camlQuery = new SP.CamlQuery();       //context.load(user);      //alert(userId);  camlQuery.set_viewXml('&lt;View&gt;&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name=\'Author\' /&gt;&lt;Value Type=\'User\'&gt;'+ user.get_title() +'&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;&lt;/View&gt;');     this.collListItem = oList.getItems(camlQuery);      context.load(collListItem);     context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));   }  function onQuerySucceeded(sender, args) {            //alert( _spPageContextInfo.userId);      var listItemInfo = '';     var listItemEnumerator = collListItem.getEnumerator();       while (listItemEnumerator.moveNext()) {         var oListItem = listItemEnumerator.get_current();         listItemInfo += '\nID: ' + oListItem.get_id() +              '\nTitle: ' + oListItem.get_item('Title');     }     alert(listItemInfo.toString());     if(listItemInfo==null){ //      flag='false';       SP.UI.ModalDialog.showModalDialog(options);            }      //alert(flag);        }  function onQueryFailed(sender, args) {     alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace()); } &lt;/script&gt;   I cant get result in the data
108302
Scenario: I have a custom button on a standard layout, which will call an apex class to do some validation on a record. If not validated, it needs to throw out some errors on that page. What are the best UX options to achieve this?  I am not too sure how to achieve this. Within a trigger, you can use the addError method to add the custom errors.  Can my Apex class reference the fields of a standard object? The ideal approach would be to do the following:  Contact.Email.addError('Please enter the right format here');   How can I achieve this via an apex class that the custom button will call?  What I have thought: Having a VF Page popup on the screen so that user can see all the errors, but that's not the best approach as UX is a big deal for this application  Thanks.
39132
I created a custom button for custom object to place in the related list. The custom object has two look-ups, one for case and one for account. This button, when clicked, should open in a new window to save a record of the custom object, with the default values for each look-up to populate automatically depending on the record where the button was clicked. It works for every record so far, except one case. It then throws the error: A problem with the Onclick Javascript for this button or link was encountered: Unexpected identifier.  I couldn't find any differences between records where it works and doesn't.  Code:  window.open('a2U/e?CF00N600000037HI4={!Account.Name}&amp;CF00N600000037HI4_lkid={!Account.Id}&amp;retURL=%2F{!Account.Id}&amp;CF00N600000037HI5={!Case.CaseNumber}&amp;CF00N600000037HI5_lkid={!Case.Id}&amp;retURL=%2F{!Case.Id}','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=yes,location=yes,status=yes');
95979
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was:      Apex trigger updatequotestatus caused an unexpected exception, contact your administrator: updatequotestatus: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.updatequotestatus line 5, column 1.   Error Occured at Line:     if((t.what.getsobjecttype() == quote__c.sobjecttype) &amp;&amp; (t.subject.substring(0,5) == 'Email')  trigger updatequotestatus on task (after insert, after update){     Set&lt;Id&gt; quoteIds = new Set&lt;Id&gt;();     List&lt;quote__c&gt; quotes = new List&lt;quote__c&gt;();      for(task t:trigger.new){         if(t.whatId!=null){             if((t.what.getsobjecttype() == quote__c.sobjecttype) &amp;&amp; (t.subject.substring(0,5) == 'Email')){                 quoteIds.add(t.whatId);             }         }     }      for(quote__c q:[select StageName__c from quote__c where Id IN : quoteIds]){         quote__c qt = new quote__c();         qt.Id = q.Id;         qt.StageName__c = 'Proposal Sent';         quotes.add(qt);     }      if(quotes.size()&gt;0){         update quotes;     } }
55301
i have this code but its not working it throws syntax error, unexpected '}' error  function my_custom_menu_item($items, $args) {     if(is_user_logged_in() &amp;&amp; $args-&gt;theme_location == 'primary')     {         $user=wp_get_current_user();         $name=$user-&gt;display_name; // or user_login , user_firstname, user_lastname         $items .= '&lt;li&gt;&lt;a href=""&gt;Welcome '.$name.'&lt;/a&gt;&lt;/li&gt;';         $items.= //Change Password, Logout, etc     }     elseif (!is_user_logged_in() &amp;&amp; $args-&gt;theme_location == 'primary') {         $items .= '&lt;li&gt;&lt;a href="'. site_url('wp-login.php') .'"&gt;Log In&lt;/a&gt;&lt;/li&gt;';         $items.= //Sign up, Lost Password     }     return $items; } add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
108897
I have created a checkbox in user edit using form alter and based checkbox state I want to print the message. For this I used below code  function module_form_user_profile_form_alter(&amp;$form, &amp;$form_state) {    $form['account']['checkbox'] = array(     '#type' =&gt; 'checkbox',     '#title' =&gt; 'Test check',    );    $form['#submit'][] = 'module_simplenews_unsubscribe'; }  //~ //Submit handler for Subscribe/unsubscribe newsletter. function module_simplenews_unsubscribe($form, &amp;$form_state) {    if ($form['account']['checkbox']['#value'] == 0) {     drupal_set_message(t("You are checked"));   }  if ($form['account']['checkbox']['#value'] == 1) {      drupal_set_message(t("You are unchecked"));   } }   It works fine. When checkbox is checked/unchecked and user saves the profile it prints respective message. But when user doesn't modify this checkbox field and modify some other field and saves, again it prints message based on checkbox state.  I want to display the message only when checkbox field is modified. How can I achieve this?
91532
Background  What we are trying to accomplish is to run daily some specific reports as an specific user.   So far  From a lightning component we are allowing the user to select a reports list. Once the user saves that list we are scheduling our apex class which will run those report, since the schedule is created as that user, it will run ok.  The running report code is something like:          Reports.ReportMetadata reportMd = ReportHelper.getReportMetadata(reportId);         Integer aggregateFieldPosition = ReportHelper.getAggregateFieldPosition(reportMd, aggregateFieldName);         Reports.ReportFilter filter = reportMd.getReportFilters()[0];         filter.setValue('some filter');         Reports.ReportResults results = Reports.ReportManager.runReport(reportId, reportMd);   That works fine on a simple context.   Problems   We potentially would have more than 1k users that will run 5 reports each.  The is a limit of 200 Schedule Apex Jobs Schedule Apex Jobs have a failure rate where they are canceled or deleted by the platform. We could have a monitor process to re-schedule them but that will run as system user.  We can not ask to create user filters since most of users are sharing the same 5 corporate's reports and them are using the org sharing model.   We have a good design but is based on the existence of RunAS() method. That does not exist.     Questions   Is there any workaround to run reports as any user. Maybe through Dashboards or Reports API ? What is the max number of schedule jobs recommended to avoid platform weird behaviours.  Any other idea of running several reports from apex considering the sharing model ?   Solution POC  I will add here the solution made using the guidance of the incredible answer given by @David Reed (Thanks a lot)  After create a connected app and give the users a permission set that is allow in that connected app, the sample code is like:  //get the accessToken by username using JWT standard class Auth.JWT jwt = new Auth.JWT(); jwt.setSub(username);  jwt.setAud('https://login.salesforce.com');          jwt.setIss(consumerKey); Auth.JWS jws = new Auth.JWS(jwt, certificateName); String token = jws.getCompactSerialization(); String tokenEndpoint = 'https://login.salesforce.com/services/oauth2/token'; Auth.JWTBearerTokenExchange bearer = new Auth.JWTBearerTokenExchange(tokenEndpoint, jws); String accessToken = bearer.getAccessToken();  //call the report api using that credentials Http h = new Http(); HttpRequest req = new HttpRequest(); req.setMethod('GET'); req.setEndpoint('https://jwt-rocks-dev-ed.my.salesforce.com/services/data/v44.0/analytics/reports/'+reportId+'?includeDetails=false'); String authorizationHeader = 'Bearer  ' + token; req.setHeader('Authorization', authorizationHeader); req.setHeader('Content-Type', 'application/json'); HttpResponse res = h.send(req); string resData =  res.getBody();   //process the result parseReportResponse(resData);   And that's it :)