public function actionAttachDocument($ownerId) { /** @var Number $number */ $number = Number::findOne($ownerId); if ($number === null) { throw new \RuntimeException("Не найден номер к которому нужно прикрепить документ"); } foreach (UploadedFile::getInstances(new Document(), 'file') as $file) { if (!$file->hasError) { $document = new Document(['filename' => $file->name, 'contentType' => $file->type, 'ownerId' => $number->getPrimaryKey(), 'file' => $file]); if (!$document->save()) { throw new \RuntimeException("Не удалось сохранить документ '{$file->name}'"); } } } echo Json::encode(['view' => $this->renderAjax('_document', ['ownerId' => $number->getPrimaryKey()])]); return; }
/** * @param UploadedFile|string $file * @throws \InvalidArgumentException|\RuntimeException * @return bool */ public function attachDocument($file) { $document = new Document(); if ($file instanceof UploadedFile) { $document->filename = $file->name; $document->contentType = $file->type; } elseif (is_file($file)) { $document->filename = basename($file); $document->contentType = mime_content_type($file); } else { throw new \InvalidArgumentException(__METHOD__ . ": unable attach document '{$file}'.'"); } $document->ownerId = $this->getPrimaryKey(); $document->file = $file; if ($document->save()) { return true; } else { throw new \RuntimeException(__METHOD__ . ": unable attach document '{$document->filename}': " . implode(", ", array_keys($document->getErrors())) . " is invalid"); } }