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
Related
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;
}
}
I have some code I'm working on for a PDF download page type in SilverStripe that allows people to upload a PDF file to the backend. In turn, this PDF file is then read into the top navigation as a link that, when clicked, automatically downloads the PDF file.
I have most of the code set up:
<?php
class PDFTemplate extends Page {
public static $db = array(
);
public static $has_one = array(
'PDFFile' => 'File'
);
public static $has_many = array(
);
public function Link() {
return '/home/download?ID=' . $this->ID;
}
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Main", new UploadField('PDFFile', "PDF File"), "Content");
return $fields;
}
}
class PDFTemplate_Controller extends Page_Controller {
public static $allowed_actions = array (
'download'
);
public function init() {
parent::init();
}
public function download() {
$id = $_GET['ID'];
$obj = DataObject::get_by_id('PDFTemplate', $id);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;');
header('Pragma: no-cache');
return readfile("");
}
}
But the one thing I'm stuck on at the moment is how to get the url of the PDF file into the readfile() command. $obj right now is being set to get the id of the specific PDF file for the page....so do I need do use something like $obj.URL or $obj.Link in readfile()?
You're requesting a PDFTemplate object at the moment, not a File object so that's a problem - but you shouldn't need to pass an ID to this page to download it anyway because the Page already has that information.
If you don't need to hide the direct URL of the PDF in question, something like this might be a lot easier and offer better performance:
Delete the download() and Link() functions.
In the .ss template for your menu do: <a <% if $PDFFile %>href="$PDFFile.Link" target="_blank"<% else %>href="$Link"<% end_if %>>
following this link I am trying to create a register form and connect the form to tables "user" and "profile". In my controller I have copied the same code as follows:
public function actionRegistration()
{
$form = new CForm('application.views.user.registerForm');
$form['user']->model = new Users;
$form['profile']->model = new Profile;
if($form->submitted('register') && $form->validate())
{
$user = $form['user']->model;
$profile = $form['profile']->model;
if($user->save(false))
{
$profile->userID = $user->id;
$profile->save(false);
$this->redirect(array('/user/login'));
}
}
var_dump($form->submitted('register'));
$this->render('registration', array('form'=>$form));
}
I actually don't know what is $form->submitted('register') for and why it returns false!
Can anyone explain me what is that and what is 'register' value which is passed to the submitted function!? Also why it should return false while posting the form?
the traditional way to get form data is
$model = new User;
if(isset($_POST["register"])){ //get the form data
...
$model->attributes=$_POST["register"]; //set model's attributes
...
}
for more examples you can go: http://www.yiiframework.com/doc/blog/1.1/en/comment.create
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.
I'm confused how to project models result in view in joomla 2.5
I have the controller which is initializing the model
class FrontpageMyComponentControllerItem extends JControllerLegacy
{
private $id;
public function display($cachable = false, $urlparams = array())
{
// Initialise variables.
$jinput = JFactory::getApplication()->input;
$this->id = $jinput->get('id');
$cachable = true;
$model = $this->getModel('item');
$result_in_view = $model->Item('23'); //$id what I get
// Set the default view name and format from the Request.
$viewName = $jinput->get('view', 'item');
$jinput->set('view', $viewName);
return parent::display($cachable, $safeurlparams);
}
}
now how do I have the result in my view?
In most components data (results) are being retrieved from Model by the View.
I'm not really sure why, but I guess it's to give more power to Views.
FrontpageMyComponentViewItem extends JViewLegacy
{
/** #var array Data are stored here */
public $items;
public function display($tpl = null)
{
/** Retrieve data from Model */
$items = $this->get('Items');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
// Raise an error
JError::raiseWarning(500, implode("\n", $errors));
return false;
}
// Assign data, so layout can access these
$this->items =& $items;
parent::display($tpl);
}
}
This is different than usual MVC implementations where Controller is retrieving data from Model and passing it to View.
If you'd like to see example of this in Joomla, look at MediaController in Joomla 2.5.
Sometimes the View may not be necessary (output is in JSON) and then you may retrieve data inside controller and output it instantly using echo like in search suggestions
There are new MVC (vs legacy) classes in Joomla, but core components still don't use them.