Добавлена возможность загружать изображения в вопросы тестирования

parent f178d010
...@@ -304,32 +304,6 @@ CREATE TABLE IF NOT EXISTS `meta_tags` ( ...@@ -304,32 +304,6 @@ CREATE TABLE IF NOT EXISTS `meta_tags` (
INSERT INTO `meta_tags` (`id`, `object_id`, `model_id`, `language`, `title`, `keywords`, `description`, `created_at`, `updated_at`) VALUES INSERT INTO `meta_tags` (`id`, `object_id`, `model_id`, `language`, `title`, `keywords`, `description`, `created_at`, `updated_at`) VALUES
(6, 1, 'common\\modules\\content\\models\\CoContent', 'ru', 'Это главная', 'Это главная', 'Это главная', 1427531082, 1435822414), (6, 1, 'common\\modules\\content\\models\\CoContent', 'ru', 'Это главная', 'Это главная', 'Это главная', 1427531082, 1435822414),
(36, 24, 'common\\modules\\content\\models\\CoContent', 'ru', '', '', '', 1450859568, 1450859568),
(5, 6, 'common\\modules\\content\\models\\CoContent', 'ru', 'тест', 'тест', 'тест', 1427531082, 1432196320),
(10, 20, 'common\\modules\\content\\models\\CoContent', 'ru', 'Как это работает? - Онлайн выдача займов', 'как это работает', 'как это работает', 1430320024, 1432062111),
(11, 1, 'common\\modules\\faq\\models\\Faq', 'ru', 'Получение займа', 'контакт, система контакт, поступили деньги, как узнать, получение перевода, kontakt', 'Круглосуточная выдача займов нашим клиентам. Быстрые переводы через Контакт.', 1430828849, 1432644694),
(12, 3, 'common\\modules\\faq\\models\\Faq', 'ru', 'Займы под низкий процент круглосуточно', 'займы, погашение, низкий процент, низкий %, займ дешево, взять в долг, ', 'Уменьшение процентной ставки нашим постоянным клиентам. Постоянные акции по снижению процентов. Звоните!', 1430829119, 1430983831),
(13, 4, 'common\\modules\\faq\\models\\Faq', 'ru', 'Погашение займа ', 'погашение займа, возврат займа, вернуть долг, отдать займ, ', 'Возвращайте займы удобным для вас способом. Множество платежных систем. Выгодно и удобно.', 1430829544, 1430984105),
(14, 6, 'common\\modules\\faq\\models\\Faq', 'ru', 'Погашение займа через Киви', 'киви, qiwi, вернуть через киви, возврат без комиссии, быстрый, возврат, займа, ', 'Без комиссии возвращайте займы через платежную систему Киви. Просто и удобно. Никаких дополнительных переплат.', 1430829726, 1430984342),
(15, 7, 'common\\modules\\faq\\models\\Faq', 'ru', 'Займ за границей', 'займ за пределами РФ, за границей, взять, деньги, в другой стране, находясь,', 'Мы выдаем займы нашим клиентам с паспортом РФ в любых странах. Мгновенные переводы через различные платежные системы. Быстро и удобно.', 1430829814, 1430984804),
(16, 8, 'common\\modules\\faq\\models\\Faq', 'ru', 'Начисление пени', 'пени за просрочку, расчет пени, размер пени, ставка пени, пени, просрочка, штрафы, не вернул вовремя, начисление пени, пеней, ', 'Ставка пени минимальная. При погашении займа в срок или при досрочном погашении пени не начисляются. ', 1430829889, 1430985833),
(17, 9, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430829976, 1430830639),
(18, 30, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830077, 1430830647),
(19, 31, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830261, 1430830261),
(20, 35, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830331, 1430830626),
(21, 36, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830383, 1430830607),
(22, 37, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830445, 1430830601),
(23, 38, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830565, 1430830565),
(24, 39, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830714, 1430830714),
(25, 40, 'common\\modules\\faq\\models\\Faq', 'ru', 'Title', 'Keywords,Keywords', 'Description', 1430830763, 1432738488),
(26, 41, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830793, 1432203673),
(27, 42, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830847, 1430830847),
(28, 43, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830894, 1430830894),
(29, 44, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430830956, 1430830956),
(30, 45, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430831089, 1430831089),
(31, 46, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430832030, 1430832030),
(32, 47, 'common\\modules\\faq\\models\\Faq', 'ru', '', '', '', 1430832533, 1432644664),
(34, 22, 'common\\modules\\content\\models\\CoContent', 'ru', 'Требования к ПО', 'по, требования, работа с сайтом, технические требования, системные требования', 'Технические требования для работы с сайтом ', 1430906924, 1430922337),
(35, 23, 'common\\modules\\content\\models\\CoContent', 'ru', '404 страница не найдена', '404 страница не найдена', '404 страница не найдена', 1432895790, 1432895790); (35, 23, 'common\\modules\\content\\models\\CoContent', 'ru', '404 страница не найдена', '404 страница не найдена', '404 страница не найдена', 1432895790, 1432895790);
-- -------------------------------------------------------- -- --------------------------------------------------------
......
...@@ -164,6 +164,8 @@ JS; ...@@ -164,6 +164,8 @@ JS;
$opt['value'] = $element['value']; $opt['value'] = $element['value'];
if(!empty($element['options']['label'])) if(!empty($element['options']['label']))
$optEl['labelOptions'] = ['label' => $element['options']['label']]; $optEl['labelOptions'] = ['label' => $element['options']['label']];
if(!empty($element['fileOptions']))
$opt = $element['fileOptions'];
if(!empty($element['empty'])) if(!empty($element['empty']))
$opt['value'] = $element['empty']; $opt['value'] = $element['empty'];
switch($element['type']) { switch($element['type']) {
...@@ -248,7 +250,7 @@ JS; ...@@ -248,7 +250,7 @@ JS;
'</div>'; '</div>';
break; break;
case 'file': case 'file':
$config['options'][] = $this->field($this->model, $key, $optEl)->fileInput(); $config['options'][] = $this->field($this->model, $key, $optEl)->fileInput($opt);
break; break;
} }
} }
......
...@@ -7,6 +7,7 @@ use common\components\AdminController; ...@@ -7,6 +7,7 @@ use common\components\AdminController;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use common\modules\testings\models\Question; use common\modules\testings\models\Question;
use common\modules\testings\models\SearchQuestion; use common\modules\testings\models\SearchQuestion;
...@@ -54,9 +55,23 @@ class QuestionAdminController extends AdminController ...@@ -54,9 +55,23 @@ class QuestionAdminController extends AdminController
'Добавить вопрос' 'Добавить вопрос'
]; ];
if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->load(Yii::$app->request->post());
$model->filesUpload = UploadedFile::getInstances($model, 'filesUpload');
if (Yii::$app->request->isPost && $model->validate())
{
if($model->filesUpload)
{
$model->upload();
$model->filesUpload = null;
}
$model->save();
return $this->redirect(['manage']); return $this->redirect(['manage']);
} else { }
else
{
$form = new \common\components\BaseForm('/common/modules/testings/forms/QuestionForm', $model); $form = new \common\components\BaseForm('/common/modules/testings/forms/QuestionForm', $model);
return $this->render('create', [ return $this->render('create', [
'model' => $model, 'model' => $model,
...@@ -75,9 +90,28 @@ class QuestionAdminController extends AdminController ...@@ -75,9 +90,28 @@ class QuestionAdminController extends AdminController
$model = $this->findModel($id); $model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->load(Yii::$app->request->post());
$model->filesUpload = UploadedFile::getInstances($model, 'filesUpload');
if (Yii::$app->request->isPost && $model->validate())
{
if($model->filesUpload)
{
if($model->files)
{
$model->deleteFiles();
}
$model->upload();
$model->filesUpload = null;
}
$model->save();
return $this->redirect(['manage']); return $this->redirect(['manage']);
} else { }
else
{
$form = new \common\components\BaseForm('/common/modules/testings/forms/QuestionForm', $model); $form = new \common\components\BaseForm('/common/modules/testings/forms/QuestionForm', $model);
return $this->render('update', [ return $this->render('update', [
'model' => $model, 'model' => $model,
...@@ -97,8 +131,7 @@ class QuestionAdminController extends AdminController ...@@ -97,8 +131,7 @@ class QuestionAdminController extends AdminController
{ {
$questions = []; $questions = [];
$param = 'карт, изобр, изображение, скриншот, картинка, схема, рисунок, рис'; $param = trim(\common\models\Settings::getValue('testings_questions_with_picture'));
// $param = trim(Setting::getValue('testings_questions_with_picture'));
$words = empty($param) ? array() : explode(',', trim($param)); $words = empty($param) ? array() : explode(',', trim($param));
......
<?php <?php
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\modules\testings\models\Test; use common\modules\testings\models\Test;
use common\modules\testings\models\Theme; use common\modules\testings\models\Theme;
use common\modules\testings\models\Question; use common\modules\testings\models\Question;
$files = '';
if($model->files)
{
foreach ($model->files as $file)
{
$files .= Html::img($file->getUrl(), ['width' => 150]) . ' ';
}
}
$elements = [ $elements = [
'test_id' => [ 'test_id' => [
'type' => 'dropdownlist', 'type' => 'dropdownlist',
...@@ -23,12 +34,14 @@ $elements = [ ...@@ -23,12 +34,14 @@ $elements = [
'type' => 'dropdownlist', 'type' => 'dropdownlist',
'items' => Question::$type_list, 'items' => Question::$type_list,
], ],
// 'files' => [ $files,
// 'type' => 'file_manager', 'filesUpload[]' => [
// 'data_type' => 'any', 'type' => 'file',
// 'title' => 'Файлы для скачивания ', 'fileOptions' => [
// 'tag' => 'files' 'multiple' => true,
// ], 'accept' => 'image/*',
]
],
// 'Ответы' => [ // 'Ответы' => [
// 'title' => 'Ответы', // 'title' => 'Ответы',
// 'type' => 'answers', // 'type' => 'answers',
...@@ -47,6 +60,9 @@ if (\Yii::$app->request->get('test')) ...@@ -47,6 +60,9 @@ if (\Yii::$app->request->get('test'))
return [ return [
'activeForm'=>[ 'activeForm'=>[
'id' => 'testing-question-form', 'id' => 'testing-question-form',
'options' => [
'enctype' => 'multipart/form-data'
],
], ],
'elements' => $elements, 'elements' => $elements,
'buttons' => [ 'buttons' => [
......
...@@ -10,6 +10,7 @@ use common\modules\testings\models\Answer; ...@@ -10,6 +10,7 @@ use common\modules\testings\models\Answer;
use common\modules\testings\models\Theme; use common\modules\testings\models\Theme;
use common\modules\testings\models\Test; use common\modules\testings\models\Test;
use common\modules\testings\models\QuestionPassing; use common\modules\testings\models\QuestionPassing;
use common\modules\testings\models\QuestionImage;
class Question extends \common\components\ActiveRecordModel class Question extends \common\components\ActiveRecordModel
{ {
...@@ -24,6 +25,10 @@ class Question extends \common\components\ActiveRecordModel ...@@ -24,6 +25,10 @@ class Question extends \common\components\ActiveRecordModel
const ACTIVE = 1; const ACTIVE = 1;
const HIDDEN = 0; const HIDDEN = 0;
const IMAGES_FOLDER = '/uploads/questions/';
public $filesUpload;
public static $type_list = [ public static $type_list = [
self::ONE_OPTION => 'Нужно выбрать один вариант', self::ONE_OPTION => 'Нужно выбрать один вариант',
self::FEW_OPTIONS => 'Нужно выбрать несколько вариантов', self::FEW_OPTIONS => 'Нужно выбрать несколько вариантов',
...@@ -54,6 +59,7 @@ class Question extends \common\components\ActiveRecordModel ...@@ -54,6 +59,7 @@ class Question extends \common\components\ActiveRecordModel
'text' => 'Текст вопроса', 'text' => 'Текст вопроса',
'type' => 'Тип вопроса', 'type' => 'Тип вопроса',
'create_date' => 'Время создания', 'create_date' => 'Время создания',
'filesUpload' => 'Изображения'
]; ];
} }
...@@ -65,6 +71,7 @@ class Question extends \common\components\ActiveRecordModel ...@@ -65,6 +71,7 @@ class Question extends \common\components\ActiveRecordModel
return [ return [
[['theme_id', 'test_id', 'text', 'is_active', 'type'], 'required'], [['theme_id', 'test_id', 'text', 'is_active', 'type'], 'required'],
[['theme_id', 'test_id', 'type', 'is_active'], 'integer'], [['theme_id', 'test_id', 'type', 'is_active'], 'integer'],
[['filesUpload'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 4],
]; ];
} }
...@@ -83,6 +90,19 @@ class Question extends \common\components\ActiveRecordModel ...@@ -83,6 +90,19 @@ class Question extends \common\components\ActiveRecordModel
]; ];
} }
public function beforeDelete()
{
if (parent::beforeDelete())
{
$this->deleteFiles();
return true;
}
else
{
return false;
}
}
public function getAnswers() public function getAnswers()
{ {
return $this->hasMany(Answer::className(), ['question_id' => 'id']); return $this->hasMany(Answer::className(), ['question_id' => 'id']);
...@@ -105,10 +125,7 @@ class Question extends \common\components\ActiveRecordModel ...@@ -105,10 +125,7 @@ class Question extends \common\components\ActiveRecordModel
public function getFiles() public function getFiles()
{ {
return $this->hasMany(FileManager::className(), ['object_id' => 'id']) return $this->hasMany(QuestionImage::className(), ['question_id' => 'id']);
->andWhere([FileManager::tableName() . '.model_id' => get_class($this)])
->andWhere([FileManager::tableName() . '.tag' => 'files'])
->orderBy(FileManager::tableName() . '.order DESC');
} }
public function getRightAnswer() public function getRightAnswer()
...@@ -170,4 +187,52 @@ class Question extends \common\components\ActiveRecordModel ...@@ -170,4 +187,52 @@ class Question extends \common\components\ActiveRecordModel
{ {
return \yii\helpers\ArrayHelper::map(Theme::find()->all(), 'id', 'name'); return \yii\helpers\ArrayHelper::map(Theme::find()->all(), 'id', 'name');
} }
public function getPath()
{
return Yii::getAlias('@frontend/web') . self::IMAGES_FOLDER;
}
public function upload()
{
if ($this->validate())
{
if(!file_exists($this->getPath()))
{
mkdir($this->getPath(), 0777, true);
}
foreach ($this->filesUpload as $file)
{
$filename = date('dmYHis-') . uniqid() . '.' . $file->extension;
$file->saveAs($this->getPath() . $filename);
$image = new QuestionImage;
$image->question_id = $this->id;
$image->filename = $filename;
$image->save();
}
return true;
}
else
{
return false;
}
}
public function deleteFiles()
{
if($this->files)
{
foreach ($this->files as $file)
{
if(file_exists($this->getPath() . $file->filename))
{
unlink($this->getPath() . $file->filename);
}
$file->delete();
}
}
}
} }
<?php
namespace common\modules\testings\models;
use Yii;
use common\modules\testings\models\Question;
/**
* This is the model class for table "testings_questions_image".
*
* @property integer $id
* @property integer $question_id
* @property string $filename
*/
class QuestionImage extends \common\components\ActiveRecordModel
{
const PAGE_SIZE = 10;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'testings_questions_image';
}
public function name()
{
return 'Изображения для вопросов';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['question_id', 'filename'], 'required'],
[['question_id'], 'integer'],
[['filename'], 'string', 'max' => 50],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'question_id' => 'Вопрос',
'filename' => 'Изображение',
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
];
}
public function getQuestion()
{
return $this->hasOne(Question::className(), ['id' => 'question_id']);
}
public function getUrl()
{
return Yii::$app->params['frontUrl'] . Question::IMAGES_FOLDER . $this->filename;
}
}
<?php
use yii\db\Migration;
class m160128_054103_add_setting_testing extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->insert('settings', [
'module_id' => 'testings',
'code' => 'testings_questions_with_picture',
'name' => 'Ключевые слова для загрузки картинки в вопрос',
'value' => 'карт, изобр, изображение, скриншот, картинка, схема, рисунок, рис',
'element' => 'text',
'hidden' => 0,
'description' => 'Ключевые слова для загрузки картинки в вопрос',
]);
}
public function safeDown()
{
$this->delete('settings', ['code' => 'testings_questions_with_picture']);
}
}
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160128_055509_add_testings_question_files extends Migration
{
public function safeUp()
{
$this->createTable(
'testings_questions_image',
[
'id' => Schema::TYPE_PK,
'question_id' => Schema::TYPE_INTEGER.'(11) NOT NULL',
'filename' => Schema::TYPE_STRING.'(50) NOT NULL',
]
);
$this->addForeignKey(
'fk_questions_image_question_id_question_id',
'testings_questions_image', 'question_id',
'testings_questions', 'id'
);
}
public function safeDown()
{
$this->dropForeignKey('fk_questions_image_question_id_question_id', 'testings_questions_image');
$this->dropTable('testings_questions_image');
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment