cakephp4でフォームから入力した情報と、事前に用意したテンプレートファイル(Excel)を使用して
見積書を作成できるWEBアプリを制作しています。
bakeコマンドで作成したEstimatesControllerのaddメソッドを変更し、
作成したEstimatesComponentを呼び出しています。
このコンポーネントには入力情報からExcelを作成する処理を書きました。
コントローラーの肥大化を防ぐためにコンポーネントに記述しましたが、そもそもこれが正しいのかも不明です。
Estimates(見積書)テーブルには
titleやpriceなどの他、別テーブルTaxRates(税率)のIDも登録するようになっており、
コンポーネント内で税込価格を算出するため、フォームの税率IDから税率テーブル内のtax_rate(税率(10などの数値))を引っ張ってきたいのですが、
その方法が分かりません。
### 該当のソースコード ```ここに言語名を入力 コントローラー public function add() { $estimate = $this->Estimates->newEmptyEntity(); if ($this->request->is('post')) { $estimate = $this->Estimates->patchEntity($estimate, $this->request->getData()); if ($this->Estimates->save($estimate)) { //$taxRate =$this->Estimates->TaxRates->find()->select(["tax_rate"])->where(['tax_rate_id' => "1"])->first(); //コンポーネント呼び出し $this->loadComponent("Estimates"); $this->Estimates->excelBuilder(); $this->Flash->success(__('The estimate has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The estimate could not be saved. Please, try again.')); } $clients = $this->Estimates->Clients->find('list', ['limit' => 200])->all(); $taxRates = $this->Estimates->TaxRates->find('list', ['limit' => 200])->all(); $users = $this->Estimates->Users->find('list', ['limit' => 200])->all(); $this->set(compact('estimate', 'clients', 'taxRates', 'users')); }
コンポーネント <?php namespace App\Controller\Component; use Cake\Controller\Component; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; class EstimatesComponent extends Component { private $controller; private $request; //コントローラーを使用できるようにする public function beforeFilter() { $this->controller = $this->getController(); $this->request = $this->controller->getRequest(); } function excelBuilder() { $this->beforeFilter(); //Excelの読み込み $filePath = $this->webroot . "excel/"; $file = IOFactory::load($filePath . "estimate_template.xlsx"); $workSheet = $file->getActiveSheet(); //Excelファイルへの書き込み $title = $this->request->getData("title"); $workSheet->setCellValue("A8", "件名:". $title); //・・・・・省略 // 作成した請求書のダウンロード header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="'. "estimate.xlsx" . '"'); header('Cache-Control: cache, must-revalidate'); $writer = new Xlsx($file); $writer->save('php://output'); exit(); } }
試したこと
試しにコントローラーに
$taxRate =$this->Estimates->TaxRates->find()->select(["tax_rate"])->where(['tax_rate_id' => "1"])->first();
このように記述したところ、期待どおり”10”という数値が取り出せたのですが、
コンポーネントからはこの部分がエラーになるようです。
調べても分からず困っております。ご教授いただければ幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。