/**
  * @throws Exception
  * @throws HttpException
  */
 public function actionDeleteRecipient()
 {
     $this->requirePostRequest();
     $id = craft()->request->getRequiredPost('id');
     $model = null;
     if ($model = sproutEmailDefaultMailer()->getRecipientById($id)) {
         if (!$model) {
             throw new Exception(Craft::t('Recipient with id ({id}) was not found.', array('id' => $id)));
         }
         $vars = array('recipientId' => $model->id);
         $deleted = SproutEmail_DefaultMailerRecipientRecord::model()->deleteByPk($model->id);
         if ($deleted) {
             SproutEmail_DefaultMailerRecipientListRecipientRecord::model()->deleteAllByAttributes($vars);
             craft()->userSession->setNotice(Craft::t('Recipient deleted successfully.'));
             if (craft()->request->isAjaxRequest()) {
                 $this->returnJson(array('success' => true));
             }
         } else {
             craft()->userSession->setNotice(Craft::t('Unable to delete recipient.'));
             if (craft()->request->isAjaxRequest()) {
                 $this->returnErrorJson(Craft::t('Unable to delete recipient.'));
             }
         }
         $this->redirectToPostedUrl($model);
     }
     throw new HttpException(404);
 }
 public function saveRecipient(SproutEmail_DefaultMailerRecipientModel &$model)
 {
     $isNewElement = !$model->id;
     if (!$isNewElement) {
         $record = SproutEmail_DefaultMailerRecipientRecord::model()->findById($model->id);
         if (!$record) {
             throw new Exception(Craft::t('No recipient exists with the id “{id}”', array('id' => $model->id)));
         }
     } else {
         $record = new SproutEmail_DefaultMailerRecipientRecord();
     }
     $record->setAttributes($model->getAttributes(), false);
     $record->validate();
     $model->addErrors($record->getErrors());
     if (!$model->hasErrors()) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             if (craft()->elements->saveElement($model, true)) {
                 $saved = false;
                 if ($isNewElement) {
                     $record->id = $model->id;
                 }
                 if ($record->save(false)) {
                     $model->id = $record->id;
                     $saved = $this->saveRecipientListRecipientRelations($record->id, $model->recipientLists);
                 }
                 if ($transaction !== null && $saved) {
                     $transaction->commit();
                 }
                 return $saved;
             }
             $model->addErrors($record->getErrors());
         } catch (\Exception $e) {
             if ($transaction !== null) {
                 $transaction->rollback();
             }
             throw $e;
         }
     }
     return false;
 }