Skip to content
This repository has been archived by the owner on Aug 22, 2024. It is now read-only.

Allow File Attachments #3

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/controllers/MainController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@

namespace plugins\dolphiq\form\controllers;

use Yii;
use Craft;
use craft\web\View;
use plugins\dolphiq\form\models\Form;
use plugins\dolphiq\form\models\log;
use plugins\dolphiq\form\models\Settings;
use plugins\dolphiq\form\Plugin;
use Yii;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\mail\MessageInterface;
use plugins\dolphiq\form\Plugin;
use plugins\dolphiq\form\models\log;
use plugins\dolphiq\form\models\Form;
use plugins\dolphiq\form\models\Settings;

class MainController extends \craft\web\Controller
{
Expand Down Expand Up @@ -75,9 +76,12 @@ public function actionIndex($handle=null, $params = [])

$params = is_array($params) ? $params : json_decode($params, true);

if ($form->load(Craft::$app->request->post()) && $form->validate()) {
// UPLOAD FILES INTO MODEL
foreach($form->files as $fileField) {
$form->attachment = UploadedFile::getInstance($form, $fileField);
}

/** Validated succesfull. **/
if ($form->load(Craft::$app->request->post()) && $form->validate()) {

// Send mail and return thank you page
if(!is_null($mail_owner) || !is_null($mail_customer)) {
Expand All @@ -90,6 +94,15 @@ public function actionIndex($handle=null, $params = [])
->setSubject($form->getSettings()->mail_subject_owner)
->setTo($form->getSettings()->mail_to);

foreach ($form->files as $fileField) {
if ($form[$fileField]) {
$ownerMail->attachContent(file_get_contents($form[$fileField]->tempName), [
'fileName' => $form[$fileField]->name,
'contentType' => $form[$fileField]->type,
]);
}
}

// Save owner mail
$this->saveInDb($form, $ownerMail);

Expand Down Expand Up @@ -120,7 +133,7 @@ public function actionIndex($handle=null, $params = [])
}
}

return $this->renderAjax($view, ['model' => $form, 'params' => $params, 'handle' => $handle]);
return $this->renderAjax($view, ['model' => $form, 'params' => $params, 'handle' => $handle, 'errors' => $form->getErrors()]);
}

return null;
Expand Down
7 changes: 7 additions & 0 deletions src/models/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ class Form extends Model{
*/
CONST APPEND_MAIL_CUSTOMER_PART = 'MailCustomer.php';

/**
* Model Attributes that will be treated as files.
*
* @var array
*/
public $files = [];

/**
* The name of this form
* @return string
Expand Down