0

коллеги. Не получается присвоить к переменной название выбранной пользователем техники. То есть, клиент заполняет форму, при её заполнение и нажатию на кнопку он получает файл pdf с названием техники и её характеристикой. Как можно реализовать то, чтобы название техники присваивалось к переменной $filename, которая находится по коду в самом низу, и скаченный файл имел название выбранной техники. Сайт лежит на хостинге с подключенной бд, в реализации использовался PHP Laravel Название техники подтягивается из БД <?php

namespace App\Http\Controllers;



use App\Exceptions\Warning;

use App\Import\MachineImport;

use App\Model\Machine;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Str;

use App\Exports\MachineExport;

use Maatwebsite\Excel\Facades\Excel;





trait MachineOrderTait

{

    protected function getPhotoUrl($file, $defaultImage = '' ) {

        $file_content = false;

        if ($file) {

            return $file;

            // $file_content = @file_get_contents($file);

        }

        if (!$file_content) {

            $file = resource_path('img').DIRECTORY_SEPARATOR.$defaultImage;

            $file_content = @file_get_contents($file);

        }

        $imageData = base64_encode($file_content);

        $mime_type = 'image/png';

        if (strpos($file, '.gif') !== false) {

            $mime_type = 'image/gif';

        }

        if (strpos($file, '.jpeg') !== false || strpos($file, '.jpg') !== false) {

            $mime_type = 'image/jpeg';

        }



        return 'data:'.$mime_type.';base64,'.$imageData;

    }

    public function createOrder()

    {

        ini_set("pcre.backtrack_limit", "5000000");

        $Machine = Machine::findOrFail($this->request->id);



        $EUR_2_RUB = $this->getEuroRate();



        if ($EUR_2_RUB) {

            $Machine->price = number_format($EUR_2_RUB * $Machine->price, 0,'.', ' ').' ₽';

        }



        $options = DB::select("

                                select 

                                  option_id,

                                  value,

                                  mo.name,

                                  mo.description

                                from machine_option_value ov

                                join machine_options mo on mo.id = ov.option_id 

                                where ov.machine_id = :id and ov.value != '' and ov.value is not null ", ["id" => $Machine->id]);



        $optionCode = DB::select("select * from machine_option_code");



        foreach ($options as &$option) {

            $t = $option->value;



            foreach ($optionCode as $item) {

                $optionPrice = number_format($EUR_2_RUB * $item->price, 0,'.', ' ').' ₽';

                $t = str_replace(trim($item->code), $optionPrice, $t);

            }



            $m = [];

            preg_match_all('/(\d{1,})\s{0,1}€/', $t, $m);

            foreach ($m[0] as $idx => $subStr) {

                $val = $m[1][$idx];

                $newVal = number_format($EUR_2_RUB * $val, 0,'.', ' ').' ₽';

                $t = str_replace($subStr, $newVal, $t);

            }

            $option->value = $t;

        }





        $filter = $this->request->filter;

        $Machine->q0 = Machine::calcQ0($Machine, $filter['t0'], $filter['tc'] );

        $Machine->p = Machine::calcP($Machine, $filter['t0'], $filter['tc'] );

        $Machine->link_photo_main = $this->getPhotoUrl($Machine->link_photo_main, 'machine-main.jpg');

        $Machine->link_photo_dimensions = $this->getPhotoUrl($Machine->link_photo_dimensions, 'machine-dimensions.jpg');



        $mpdf = new \Mpdf\Mpdf();

        $css = file_get_contents(resource_path() . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'order.css');

        $html = view('order', ['machine' => $Machine, 'filter' => $filter, 'options' => $options])->toHtml();

        $header = view('order_header')->toHtml();

        $footer = view('order_footer')->toHtml();

        $mpdf->margin_header = 0;

        $mpdf->margin_footer = 0;

        $mpdf->SetHTMLHeader($header);

        $mpdf->SetHTMLFooter($footer);

        $mpdf->AddPageByArray([

            'margin-left' => 0,

            'margin-right' => 0,

            'margin-top' => 20,

            'margin-bottom' => 20,

        ]);





        $mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);

        $mpdf->WriteHTML($html);

        $fileName = 'commercial.pdf';

        $mpdf->Output($fileName, \Mpdf\Output\Destination::DOWNLOAD);

    }

}

1 ответ 1

0

Не совсем понимаю, откуда берется название техники, но если из шаблона, то его можно передать ajax-ом на сервер и там уже вытянуть в свою php-переменную

1
  • Спасибо за ответ, помог мне товарищ, перед foreach я присвоил к $filename значение 'name' из базы данных, так же добавил '.pdf' 27 июл 2022 в 12:44

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.