0

I have a multi database site, when I save my content type it is added in both the Laravel side database and the default Drupal database. Now most of my code is in try catch and it does not save data in Laravel db in case of catch but it does save the content types or nodes in the Drupal db hence they show up in my views. How do I stop this in case any error occurs while saving the content type ? eg ;

try {

        if (!empty($rec)) {
            $db->update('xyz')->fields([
                'type' => $type,
                'logo' => $img_url,
                'link' => $redirect_url,
                'status_id' => $form_state->getValue('field_status')[0]['value'],
                'site_id' => $form_state->getValue('field_site')[0]['target_id'],
                'updated_at' => $currentDateTime,
            ])->condition('id', $rec['id'])
                ->execute();
            $message = 'Content has been updated successfully to the job portal.';
            \Drupal::messenger()->deleteAll();
            \Drupal::messenger()->addMessage($message);
        }
    } catch (Exception $e) {
        //log the exception to watchdog.
        $message = 'Something went wrong to save content in job portal';
        \Drupal::messenger()->deleteAll();
        \Drupal::messenger()->addError(t($message));
        \Drupal::logger('Save-Awards and Certificates')
            ->error($e->getMessage());
    }
    \Drupal\Core\Database\Database::setActiveConnection('default');
4
  • Just to clarify the question, you don't want to save the nodes to Drupal in case there is an error saving to Laravel? May 11 '20 at 22:23
  • You can check this answer drupal.stackexchange.com/questions/223140/… May 11 '20 at 22:29
  • It's unclear where the code is placed, but assuming it is in a hook presave hook. If you did not catch the exception or did throw a new exception, then the node wouldn't be saved, because on Drupal side an entity save operation is by default enclosed in a transaction which is rolled back in case of an error.
    – 4k4
    May 12 '20 at 6:26
  • BTW if you only want to log and display the error message then you can do this in an exception event subscriber, you don't need to catch the exception here.
    – 4k4
    May 12 '20 at 6:39

Your Answer

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

Browse other questions tagged or ask your own question.