I tried to use Laravel excel with multiple sheets and shouldQueue, but the file returned with an empty sheet, all the sheet created successfully though.
I manage to make a work around by limiting the record per file
here is the code
<?php
namespace App\Exports;
use App\Exports\Sheets\AnswersPerSchoolSheet;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class AnswersExport implements WithMultipleSheets, ShouldQueue
{
use Exportable;
public function __construct($start, $end)
{
$this->start = $start;
$this->end = $end;
}
public function sheets(): array
{
$sheets = [];
$schools = DB::table('schools')
->join('answers', 'schools.id', '=', 'answers.school_id')
->select('schools.id')
->distinct('schools.id')
->whereBetween('schools.id', [$this->start,$this->end])
->get();
foreach ($schools as $school) {
$sheets[] = new AnswersPerSchoolSheet($school->id);
}
return $sheets;
}
}
Related
I am going to use DynamicPDF plugin to export to pdf some fields from backend on update/edit view of my plugin in OctoberCMS, can someone help me?
on plugin controller i have this call:
<?php namespace Vimagem\Pacientes\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
use Renatio\DynamicPDF\Classes\PDF;
use Renatio\DynamicPDF\Classes\PDFWrapper;
class Pacientes extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Vimagem.Pacientes', 'main-menu-item');
}
/** PDF **/
public function pdf($id)
{
return PDF::loadTemplate('export-data-pdf')->stream('download.pdf');
}
}
On the PDF Template (export-data-pdf) i need to call some form fields from one client:
{{ name }}
{{ address }}
{{ phone }}
etc...
but i canĀ“t get the fields show up, what its wrong ?
Thank you,
Vitor
This code was found in the plugins documents.
use Renatio\DynamicPDF\Classes\PDF; // import facade
...
public function pdf()
{
$templateCode = 'renatio::invoice'; // unique code of the template
$data = ['name' => 'John Doe']; // optional data used in template
return PDF::loadTemplate($templateCode, $data)->stream('download.pdf');
}
I have used this plugin and it works well. You need to pass in data to the PDF stream.
This is done, worked around a solution for this.
Here is the controller application:
<?php namespace Vimagem\Pacientes\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
use Renatio\DynamicPDF\Classes\PDFWrapper;
use Vimagem\Pacientes\Models\Paciente;
use \October\Rain\Database\Traits\Validation;
use Str;
class Pacientes extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Vimagem.Pacientes', 'main-menu-item');
}
/**** PDF Export ***/
public function pdf($id)
{
$paciente = Paciente::find($id);
if ($paciente === null) {
throw new ApplicationException('User not found.');
}
$filename = Str::slug($paciente->nome) . '.pdf';
try {
/** #var PDFWrapper $pdf */
$pdf = app('dynamicpdf');
$options = [
'logOutputFile' => storage_path('temp/log.htm'),
];
return $pdf
->loadTemplate('export-data-pdf', compact('paciente'))
->setOptions($options)
->stream($filename);
} catch (Exception $e) {
throw new ApplicationException($e->getMessage());
}
}
}
Now i can use partials on the template like this:
<p>{{ paciente.nome }}</p>
<p>{{ paciente.morada }}</p>
etc...
Thank you all that try to helped me.
Vitor
I need to do a where condition on the code field from my intermediate table. My two models are;
class Agreement extends Eloquent {
protected $table = 'agreements';
public function clients(){
return $this->belongsToMany('Client', 'client_agreements')->withPivot('start_date', 'expire_date', 'code');
}
}
And;
class Client extends Eloquent {
public function agreements(){
return $this->belongsToMany('Agreement', 'client_agreements')->withPivot('start_date', 'expire_date', 'id', 'code');
}
}
My controller is currently;
public function show($code, $client_id)
{
//
$client = Client::with('agreements')->find($client_id);
$client_agreement = $client->agreements;
}
I think I need to expand the $client->agreements; code to include a where condition on the $code. I have tried so many different combinations but just keep returning the same Call to undefined method error.
I've tried things like;
$client_agreement = $client->agreements->where('code', '=', $code);
$client_agreement = $client->agreements->code->find($code);
$client_agreement = $client->agreements->pivot->code->find($code);
I always get the same error. I'm not that great on objects so maybe I'm looking at this all wrong. How is it done?
You need to access ->relation() not ->relation (which is dynamic property call):
$client_agreement = $client->agreements()
->wherePivot('code', '=', $code)
->first();
My system is working fine for small database and my report is generates from at least 5 table of phpmyadmin after certain limit of data load '500 internal server error' will come.I want enhance exporting a report to csv/excel from phpmyadmin using yii for larger database.
I use this extension to export to CSV. http://www.yiiframework.com/extension/csvexport/
I have created an action that I can attach to any controller that I need to export.
<?php
class Csv extends CAction {
public $field_list;
public function run() {
$controller = $this->getController();
/* Disable the logging because it should not run on this function */
foreach (\Yii::app()->log->routes as $route) {
if ($route instanceof \CWebLogRoute) {
$route->enabled = false;
}
}
\Yii::import('core.extensions.ECSVExport.ECSVExport');
//use the existing filters
$model_name = $controller->modelName();
$model = new $model_name('search');
$dataProvider = $model->search();
$criteria = $dataProvider->criteria;
//remove the pagination
$dataProvider->setPagination(false);
//changing the criteria to only select what we want
$criteria->select = implode(',', $this->field_list);
$dataProvider->setCriteria($criteria);
//export to CSV
$csv = new \ECSVExport($dataProvider);
if(isset($_GET['test'])) {
echo $csv->toCSV();
} else {
\Yii::app()->getRequest()->sendFile($controller->modelName() . '_'.date('Y-m-d').'.csv', $csv->toCSV(), "text/csv", false);
exit();
}
}
}
field_list are the fields that I need to export.
For the controller I add
/**
* #return array actions to be mapped to this controller
*/
public function actions(){
return array(
'csv'=>array(
'class'=>'core.components.actions.Csv',
'field_list'=>array('t.id', 't.name', 't.status'),
),
);
}
/**
I use the same search as in the controller because it suits me and because I use http://www.yiiframework.com/extension/remember-filters-gridview/ I actually can export exactly what is on the screen. Change the field list to what you need. Remember to give access to the csvAction function.
You can use yiiexcell extension for that: http://www.yiiframework.com/extension/yiiexcel/ it is simple wrapper for PHPExcel http://phpexcel.codeplex.com/releases/view/107442
I'm planning to have a function that will store the sql statement on the Cache using the given second parameter on remember() as the key and whenever the sql statement changes it will run against the database again and overwrite the stored sql, also the cached result, and if not it will take the default cached result by the remember() function.
So I am planning to have something like this on Illuminate\Database\Query\Builder
/**
* Execute the query based on the cached query
*
* #param array $columns
* #return array|static[]
*/
public function getCacheByQuery($columns = array('*'))
{
if ( ! is_null($this->cacheMinutes))
{
list($key, $minutes) = $this->getCacheInfo();
// if the stored sql is the same with the new one then get the cached
// if not, remove the cached query before calling the getCached
$oldSql = self::flag($key);
$newSql = $this->toSql().implode(',', $this->bindings);
if ($newSql!==$oldSql)
{
// remove the cache
\Cache::forget($key);
// update the stored sql
self::updateFlag($key, $newSql);
}
return $this->getCached($columns);
}
return $this->getFresh($columns);
}
public static function updateFlag($flag, $value)
{
$flags = \Cache::get(t().'databaseFlags', []);
$flags[$flag] = $value;
\Cache::put(t().'databaseFlags', $flags, USER_SESSION_EXPIRATION);
}
public static function flag($flag)
{
$flags = \Cache::get(t().'databaseFlags', []);
return #$flags[$flag] ?: false;
}
But the thing is, I don't want to put this directly on Illuminate\Database\Query\Builder since it is just my need for the current application I am working. I'm trying to extend Illuminate\Database\Query\Builder, but the problem is it does not detect the my extension class.
Call to undefined method Illuminate\Database\Query\Builder::getCachedByQuery()
My Extension Class
<?php namespace Lukaserat\Traits;
class QueryBuilder extends \Illuminate\Database\Query\Builder {
/**
* Execute the query based on the caced query
*
* #param array $columns
* #return array|static[]
*/
public function getCachedByQuery($columns = array('*'))
{
if ( ! is_null($this->cacheMinutes))
{
list($key, $minutes) = $this->getCacheInfo();
// if the stored sql is the same with the new one then get the cached
// if not, remove the cached query before calling the getCached
$oldSql = self::flag($key);
$newSql = $this->toSql().implode(',', $this->bindings);
if ($newSql!==$oldSql)
{
// remove the cache
\Cache::forget($key);
// update the stored sql
self::updateFlag($key, $newSql);
}
return $this->getCached($columns);
}
return $this->getFresh($columns);
}
public static function updateFlag($flag, $value)
{
$flags = \Cache::get(t().'databaseFlags', []);
$flags[$flag] = $value;
\Cache::put(t().'databaseFlags', $flags, USER_SESSION_EXPIRATION);
}
public static function flag($flag)
{
$flags = \Cache::get(t().'databaseFlags', []);
return #$flags[$flag] ?: false;
}
}
Implementing on..
<?php
use LaravelBook\Ardent\Ardent;
use Lukaserat\Traits\DataTable;
use Lukaserat\Traits\QueryBuilder as QueryBuilder;
use Illuminate\Support\MessageBag as MessageBag;
class ArdentBase extends Ardent implements InterfaceArdentBase{
use DataTable;
Am I missing something?
Is it correct that I overwrite the get() method on the Illuminate\Database\Query\Builder by renaming the function I made in my extension class from getCachedByQuery to get since I just extending the routine of the get.
I changed
public function getCachedByQuery($columns = array('*'))
to
public function get()
on my Lukaserat\Traits\QueryBuilder
and it is now working as I expected..
I am working with options, to add some additional info like image. and I saved this data to my own table with option_type_id and option_id. now on frontend I would like to join my own table data to default options. so these options come with image info.
$_option->getValues()
this function returns option data, now I have to reach the implementation of this function where it generate the query so I could add join to retrieve my own data with.
I dont see a clean way to do this.
Here is a dirty way:
RewriteMage_Catalog_Model_Resource_Product_Option and add this function below.
Modify it with you join. however the join to you table would then be done for every product option. You will need to check for somekind of a flag and only add your join if this flag is set.
protected function _getLoadSelect($field, $value, $object)
{
$select = parent::_getLoadSelect($field, $value, $object);
if("do your check here"){
$select->join('your table')
}
return $select;
}
Here is what i got success from.
i overridden the resource collection of product
class MYC_COPSwatch_Model_Resource_Product_Option_Collection extends Mage_Catalog_Model_Resource_Product_Option_Collection{
public function addValuesToResult($storeId = null)
{
if ($storeId === null) {
$storeId = Mage::app()->getStore()->getId();
}
$optionIds = array();
foreach ($this as $option) {
$optionIds[] = $option->getId();
}
if (!empty($optionIds)) {
/** #var $values Mage_Catalog_Model_Option_Value_Collection */
$values = Mage::getModel('catalog/product_option_value')
->getCollection()
->addTitleToResult($storeId)
->addPriceToResult($storeId)
->addSwatchToResult($storeId) //USED Join in this function
->setOrder('sort_order', self::SORT_ORDER_ASC)
->setOrder('title', self::SORT_ORDER_ASC);
foreach ($values as $value) {
$optionId = $value->getOptionId();
if($this->getItemById($optionId)) {
$this->getItemById($optionId)->addValue($value);
$value->setOption($this->getItemById($optionId));
}
}
}
return $this;
}
might be save time for someone.