Как мне заставить domPDF правильно отображать мое представление codeigniter

Я чувствую, что есть небольшой шаг, который я упускаю, и, по-видимому, все понимают другие связанные вопросы.

Я создал простое представление CI 2, контроллер и модель, показанные ниже:

Я установил dompdf в папку helpers следующим образом:

applications/helpers/dompdf

applications/helpers/dompdf/dompdf_help.php

Я хочу, чтобы это произошло, когда пользователь нажимает кнопку отправки на странице просмотра, отправляет данные формы в базу данных, а затем получает заполненную форму в формате PDF.

Между получением недоопределенных ошибок var или вообще ничего, кроме данных, идущих в БД, я не вижу, чего мне не хватает.

Не могли бы некоторые, пожалуйста, направить меня? Что я здесь не понимаю?

Просмотреть

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>test pdf</title>
    </head>
    <body>
<?php // Change the css classes to suit your needs    

$attributes = array('class' => '', 'id' => '');
echo form_open('quicksubmit', $attributes); ?>

<p>
        <label for="title">Title <span class="required">*</span></label>
        <?php echo form_error('title'); ?>

        <?php // Change the values in this array to populate your dropdown as required ?>
        <?php $options = array(
                    ''  => 'Please Select',
                    'Mrs'    => 'Mrs',
                    'Miss'    => 'Miss',
                    'Ms'    => 'Ms',
                    'Mr'    => 'Mr',
                  ); ?>

        <br /><?php echo form_dropdown('title', $options, set_value('title'))?>
</p>                                             

<p>
        <label for="first_name">First Name</label>
        <?php echo form_error('first_name'); ?>
        <br /><input id="first_name" type="text" name="first_name" maxlength="100" value="<?php echo set_value('first_name'); ?>"  />
</p>

<p>
        <label for="last_name">Last Name <span class="required">*</span></label>
        <?php echo form_error('last_name'); ?>
        <br /><input id="last_name" type="text" name="last_name" maxlength="100" value="<?php echo set_value('last_name'); ?>"  />
</p>

<p>
        <label for="branch">Branch</label>
        <?php echo form_error('branch'); ?>

        <?php // Change the values in this array to populate your dropdown as required ?>
        <?php $options = array(
                    ''  => 'Please Select',
                    'Branch 1'    => 'Branch One',
                    'Branch 2'    => 'Branch Two',
                  ); ?>

        <br /><?php echo form_dropdown('branch', $options, set_value('branch'))?>
</p>                                             

<p>
        <label for="zip">Zip</label>
        <?php echo form_error('zip'); ?>
        <br /><input id="zip" type="text" name="zip" maxlength="7" value="<?php echo set_value('zip'); ?>"  />
</p>


<p>
        <?php echo form_submit( 'submit', 'Submit'); ?>
</p>

<?php echo form_close(); ?>

    </body>
</html>

Контроллер

<?php

class Quicksubmit extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->database();
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->model('quicksubmit_model');
    }   
    function index()
    {           
        $this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');          
        $this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');            
        $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');         
        $this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');            
        $this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');

        $this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');

        if ($this->form_validation->run() == FALSE) // validation hasn't been passed
        {
            $this->load->view('quicksubmit_view');
        }
        else // passed validation proceed to post success logic
        {
            // build array for the model
                    $this->pdf($output);

                        $form_data = array(
                                    'title' => set_value('title'),
                                    'first_name' => set_value('first_name'),
                                    'last_name' => set_value('last_name'),
                                    'branch' => set_value('branch'),
                                    'zip' => set_value('zip')
                                    );

            // run insert model to write data to db

            if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
            {
                redirect('quicksubmit/success');   // or whatever logic needs to occur
            }
            else
            {
            echo 'An error occurred saving your information. Please try again later';
            // Or whatever error handling is necessary
            }
        }
    }
    function success()
    {
            redirect(base_url(),'refresh');     
            /*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
            sessions have not been used and would need to be added in to suit your app';*/
    }
        function pdf()
            {
                 $this->load->helper(array('dompdf', 'file'));
                 // page info here, db calls, etc.     
                 $html = $this->load->view('quicksubmit_view', $data, true);
                 pdf_create($html, 'filename');
                 /*or
                 $data = pdf_create($html, '', false);
                 write_file('name', $data);*/
                 //if you want to write it to disk and/or send it as an attachment    
            }
}
?>

Модель

<?php

class Quicksubmit_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    // --------------------------------------------------------------------

      /** 
       * function SaveForm()
       *
       * insert form data
       * @param $form_data - array
       * @return Bool - TRUE or FALSE
       */

    function SaveForm($form_data)
    {
        $this->db->insert('quicksubmit', $form_data);

        if ($this->db->affected_rows() == '1')
        {
            return TRUE;
        }

        return FALSE;
    }
}
?>

файл dompdf_help.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function pdf_create($html, $filename='', $stream=TRUE) 
{
    require_once("dompdf/dompdf_config.inc.php");

        $dompdf = new DOMPDF();
        $dompdf->load_html($html);
        $dompdf->render();
        if ($stream) {
            $dompdf->stream($filename.".pdf");
        } else {
            return $dompdf->output();
        }
}
?>

person user1176783    schedule 01.08.2013    source источник
comment
Я не пользователь CI, так что простите мое невежество. Вы вызываете $this->pdf($output), но не устанавливаете $output, а метод pdf не принимает никаких параметров. Просто точка чистоты кода. В методе pdf вы загружаете представление, передавая ему переменную $data. Эта переменная установлена ​​CI, потому что она нигде больше не определена? Возможно, вы захотите удалить все, что вам не нужно, чтобы упростить код и устранить ошибки (которые вы должны опубликовать здесь, поскольку они могут иметь значение).   -  person BrianS    schedule 02.08.2013


Ответы (1)


ты был почти там!

Вероятно, лучше хранить dompdf в папке Third_Party, и это не помощник по воспламенению кода. - увидеть путь, в котором я храню его в конструкторе. Тогда он всегда доступен.

Кроме того, вероятно, лучше выполнять «работу» программы в модели, включая создание PDF-файлов и т. д.

  • не используйте ?> в конце вашего кода.

я модифицировал ваш код, чтобы он работал, и убедился, что он работает. он просто сохраняет файл с именем tmp/name.pdf. Я уверен, что вы можете решить все остальное. я закомментировал загрузчик базы данных, потому что мне не нужно было тестировать код.

см. прил.

<?php

 class Quicksubmit extends CI_Controller {

function __construct()
{
    parent::__construct();
    $this->load->library('form_validation');
    //$this->load->database();
    $this->load->helper('form');
    $this->load->helper('url');
    $this->load->helper('file');
    $this->load->model('quicksubmit_model');

    global $_dompdf_show_warnings;global $_dompdf_debug;global $_DOMPDF_DEBUG_TYPES;global $_dompdf_warnings;$_dompdf_show_warnings = FALSE;
    require_once(realpath(APPPATH."third_party/dompdf")."/dompdf_config.inc.php"); // remember that the constant DOMPDF_TEMP_DIR may need to be changed.
    spl_autoload_register('DOMPDF_autoload');
}   
function index()
{           
    $this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');          
    $this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');            
    $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');         
    $this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');            
    $this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');

    $this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');

    if ($this->form_validation->run() == FALSE) // validation hasn't been passed
    {
        $this->load->view('quicksubmit_view');
    }
    else // passed validation proceed to post success logic
    {
        // build array for the model


        $form_data = array(
                    'title' => set_value('title'),
                    'first_name' => set_value('first_name'),
                    'last_name' => set_value('last_name'),
                    'branch' => set_value('branch'),
                    'zip' => set_value('zip')
                    );
        $this->pdf($form_data);
        // run insert model to write data to db

        if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
        {
            redirect('quicksubmit/success');   // or whatever logic needs to occur
        }
        else
        {
            echo 'An error occurred saving your information. Please try again later';
        // Or whatever error handling is necessary
        }
    }
}
function success()
{
        redirect(base_url(),'refresh');     
        /*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
        sessions have not been used and would need to be added in to suit your app';*/
}
function pdf($data)
{
    $dompdf = new DOMPDF();
    $html = $this->load->view('quicksubmit_view', $data, true);
    $dompdf->set_paper('a4','portrait');
    $dompdf->load_html($html);
    $dompdf->render();
    $pdf = $dompdf->output();
    write_file('tmp/name.pdf', $pdf);

}
}
person pgee70    schedule 23.09.2013