Error 504 gateway time-out - yii2

I have a problem with download excel file from site. I use kartik\export\ExportMenu; I add into view in script this :
<?php
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
$gridColumns = [
'order_number',
[
But it doesnt help. How could I fixed it?
public function actionIndex()
{
$searchModel = new OrderSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

There are three configurations that can help in case of timeouts but it's not guaranteed.
Options to set in ExportMenu widget configuration:
Large Files Linking
'stream' => false
Large Files Streaming
'stream' => false, // this will automatically save the file to a folder on web server
'streamAfterSave' => true, // this will stream the file to browser after its saved on the web folder
'deleteAfterSave' => true, // this will delete the saved web file after it is streamed to browser,
'target' => '_blank',
Batch Loading
'batchSize' => 10,
'target' => '_blank',

try increase the max_execution_time
<?php
ini_set('max_execution_time', 3600); //3600 seconds = 60 minutes
$gridColumns = [
'order_number',
[

Related

Yii2 save Log into Database

i have some problem with Log with Yii2.
I set Log Targets in this way:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'flushInterval' => 1,//test
'targets' => [
[
'class' => 'common\components\SaDbTarget',
'levels' => ['error', 'warning','trace','info'],
'exportInterval' => 1,//test
//'categories' => ['application'],
/*'except' => [
'yii\db\*',
],*/
],
],
],
I create my SaDbTarget extending DbTarget Class, and this is working fine because i found in my table some log.
After that, in a controller i tried to set a log like this way
public function actionIndex(){
$searchModel = new CategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::trace('trace log', __METHOD__);
Yii::warning('warning log');
// here is the rest of the code
}
I can see this 2 logs into the debug toolbar, but not in my db table.
According to the Docs
To make each log message appear immediately in the log targets, you
should set both flushInterval and exportInterval to be 1
I tried to set this values but still doesn't work.
I don't know what am I doing wrong.
UPDATE
This is my SaDbTarget
namespace common\components;
use Yii;
use yii\log\DbTarget;
use yii\log\Logger;
class SaDbTarget extends DbTarget{
//set custom table db for saving log
public $logTable = 'authlog';
//overwrite export();
public function export(){
$tableName = $this->db->quoteTableName($this->logTable);
$sql = "INSERT INTO $tableName ([[authlog_login]], [[authlog_ip]], [[authlog_area]], [[authlog_act]], [[authlog_time]], [[authlog_data]])
VALUES (:login, :ip, :area, :act, :time, :data )";
$command = $this->db->createCommand($sql);
//Get username
$user=Yii::$app->user->getId();
//Get user ip address
$ip = Yii::$app->request->getUserIP();
//Get area/controller
$controller=Yii::$app->controller->uniqueId;
//Get action
$event= Yii::$app->controller->module->requestedAction->id;
//Set timezone
$time = Yii::$app->formatter->asDate('now', 'php:Y-m-d H:i:s');
//Set Data
$data = $this->messages[0];
$command->bindValues([
':login' => $user,
':ip' => $ip,
':area' => $controller,
':act' => $event,
':time' => $time,
':data' => $data,
])->execute();
}
Could you check wether the 'log' component is set on bootstrap?
I think this could be the issue that the dispatcher is not setup and does not pickup the target.
So the bootstrap should look like
[
'bootstrap' => ['log'],
'components' => [
'log' => [
...
],
....
]
Another way would be to check in the debugger if the dispatcher on the logger is configured correctly.

Yii2: Override global pdf orientation settings for mpdf in controller action

I am using the mpdf extension to generate pdf files. I have set global settings for the mpdf in the config file, hence I am able to call the function every time I want to generate a pdf from my controller action. However, I am finding it hard to change the orientation for the pdf with data that requires landscape orientation since the default orientation set in the global settings is portrait. Here are the codes:
main.pdf code for the global setting
'pdf' => [
'class' => Pdf::classname(),
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => [
'shrink_tables_to_fit' => 0
],
// refer settings section for all configuration options
],
Controller Action calling the global settings:
public function actionReservationsList()
{
$searchModel = new ReservationsSearch();
$dataProvider = $searchModel->search(Yii::$app->session->get('repquery'));
$dataProvider->pagination = false;
$pdf = Yii::$app->pdf;
$pdf->content = $this->renderPartial('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
$pdf->methods = [
'SetHeader' => [Yii::$app->user->identity->company->name.'||Date: ' . date("r")],
'SetFooter' => ['User: '.Yii::$app->user->identity->username.'||Page {PAGENO}'],
];
return $pdf->render();
}
So I need help in overriding the 'orientation' => Pdf::ORIENT_PORTRAIT, setting that is in the global settings main.php file from the controller action.
This work for me:
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use kartik\mpdf\Pdf;
class InformesController extends Controller
{
...
public function actionImprimirInforme($id,$key)
{
$html = $this->renderPartial('informe-pdf', [
'title' => 'Informe'
]);
$pdf = new Pdf([
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_LANDSCAPE,
'destination' => Pdf::DEST_BROWSER,
'options' => [
'showImageErrors' => true,
]
]);
$pdf->configure([
'title' => 'Informe ',
]);
$pdf->content = $html;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;
$pdf->execute('SetFooter', ['{PAGENO} de {nbpg}']);
$pdf->filename = "Informe.pdf";
return $pdf->render();
}
}
My first answer was wrong, i have been setting the property 'orientation' into pdf component, so the dynamically assign does not work properly.
Here you have the documentation example
You need to add the contents via addPage. So if you build a array of pages, with the contents etc - you should be able to specify the orientation per page.
<?php
$mpdf = new mPDF('', 'Legal');
$mpdf->WriteHTML('
Hello World
');
$mpdf->AddPage('L'); // Adds a new page in Landscape orientation
$mpdf->WriteHTML('
Hello World
');
$mpdf->Output();
?>
Try add this line this :
$pdf = Yii::$app->pdf;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;

Call to a member function saveAs() on a non-object

I am trying to upload image and database table.
on database table basic_info field name 'photo' that i want to store file name.
here is model
public function rules()
{
return [
[['photo'], 'string', 'max' => 255],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
];
}
here is controller
public function actionCreate()
{
$model = new BasicInfo();
if ($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
$filename = pathinfo($model->image , PATHINFO_FILENAME);
$ext = pathinfo($model->image , PATHINFO_EXTENSION);
$newFname = $filename.'.'.$ext;
$path=Yii::getAlias('#membersImgPath');
if(!empty($newFname)){
$model->image->saveAs($path.$newFname);
$model->image = $newFname;
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
}
}
return $this->render('create', [
'model' => $model,
]);
}
here is view
echo FileInput::widget([
'name' => 'photo',
'options' => ['accept' => 'image/*'],
]);
from your comment here,
$form = ActiveForm::begin(['type'=>ActiveForm::TYPE_VERTICAL],['opti‌​ons'=>['enctype'=>'m‌​ultipart/form-data']‌​]);
ActiveForm::begin does not have a second parameter. you need to use a single options array.
$form = ActiveForm::begin([
'type' => ActiveForm::TYPE_VERTICAL,
'opti‌​ons' => [
'enctype' => 'm‌​ultipart/form-data'
]‌
​]);
First of all, you have to check if there's a file. To do it try:
if(UploadedFile::getInstance($model, 'image')) {
// here should go your code with $model->image
}
Youre using pathinfo to get filename and extension. Remember, that youre using powerfull framework, you just initialized class UploadedFile which can do everything for you:
if(UploadedFile::getInstance($model, 'image')) {
$model->image = UploadedFile::getInstance($model, 'image');
$newFname = $model->image->name; // UploadedFile have properties like `name`, `tempName`, even `size`!
}
After doing this small fixes to your code (you should always check if something is set) - we can go to main problem.
Your input field name is photo, but youre trying to get image with name image.
Change this:
UploadedFile::getInstance($model, 'image');
To this:
UploadedFile::getInstance($model, 'photo'); // remeber to change it in `if` statement aswell!!
Theres also posibility that youre trying to upload file bigger than your post_max_size and upload_max_filesize allows. Change this properties in your php.ini, restart server and try again. If still something is not right, try to debug this thing, for start by doing var_dump($_FILES);die; in your controller.

CakePHP 3 - View class "CsvView.csv" is missing issue

I'm trying to include a csv exporter in my application, And i used https://github.com/FriendsOfCake/cakephp-csvview.
It works fine on my local machine but for some reason it doesn't work on my server. It throws me View class "CsvView.csv" is missing. error. Is there a way to fix this issue?
Here's my controller for reference
public function export() {
$this->response->download('export.csv');
// $opts1['order'] = array('Blogs.created' => 'desc');
// $blogsinfos = $this->Blogs->find('all',$opts1);
$opts1['order'] = array('Incomes.title' => 'desc');
$data = $this->Incomes->find('all',$opts1)->toArray();
$_serialize = 'data';
// Give the needed the colums to extract
$_extract = ['id', 'title' ,'description' , 'created' , 'amount'];
//headings for the CSV
$_header = ['ID', 'Title' ,'Description' , 'Created' , 'Amount'];
$this->set(compact('data', '_serialize', '_header', '_extract'));
$this->viewBuilder()->className('CsvView.csv');
return;
}
Code to create the downloadable link.
<?= $this->Html->link('Monthly Report', [
'controller' => 'incomes',
'action' => 'export',
'_ext' => 'csv'
],
['class' => 'btn btn-success'])
?>
I'm using CakePHP 3.4.7.

Cakephp goes to wrong path

I am working on Cakephp. In default.ctp i give a link like
<li><?= $this->Html->link('List',['controller' => 'Products', 'action' => 'index']) ?></li>
I also have a ProductsController.php .
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
class ProductsController extends AppController {
public function initialize(){
parent::initialize();
$this->loadcomponent('Flash');
}
public function index(){
$products = $this->Products->find('all');
$this->set(compact('products'));
}
But when i click on that link it give the error like
Error: WebrootController could not be found.
Error: Create the class WebrootController below in file: src/Controller/WebrootController.php
When click on toggle arguments it shows
object(Cake\Network\Request) {
params => [
'plugin' => null,
'controller' => 'Webroot',
'action' => 'products',
'_ext' => null,
'pass' => [],
'_matchedRoute' => '/:controller/:action/*',
'isAjax' => false
]
data => []
query => []
cookies => [
'__atuvc' => '1|21'
]
url => 'webroot/products/'
base => '/cakephp'
webroot => '/cakephp/'
here => '/cakephp/webroot/products/'
trustProxy => false
Please help me to solve this error.
Check if you have two .htaccess files present in your application root folder and in the webroot folder.
And make sure that an .htaccess override is allowed and that AllowOverride is set to All for the correct DocumentRoot
http://book.cakephp.org/3.0/en/installation.html#url-rewriting