Function Download in Yii2 - file

public function actionUnduh($id) {
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('../web/bukti/') . $download->bukti;
if (file_exists($path)) {
//return \Yii::$app->response->sendFile($download->pre_paper,#file_get_contents($path));
return Yii::$app->response->sendFile($path);
}
}
I need to download file from folder web/bukti, the code not error but the code doesn't work, Anyone can help me :(

public function actionUnduh($id)
{
$download = PstkIdentifikasi::findOne($id);
$path = Yii::getAlias('#webroot').'/bukti/'.$download->bukti;
if (file_exists($path)) {
return Yii::$app->response->sendFile($path, 'File name here');
}
}
Refer below:
Yii2 Aliases
Yii2 sendFile()

Firstly you can write an action in SiteController.php like this:
public function actionDownload()
{
$file=Yii::$app->request->get('file');
$path=Yii::$app->request->get('path');
$root=Yii::getAlias('#webroot').$path.$file;
if (file_exists($root)) {
return Yii::$app->response->sendFile($root);
} else {
throw new \yii\web\NotFoundHttpException("{$file} is not found!");
}
}
then you can call this function anywhere:
Yii::$app->urlManager->createUrl(['site/download','path'=>'/upload/files/','file'=>'filename.pdf'])
Be careful your files must be in this directory:
"backend/web/upload/files/filename.pdf"
or
"frontend/web/upload/files/filename.pdf"

Related

Find a file in React

How to search a specific named file in a folder using React ?
My file name is like below
var filename = window.location.hostname ;
Now I would like to search the file like below
if(require('../public/service/filename.json')) {
//do something
}
else {
//do something
}
You can use following way:
const checkFileExist = (path) => {
try {
return require(`${path}`);
} catch (err) {
return null;
}
};
and use it on your component
if(checkFileExist('../public/service/filename.json') === null) {
// something
} else {
// something
}

CakePhp AngularJs pagination

I started learning CakePhp and AngularJs, I want to get pagination working.
I found this simple tutorial: http://florian-kraemer.net/2015/10/cakephp-angularjs-pagination/ but I can't get it to work.
This is the code from the example:
public function index() {
$query = $this->Table->find();
if (empty($this->request->params['paging'][$this->Table->alias()])) {
$paging = false;
} else {
$paging = $this->request->params['paging'][$this->Table->alias()];
}
$this->set('records', $this->paginate($query));
$this->set('paging', $paging);
$this->set('_serialize', ['records', 'paging']);
}
My Model is called Entry, how to I have to change the code for this example to work, I tried it like this but it's not working:
public function index() {
$query = $this->Entry->find();
if (empty($this->request->params['paging'][$this->Entry->alias()])) {
$paging = false;
} else {
$paging = $this->request->params['paging'][$this->Entry->alias()];
}
$this->set('records', $this->paginate($query));
$this->set('paging', $paging);
$this->set('_serialize', ['records', 'paging']);
}
I am not sure what to change in my code to get it working. Any help would be appreciated.
Thanks, Gregor
Please try this code, it should be work. You have to declare $paging after paginate.
public function index() {
$query = $this->Entry->find();
$this->paginate($query);
if (empty($this->request->params['paging'][$this->Entry->alias()])) {
$paging = false;
} else {
$paging = $this->request->params['paging'][$this->Entry->alias()];
}
$this->set(compact('records', 'paging'));
$this->set('_serialize', ['records', 'paging']);
}

validation error messages in BaseController

I have a UsersController'S signup action which gathers validation error messages like
if($user->errors()) {
$error_msg = [];
foreach( $user->errors() as $errors) {
if(is_array($errors)){
foreach($errors as $error) {
$error_msg[] = $error;
}
} else {
$error_msg[] = $errors;
}
}
if(!empty($error_msg)){
$this->Flash->error(__(implode("\n \r", $error_msg)) );
}
}
This kind of error messages I want to use in all controllers. This means I have to repeat the same code in all controllers? Or is there a way to write a central function without passing specific entity?
If you want to get model validation in string you can create a component which can be accessed from the controller
Create a component UtilsComponent.php under src/Controller/Component
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
class UtilsComponent extends Component
{
public function validationError($validationError)
{
$errorMsg = '';
if ($validationError) {
foreach ($validationError as $errorOn => $error) {
$errorMsg .= strtoupper($errorOn) . ': ' . implode(', ', $error) . "\n";
}
} else {
$errorMsg = 'Error Occurred! Try again';
}
return $errorMsg;
}
}
After that you can use this function anywhere in the controller like this
if ($this->Users->save($user)) {
// Do what you want
} else {
$this->Flash->error(__($this->Utils->validationError($user->errors())));
}
Hope this will help

Cakephp 3 : How to detect mobile in controller by requestHandler?

I need detect mobile in controller for a condition. I have tried below code in my controller.
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
Then I have written below code in index method
if ($this->RequestHandler->is('mobile'))
{
//condition 1
}else {
//condition 2
}
Here I get the error
Error: Call to undefined method Cake\Controller\Component\RequestHandlerComponent::is()
How can mobile detect in controller ?
The request handler isn't necessary for that since all the request handler does is proxy the request object:
public function isMobile()
{
$request = $this->request;
return $request->is('mobile') || $this->accepts('wap');
}
The controller also has direct access to the request object, so the code in the question can be rewritten as:
/* Not necessary
public function initialize()
{
parent::initialize();
}
*/
public function example()
{
if ($this->request->is('mobile')) {
...
} else {
...
}
}
I think that will be
$this->RequestHandler->isMobile()
CakePHP 3 uses mobiledetect/mobiledetectlib lib
In bootstrap.php added 2 types of detection 'mobile', 'tablet'
You can use it:
if ($this->request->is('mobile')) {
// ...
}
elseif ($this->request->is('tablet')) {
// ...
}
else {
// ...
}

Can't delete row from beforeSave method in CakePHP 2.4+

I cant delete in my beforeSave() method in newer version of Cake but it works with earler libs (e.g. version 2.2)
Does anyone know how get it working again without altering the Cake libs?
Code:
public function beforeSave($options = array()) {
if(!empty($this->data['Attachment']['delete']) && (int) $this->data['Attachment']['delete'] === 1) {
if($this->deleteFromDb((int) $this->data['Attachment']['id'])) {
$this->data['Attachment'] = array();
return true;
} else {
return false;
}
}
return true;
}
public function deleteFromDb($id) {
if ($this->delete($id)) {
return true;
} else {
return false;
}
}
The following line returns false but I don't understand why:
if($this->deleteFromDb((int) $this->data['Attachment']['id']))
If I replace it with the following it is still returns false:
if($this->delete((int) $this->data['Attachment']['id']))
If I access the method from a controller it returns true, e.g.
$this->Model->deleteFromDb($id);
Any help at all would be great.
I got this resolved, In the newer libs for cake you can't delete from beforeSave(), so I moved it to the next appropriate method, in my case this was beforeValidate().
Hope this helps someone.

Resources