Для очередного проекта появилась нестандартная просьба — сделать экспорт покупателей в админке opencart в формат csv. Конечно можно было купить соответствующий модуль, но это решение не для программистов) Я предлагаю свое простенькое решение, которое реализуется путем добавления небольшого кода в 2-х файлах.Итак первый файл, который нужно отредактировать это customer_list.tpl находится в папке admin\view\template\sale
Было
1 | <div class = "buttons" ><a onclick= "$('form').attr('action', '<?php echo $approve; ?>'); $('form').submit();" class = "button" ><?php echo $button_approve ; ?></a><a onclick= "location = '<?php echo $insert; ?>'" class = "button" ><?php echo $button_insert ; ?></a><a onclick= "$('form').attr('action', '<?php echo $delete; ?>'); $('form').submit();" class = "button" ><?php echo $button_delete ; ?></a></div> |
Стало
1 | <div class = "buttons" ><a class = "button" href= "/admin/index.php?route=sale/customer/export&token=<?php echo $this->session->data['token'] ?>" >Экспорт покупателей</a><a onclick= "$('form').attr('action', '<?php echo $approve; ?>'); $('form').submit();" class = "button" ><?php echo $button_approve ; ?></a><a onclick= "location = '<?php echo $insert; ?>'" class = "button" ><?php echo $button_insert ; ?></a><a onclick= "$('form').attr('action', '<?php echo $delete; ?>'); $('form').submit();" class = "button" ><?php echo $button_delete ; ?></a></div> |
Далее добавляем в файл admin\controller\sale\customer.php фуекцию экспорта, я разместил в конце файла перед последним закрытием }
1 | public function export(){ |
2 | $this ->load->model( 'sale/customer' ); |
3 | $results = $this ->model_sale_customer->getCustomers( $data ); |
5 | foreach ( $results as $result ) { |
7 | $this ->data[ 'customers' ][] = array ( |
8 | 'customer_id' => $result [ 'customer_id' ], |
9 | 'name' => $result [ 'name' ], |
10 | 'email' => $result [ 'email' ], |
11 | 'customer_group' => $result [ 'customer_group' ], |
12 | 'status' => ( $result [ 'status' ] ? $this ->language->get( 'text_enabled' ) : $this ->language->get( 'text_disabled' )), |
13 | 'approved' => ( $result [ 'approved' ] ? $this ->language->get( 'text_yes' ) : $this ->language->get( 'text_no' )), |
14 | 'ip' => $result [ 'ip' ], |
15 | 'date_added' => date ( $this ->language->get( 'date_format_short' ), strtotime ( $result [ 'date_added' ])), |
20 | $customer_export = 'customer_export_' . (string)( date ( 'Y-m-d-Hi' )) . '.csv' ; |
22 | $tmp = DIR_SYSTEM . 'logs/' ; |
24 | $tmp_dir = $tmp . '/' . $uid . '/' ; |
25 | $file = $tmp . '/' . $uid . '.csv' ; |
27 | if (( $handle = fopen ( $file , 'w' )) !== FALSE) { |
40 | fputcsv ( $handle , $ods_title , ';' , '"' ); |
42 | foreach ( $this ->data[ 'customers' ] as $fields ) { |
44 | fputcsv ( $handle , $fields , ';' , '"' ); |
51 | if (( $output = file_get_contents ( $file )) !== FALSE ) { |
55 | $this ->response->addheader( 'Pragma: public' ); |
56 | $this ->response->addheader( 'Connection: Keep-Alive' ); |
57 | $this ->response->addheader( 'Expires: 0' ); |
58 | $this ->response->addheader( 'Content-Description: File Transfer' ); |
59 | $this ->response->addheader( 'Content-Type: application/octet-stream' ); |
60 | $this ->response->addheader( 'Content-Disposition: attachment; filename=' . $customer_export ); |
61 | $this ->response->addheader( 'Content-Transfer-Encoding: binary' ); |
62 | $this ->response->addheader( 'Content-Length: ' . strlen ( $output )); |
63 | $this ->response->setOutput( $output ); |
64 | exit ( $this ->response->output()); |
Поля естественно можно поменять, что-то отключить, что-то добавить, но основной смысл думаю понятен) Теперь при клике на кнопку Экспорт покупателей мы получим список всех покупателей нашего магазина в csv
Этот же способ актуален и для Aceshop, собстевнно для него он и писался 😉
1.Файл не создается. Выгружается в окне браузера.
2. Выкидывает при нажатии на кнопку «экспорт».
Причин может быть куча. Включите отображение ошибок и смотрите в чем проблема.
С ссылкой еще можно поступить таким образом что бы не выкидывало:
<a class="button" href="/admin/index.php?route=sale/customer/export&token=session->data[‘token’]; ?>»>Экспорт покупателей
Ссылка неправильная
$results = $this->model_sale_customer->getCustomers($data);
а откуда у нас бурется переменная $data ?
Ниоткуда) Её можно не писать, эта переменная используется только когда нужно сделать выборку по определённым параметрам. В данном случае она не нужна и ее нет.
$results = $this->model_sale_customer->getCustomers($data);
$data ….я убрал из-за неё ошибка вылетает
Так же href=»/admin/index.php?route=sale/customer/export» не катит….так при клике на кнопку нас выкидывает с админки и просит заново авторизоваться….нужно еще токен передавать
в фалй admin\controller\sale\customer.php в функцию getList()
добавлена строка
$this->data[‘export’] = $this->url->link(‘sale/customer/export’, ‘token=’ . $this->session->data[‘token’] . $url, ‘SSL’);
ну и в теме теперь используется
href=»» вместо старой ссылки.
еще была проблема с кодировкой русских символов в csv файле
Есть возможность предоставить код с учетом указанных правок в комментариях?
Сам я туповат не совсем догоняю как исправить проблему с кодировкой ((((
что и куда прописывать чтобы не выкидывало из админки? И с кодировкой помогите, спс.
Иначе в чем смысл статьи если в ней половина решения?
Поправил ссылку в статье. Добавил токен &token=session->data[‘token’] ?> . С кодировкой проблемы могут быть если файл сохранили после редактирования не в utf-8