0

I created a plugin which provides custom validation for civicrm forms. Part of the jQuery validation on the plugin makes an AJAX call to the plugin. The plugin calls its onAjax[Name] method. In the onAjax[Name] method, I want to use civicrm_api3( ... ). However, the system returns a fatal error

Call to undefined function civicrm_api3()

How do I use civicrm_api3 in the above context? Do I need to import some class files? The same code works if the validation occurs when the form is submitted with the submit button instead of AJAX.

3

Call civicrm_initialize() before using civicrm_api3() (or other CiviCRM functions).

This function is defined in the various CMS plugins (eg civicrm.module) and will load required files then initialize CiviCRM, after which you can make API calls.

Since booting the CRM adds overhead, it's best to only do when CRM is required - hence the separate function.

  • Civicrm_initialize() generates a fatal error call to undefined function civicrm_initialize() – ermSO Jan 11 '18 at 16:36
  • Can you paste the url you trying to call on ajax? – Pradeep Nayak Jan 11 '18 at 16:46
0

I used the following. It is important to note that my current working directory was that of the website not the plugin directory, so when I did the require_once and conf_path, I had to take that into account for class.api.php and civicrm.settings.php (i.e. my path was like administrator/.../class.api.php)

require_once 'your/civicrm/folder/api/class.api.php';
$api = new civicrm_api3(array(
  // Specify location of "civicrm.settings.php".
  'conf_path' => 'your/sites/default',
));
$apiParams = array(
  'first_name' => 'Alice',
  'last_name' => 'Roberts',
);
if ($api->Contact->Get($apiParams)) {
  //each key of the result array is an attribute of the api
  echo "\n contacts found ".$api->count;
}
else {
  echo $api->errorMsg();
}

It really should be documented somewhere that you cannot bootstrap CiviCRM in an onAjax[Name] method. In my case, when I tried it, the submit button for the form lost its functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.