When i call this function first time then file downloaded but after refresh the page it show me some not understanding character on my browser screen
// Controller Code
public function actionDownload($id)
{
$model = $this->findModel($id);
$file ='../frontend/uploads/users/'.$model->image;
if(file_exists($file))
{
return Yii::$app->response->sendFile($file);
exit;
}
//Button Code
[
'attribute'=>'resume',
'label'=>'Resume',
'format'=>'raw',
'value'=>function($data)
{
if($data->resume != null)
{
// $url = Yii::$app->params['application_base'].'admin/user/download/'.$data->id;
return Html::a('Download', ['download','id'=> $data->id]);
}
else
{
return 'NA';
}
},
],
Try to omit a pjax amd use
return Html::a('Download', ['download','id'=> $data->id, 'data-pjax' => 0]);
instead of
return Html::a('Download', ['download','id'=> $data->id]);
Related
When I am trying to insert new column using codeigniter version 4 with dbforge.
I got an error in Production mode:
Whoops!We seem to have hit a snag. Please try again later...
public function addLanguage()
{
$language = preg_replace('/[^a-zA-Z0-9_]/', '', $this->request->getPost('language',FILTER_SANITIZE_STRING));
$language = strtolower($language);
if (!empty($language)) {
if (!$this->db->fieldExists($language, "language")) {
$this->dbforge->addColumn("language", [
$language => [
'type' => 'TEXT'
]
]);
$this->session->setFlashdata('message', 'Language added successfully');
return redirect()->route('backend/setting/language');
}
} else {
$this->session->setFlashdata('exception', display('please_try_again'));
}
return redirect()->route('backend/setting/language');
}
What am I doing wrong in this code? Any potential help would be greatly appreciated!
Development mode error image below:
You can use this code
public function addLanguage()
{
$dbforge = \Config\Database::forge();
$language = preg_replace('/[^a-zA-Z0-9_]/', '', $this->request->getPost('language',FILTER_SANITIZE_STRING));
$language = strtolower($language);
if (!empty($language)) {
if (!$this->db->fieldExists($language, "language")) {
$dbforge->addColumn("language", [
$language => [
'type' => 'TEXT'
]
]);
$this->session->setFlashdata('message', 'Language added successfully');
return redirect()->route('backend/setting/language');
}
} else {
$this->session->setFlashdata('exception', display('please_try_again'));
}
return redirect()->route('backend/setting/language');
}
why did I get this bad request (#400) error after submitting my update on my 'news' section :
Missing required parameters: id
This is my update function
php
public function actionUpdate($id)
{
$model = $this->findModel($id);
$oldFile = $model->getImageFile();
$currentImage=$model->image;
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$image = $model->uploadImage();
// revert back if no valid file instance uploaded
if ($image === false) {
$model->image = $currentImage;
}
if ($model->save()) {
// upload only if valid uploaded file instance found
if ($image !== false && unlink($oldFile)) { // delete old and overwrite
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
]);
}
} else {
return $this->render('update', [
'model'=>$model,
]);
}
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Please note that the updating and uploading image process were actually a success (that's why I didn't show my model's method code that my actionUpdate called). If I go directly to view the recently updated page and view the content, it clearly displays the updated contents along with the image without problem. The error only occurs just right after the update is submitted. I thought I had pass the parameter after the update by this line :
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
Right before that line I even echo $model->id to test and it echoed out the id.
I've looked for similar problem in StackOverflow and find someone suggested this :
php
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
But it didn't work. Any idea?
You should pass URL as flat array:
return $this->redirect(['view', 'id' => $model->id,'image' => $model->image]);
My Code related is the following:
Model Rules
[['documentTypeId', 'itemId', 'name', 'document'], 'required'],
[['document'], 'file', 'skipOnEmpty' => false, 'extensions' => ['png', 'jpg', 'doc', 'pdf'], 'checkExtensionByMimeType'=>false],
Model method
public function upload($file)
{
if ($this->validate()) {
$userFolder = Yii::getAlias("#app")."/uploads/".$this->item->userId;
if(BaseFileHelper::createDirectory($userFolder) !== false) {
$fileName = uniqid(rand(), false) . '.' . $this->document->extension;
$file->saveAs($userFolder.'/' . $fileName);
$this->document = $file->name;
return true;
} else {
return false;
}
} else {
return false;
}
}
Controller
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = UploadedFile::getInstance($model, 'document');
if($model->upload($file) !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
This is giving me a validation error: "Document can not be blank". If I set "Document" field as not required and submit form I get "Please upload a file."
I am uploading this through a form with some other fields.
Any ideas?
I have found the error it was the model->validate() on controller. When i do:
$model->load(Yii::$app->request->post())
File content is not loaded to the "document" field. Yii generates a hidden field which is empty. So I need first to do this:
$file = UploadedFile::getInstance($model, 'document');
So now my controller looks like this:
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post())) {
$model->document = UploadedFile::getInstance($model, 'document');
if($model->validate()) {
if ($model->upload() !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
And I removed the validation inside upload method on model. Hope it helps someone.
I use Laravel5.2 to build a E-commerce platform and get some troubles.When I loginout user state and I use Session::forget('user') or $request->session()->forget('user'), it works in current page,and I redirect to the login page and dd(Session::all()) find the session 'user' still exist!!! so I am confused to know what is wrong with it? plz tell me the reason,thanks all.
ps. loginout code
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
echo json_encode(['result' => 1]);
exit;
}
echo json_encode(['result'=>0,'msg'=>'loginout error']);
exit;
}
The session doesn't get saved until the response is sent and events/middleware are triggered.
Try doing:
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
return Response::json(['result' => 1]);
return '';
}
return Response::json(['result'=>0,'msg'=>'loginout error']);
}
Or if your using the helpers:
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
return response()->json(['result' => 1]);
return '';
}
return response()->json(['result'=>0,'msg'=>'loginout error']);
}
I am using the default captcha implementation of the yii2 advanced framework. I have a problem: I want to change my captcha code every time I refresh a page but when I refresh the page my captcha code does not change.
The most correct solution will be to create your own CaptchaAction, that extends yii\captcha\CaptchaAction and override the run() method as follows:
namespace app\actions; // Change to your own
class CaptchaAction extends yii\captcha\CaptchaAction {
public $autoRegenerate = true;
public function run()
{
if ($this->autoRegenerate && Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) === null) {
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode(true));
}
return parent::run();
}
}
try this
<script>
window.onload = hello;
function hello()
{
document.getElementById('loginform-captcha-image').click();
}
</script>
because you have set YII_ENV to TEST like this defined('YII_ENV') or define('YII_ENV', 'test'); change it to defined('YII_ENV') or define('YII_ENV', 'prod');
I found a dirty way round this - simply trigger the click event when the page loads. Add this code at the very end of your view file, after the end of the form;
$js = <<<JS
$('#loginform-captcha-image').trigger('click');
JS;
$this->registerJs($js, $this::POS_READY);
It's not very pretty, but it works and it's the only way I've found to get aroun d this problem, which has also plagued my own sites.
In your controller, just unset the session of captcha:
session_start();
unset($_SESSION["__captcha/panel/panel-auth/captcha"]);
unset($_SESSION["__captcha/panel/panel-auth/captchacount"]);
This worked for me
$(document).ready(function(){
setTimeout(() => {
$("#form-captcha-image").click();
}, 100);
});
Update Your CaptchaAction as
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => null,
],
];
}
Read Fixed Verify Code
IF fixedVerifyCode if set then captcha is same as value setted in fixedVerifyCode
// code from yii\captcha\CaptchaAction in Yii2
public function getVerifyCode($regenerate = false)
{
if ($this->fixedVerifyCode !== null) {
return $this->fixedVerifyCode;
}
$session = Yii::$app->getSession();
$session->open();
$name = $this->getSessionKey();
if ($session[$name] === null || $regenerate) {
$session[$name] = $this->generateVerifyCode();
$session[$name . 'count'] = 1;
}
return $session[$name];
}