Передайте значение из контроллера в представление - PullRequest
0 голосов
/ 07 февраля 2020

Я создал форму и передал значения для name и picture из формы. Доступ к значению осуществляется из контроллера загрузки следующим образом:

  $data = array(
    'title' => $this->input->post('title', true),
    'name' => $this->input->post('name',true),
    'picture' => $this->file_upload($_FILES['picture'])
);
return $data;

Мне нужно передать эти значения в представление, поэтому я изменил приведенный выше код следующим образом:

    class Upload extends CI_Controller
{
    function  __construct() {
        parent::__construct();
    }

public function input_values(){
    $data = array(
        'name' => $this->input->post('name',true),
        'picture' => $this->file_upload($_FILES['picture'])
    );
$this->load->view('documents', $data);    }
        function add(){
        $data = $this->input_values();
        if($this->input->post('userSubmit')) {
          $this->file_upload(($_FILES['picture']));
            if (!empty($_FILES['picture']['name'])) {
                $config['upload_path'] = 'uploads/docs/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
                $config['file_name'] = $_FILES['picture']['name'];
                $data['picture']=$this->file_upload($_FILES['picture']);
            }
        }

        return $this->db->insert('files', $data);
    }

    //logo image upload
    public function file_upload($file)
    {
        $this->my_upload->upload($file);
        if ($this->my_upload->uploaded == true) {
            $this->my_upload->file_new_name_body = 'file_' . uniqid();
            $this->my_upload->process('./uploads/docs/');
            $image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
            return $image_path;
        } else {
            return null;
        }
    }

}

Но я возможность получить только значение заголовка. Следующая ошибка возникает как для имени, так и для заголовка:

Message: Undefined variable: name

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

 <?php var_dump($title)?>
  <?php var_dump($name)?
  <?php var_dump($picture)?>

1 Ответ

0 голосов
/ 10 февраля 2020

Итак, эта часть, где вы получаете данные поста и представление загрузки (содержат форму загрузки)

public function input_values() {
    $data = array(
        'name' => $this->input->post('name',true),
        'picture' => $this->file_upload($_FILES['picture'])
    );
    $this->load->view('documents', $data);    
}

, тогда эта часть обрабатывает запрос поста из формы загрузки:

function add() {
        $data = $this->input_values();
        if($this->input->post('userSubmit')) {
          $this->file_upload(($_FILES['picture']));
            if (!empty($_FILES['picture']['name'])) {
                $config['upload_path'] = 'uploads/docs/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
                $config['file_name'] = $_FILES['picture']['name'];
                $data['picture']=$this->file_upload($_FILES['picture']);
            }
        }

        return $this->db->insert('files', $data);
    }

и в этой части вы загружаете файл

public function file_upload($file)
    {
        $this->my_upload->upload($file);
        if ($this->my_upload->uploaded == true) {
            $this->my_upload->file_new_name_body = 'file_' . uniqid();
            $this->my_upload->process('./uploads/docs/');
            $image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
            return $image_path;
        } else {
            return null;
        }
    }

, когда вы вызываете функцию add (), она вызывает функцию input_values ​​(), затем загружает представления, тогда следующая строка кодов не будет выполнена (cmiiw).

так что, может быть, вы хотите изменить с этим:

public function index() {
   if ($this->input->post()) {
      // then handle the post data and files tobe upload here
      // save the post data to $data, so you will able to display them in view
   } else {
      // set the default data for the form
      // or just an empty array()
      $data = array();
   }

   // if the request was not a post, render view that contain form to upload file
   $this->load->view('nameOfTheView', $data);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...