I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron
Related
I have a problem with my old website. Now I try to move it to new server (php5.6) and when i try to save data I have error:
Request blackholed due to "auth" violation.
I serach the place whose do it this error:
if ($this->Node->saveWithMeta($this->request->data)) {
Croogo::dispatchEvent('Controller.Nodes.afterAdd', $this, array('data' => $this->request->data));
$this->Session->setFlash(__('%s has been saved', $type['Type']['title']), 'default', array('class' => 'success'));
if (isset($this->request->data['apply'])) {
$this->redirect(array('action' => 'edit', $this->Node->id));
} else {
$this->redirect(array('action' => 'index'));
}
}
I think error do function saveWithMeta(). This function view like:
public function saveWithMeta(Model $model, $data, $options = array()) {
$data = $this->_prepareMeta($data);
return $model->saveAll($data, $options);
}
Can I replace/edit this function so that it starts to work?
edit
if (!$db->create($this, $fields, $values)) {
$success = $created = false;
} else {
$created = true;
}
These lines cause an error.
Am new to Yii, this is the login function (path /basic/controllers/siteController.php), once the users is logged in it will render the login template.
After a user is logged in,
How to get the SESSION ID and store to DB. ?
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
And the model code (path /models/LoginForm.php)
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
$session = Yii::$app->session->getId();
Will grab the Id. There is a good article on sessions here http://www.bsourcecode.com/yiiframework2/session-handling-in-yii-framework-2-0/
And to save something like:
$model->session = $session;
$model->save();
Hi can someone know this i am beginner in Cakephp i tried to upload multiple images but it wont save.
Controller:
public function add() {
if ($this->request->is('post')) {
//$data = $this->request->getData();
if(!empty($_FILES['photo']['name'])){
$count = count($_FILES['photo']['name']);
for ($i=0; $i < $count; $i++) {
$filename = $_FILES['photo']['name'][$i];
$type = $_FILES['photo']['type'][$i];
$tmp = $_FILES['photo']['tmp_name'][$i];
$error = $_FILES['photo']['error'][$i];
$size = $_FILES['photo']['size'][$i];
$uploadPath = '../uploads/files/';
$file[$i]['user_id'] = $this->Auth->user('id');
$file[$i]['filename'] = $filename;
$file[$i]['file_location'] = $uploadPath;
$file[$i]['file_type'] = $type;
$file[$i]['file_size'] = $size;
$file[$i]['file_status'] = 'Active';
$file[$i]['created'] = date("Y-m-d H:i:s");
$file[$i]['modified'] = date("Y-m-d H:i:s");
}
$table = TableRegistry::get('files');
$entities = $table->newEntities($file);
if($table->saveMany($entities)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
but when i tried to debug all good but in saving it wont work! does my code has problem, can someone help me how to fix my add function
View:
echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']);
You are trying to save one record once using saveMany().
public function add()
{
if ($this->request->is('post')) {
$table = TableRegistry::get('files');
$uploadPath = '../uploads/files/';
if(!empty($_FILES['photo'])){
foreach ($_FILES['photo'] as $EachPhoto) {
$data[] = [
'user_id' => $this->Auth->user('id'),
'filename' => $EachPhoto['name'],
'file_location' => $uploadPath,
'file_type' => $EachPhoto['type'],
'file_size' => $EachPhoto['size'],
'file_status' => 'Active',
'created' => date("Y-m-d H:i:s")
];
}
$entities = $table->newEntities($data);
if($this->Files->saveMany($entitie)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
I have created ..\frontend\web\uploads.
This is the function Create in PropertiesControllers.php configuration that I have:
public function actionCreate()
{
$model = new Properties();
$date = date('YmdHis');
if ($model->load(Yii::$app->request->post())) {
$file = \yii\web\UploadedFile::getInstance($model, 'url_img');
if (!empty($file))
$model->url_img = $date.$file;
if($model->save())
{
if (!empty($file))
$file->saveAs( Yii::getAlias('#frontend') .'/web/uploads/'.$date.$file);
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', ['model' => $model]);
} else {
return $this->render('create', ['model' => $model]);
}
}
It works when uploads is existed. But I want to redirect to new folder in uploads as uploads\img
if (!empty($file))
$file->saveAs( Yii::getAlias('#frontend') .'/web/uploads/img'.$date.$file);
It show error because ../web/uploads/img is not existed.
I don't know to solve this issue. Help me!
I suggest you to create the img folder before $file->saveAs(. In Yii2,you can make use of yii\helpers\FileHelper to create a directory. If your problem is like img folder does not exists inside uploads,then you can create the folder with yii\helpers\FileHelper as
$path = Yii::getAlias('#frontend')."/web/uploads/img";
\yii\helpers\FileHelper::createDirectory($path, $mode = 0775, $recursive = true);
Full code
public function actionCreate() {
$model = new Properties();
$date = date('YmdHis');
if ($model->load(Yii::$app->request->post())) {
$file = \yii\web\UploadedFile::getInstance($model, 'url_img');
if (!empty($file))
$model->url_img = $date . $file;
if ($model->save()) {
if (!empty($file)) {
$path = Yii::getAlias('#frontend') . "/web/uploads/img";
//here you create the folder
if (\yii\helpers\FileHelper::createDirectory($path, $mode = 0775, $recursive = true)) {
$file->saveAs(Yii::getAlias('#frontend') . '/web/uploads/img/' . $date . $file);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', ['model' => $model]);
} else {
return $this->render('create', ['model' => $model]);
}
}
More info about FileHelper here http://www.yiiframework.com/doc-2.0/yii-helpers-filehelper.html
I got this method that's intended to upload a file, but sometimes it does so when $this->imageFile is not instantiated. I have no idea why.
public function upload()
{
$path = Url::to('#webroot/images/photos/');
$filename = strtolower($this->username) . '.jpg';
$this->imageFile->saveAs($path . $filename);
return true;
}
I call the method upload() in beforeSave() like this:
public function beforeSave($insert)
{
if(parent::beforeSave($insert)){
if($this->isNewRecord)
{
$this->password = Yii::$app->security->generatePasswordHash($this->password);
}
$this->upload();
return true;
}
else
{
return false;
}
}
I called this method like 100 times with mixed results. I have no idea why this method call doesn't give the same result. It should either never work or always work, but for some reason the code is not deterministic at all.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Another thing, when I use this code, I get a file, but the username is blank so I get a .jpeg file without a name.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$model->upload();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
<?php
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
In the If clause you are redirecting to view and $model disappears between requests naturally. But in else you sending $model to view directly. It looks like the buggy section.
The other one, when you move the $model->upload() to actionCreate, you are placing it before If statement but you are loading the post to the model in if clause so, naturally user wasn't loading when you are trying to upload.
If you are prefer to send $model->upload() to action just be sure to call following method before upload. $model->load(Yii::$app->request->post())