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.
Related
I am trying to add dynamic drop downs, which will added from javascript on clicking add new button.
view file
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use kartik\select2\Select2Asset;
use yii\helpers\ArrayHelper;
Select2Asset::register($this);
?>
<div class='row'>
<div class='form-group'>
<?=
Select2::widget([
'name' => 'coupons',
'value' => $model->coupon_id,
'data' => ArrayHelper::map($coupons, 'id', 'name'),
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
controller
public function actionNewCoupon()
{
$coupon = new DealCoupon();
$deal = Yii::$app->request->get('deal');
$order = Yii::$app->request->get('order');
$coupon->deal_id = $deal;
$coupon->order = $order;
$coupon->save();
$coupons = Coupon::find('id','name')->all();
return $this->renderPartial('_form', [
'model' => $coupon,
'coupons' => $coupons
],true, true);
}
js file
.get(BASE_URL + '/coupon/new-coupon', { deal: dealId, order: order }, function(data) {
var dealWidget = newStep.find('.coupon-panel');
$(newStep).find('.coupon-panel').html(data);
});
What I am getting
Any help to resolve this issue is appreciable, as I am totaly lost.
Thanks in advance.
yii\web\Controller::renderPartial() doesn't include registered JS or CSS files. Try using yii\web\Controller::renderAjax() instead. It's similar but it injects registered JS/CSS files into rendered html code.
I am trying to build a dynamic page system with cakephp 3.
Using slugs I can show pages and content. But on the homepage, it is just using the default view template.
I have the routes as followed:
$routes->connect('/', ['controller' => 'pages', 'action' => 'display', 'home']);
$routes->connect('/:slug', ['controller' => 'pages', 'action' => 'view'], ['pass' => ['slug'], 'slug' => '[^\?/]+']);
Which works for the none homepage pages.
But I want to use the homepage as / (e.g. localhost:8000/)
And not /home (e.g. localhost:8000/home).
Currently the view function in the pages controller looks like this:
public function view($slug = null)
{
$pages = TableRegistry::getTableLocator()->get('webpages');
$page = $pages->findBySlug($slug)->firstOrFail();
$this->set(compact('page'));
}
Any idea?
Seems I already found the solution.
I changed the routing to just the following line:
$routes->connect('/*', ['controller' => 'pages', 'action' => 'view']);
Then I changed the view as followed:
public function view($slug = null)
{
$pages = TableRegistry::getTableLocator()->get('webpages');
if($slug == null){
$query = $pages->find('all', [
'conditions' => ['ishome' => 1]
]);
} else {
$query = $pages->find('all', [
'conditions' => ['slug' => $slug]
]);
}
$page = $query->first();
$this->set(compact('page'));
}
I use the answer from the following comment, but had to modify it a bit, since that code was used for an older version of cakephp (I am using cakekphp 3.8).
https://stackoverflow.com/a/3975923/6181243
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.
When my form is sent UploadedFile::getInstance($model, 'images') returns null. I also tried UploadedFile::getInstanceByName('images'). In the $_POST array the images key is empty e.g. 'images' => ['']. The file exists in $_FILES array.
My code is pretty simple. My view:
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'validation-wizard wizard-circle floating-labels',
'enctype'=>'multipart/form-data'
],
]); ?>
<?= $form->field($model, 'images[]')->fileInput([
'id' => 'image_0',
'class' => 'dropify',
'data-default-file' => ''
]) ?>
<?php ActiveForm::end() ?>
In my model I have:
public $images;
public function rules()
{
return [
['images', 'each', 'rule' => ['file']],
];
}
If you want to access an array of files, you need to use UploadedFile::getInstances() instead of UploadedFile::getInstance().
$files = UploadedFile::getInstances($model, 'images');
Good example of handling multiple files can be found in guide in Uploading Multiple Files section.
I'm using yii2-widget-fileinput for an image uploading in a form.
When I click on upload or the create button I get Trying to get property of non-object error in controller.
Controller
public function actionCreate()
{
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/';
$model = new Ads();
$provinces = ArrayHelper::map(Province::find()->all(), 'name', 'name');
if ($model->load(Yii::$app->request->post())){
$image = UploadedFile::getInstances($model, 'image');
$model->filename = $image->name;
$ext = end((explode(".", $image->name)));
$avatar = Yii::$app->security->generateRandomString().".{$ext}";
$path = Yii::$app->params['uploadPath'].$avatar;
if ($model->save()) {
$image->saveAs($path);
$model->image_adr = $path;
return $this->redirect(['view', 'id' => $model->id]);
}else{
echo "error on saving the model";
}
}
return $this->render('create', [
'model' => $model,
'provinces'=>$provinces,
]);
}
model rules
public function rules()
{
return [
[['type', 'explanation', 'cost', 'province_name', 'address'], 'required'],
[['type', 'explanation', 'image_adr', 'address'], 'string'],
[['cost'], 'integer'],
[['province_name'], 'string', 'max' => 20],
[['province_name'], 'exist', 'skipOnError' => true, 'targetClass' => Province::className(), 'targetAttribute' => ['province_name' => 'name']],
[['image'],'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png', 'maxFiles'=>3,],
];
and finnally the view
<?= $form->field($model, 'image[]')->widget(FileInput::classname(), [
'options'=>['accept'=>'image/*', 'multiple'=>true],
'pluginOptions'=>['allowedFileExtensions'=>['jpg','gif','png'], 'overwriteInitial'=>false,]
]); ?>
the problem should refer to this part in the controller I think
$image = UploadedFile::getInstances($model, 'image');
An image of the error might be helpful
You should check first is image in post or not.
....
$image = UploadedFile::getInstances($model, 'image'); //getInstanceByName
if (!empty($image))
$model->filename = $image->name;
.....
if ($model->save()) {
if (!empty($image))
$image->saveAs($path);
.........
Make sure in your form ency type is added:
$form = ActiveForm::begin([
'id' => 'form_id',
'options' => [
'class' => 'form_class',
'enctype' => 'multipart/form-data',
],
]);
The problem is when you're using UploadedFile::getInstances($model, 'image'); you should work with foreach or treat it like an array.
Something that made me a problem was that even if you're using UploadedFile::getInstanc (notice the obsoleted s in the end) you should still treat it like an array and in all parts you should use $image[0], not $iamge lonely.