first
This commit is contained in:
163
kernel/app_modules/user_custom_fields/UserCustomFieldsModule.php
Normal file
163
kernel/app_modules/user_custom_fields/UserCustomFieldsModule.php
Normal file
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use itguild\forms\builders\SelectBuilder;
|
||||
use itguild\forms\builders\TextInputBuilder;
|
||||
use kernel\app_modules\tag\models\Tag;
|
||||
use kernel\app_modules\tag\service\TagEntityService;
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
|
||||
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
|
||||
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
|
||||
use kernel\app_modules\user_custom_fields\services\UserCustomValuesService;
|
||||
use kernel\EntityRelation;
|
||||
use kernel\helpers\Debug;
|
||||
use kernel\Module;
|
||||
use kernel\modules\menu\service\MenuService;
|
||||
use kernel\Request;
|
||||
use kernel\services\MigrationService;
|
||||
|
||||
class UserCustomFieldsModule extends Module
|
||||
{
|
||||
|
||||
public MenuService $menuService;
|
||||
|
||||
public MigrationService $migrationService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->menuService = new MenuService();
|
||||
$this->migrationService = new MigrationService();
|
||||
}
|
||||
|
||||
public function init(): void
|
||||
{
|
||||
$this->migrationService->runAtPath("{KERNEL_APP_MODULES}/user_custom_fields/migrations");
|
||||
|
||||
$this->menuService->createItem([
|
||||
"label" => "Доп. поля пользователей",
|
||||
"url" => "/admin/custom_field",
|
||||
"slug" => "custom_field",
|
||||
]);
|
||||
|
||||
$this->menuService->createItem([
|
||||
"label" => "Список",
|
||||
"url" => "/admin/custom_field",
|
||||
"slug" => "custom_field_list",
|
||||
"parent_slug" => "custom_field"
|
||||
]);
|
||||
|
||||
$this->menuService->createItem([
|
||||
"label" => "Значения",
|
||||
"url" => "/admin/custom_field/user_values",
|
||||
"slug" => "custom_field_user_values",
|
||||
"parent_slug" => "custom_field"
|
||||
]);
|
||||
|
||||
EntityRelation::addEntityRelation('user', 'user_custom_fields');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function deactivate(): void
|
||||
{
|
||||
$this->migrationService->rollbackAtPath("{KERNEL_APP_MODULES}/user_custom_fields/migrations");
|
||||
$this->menuService->removeItemBySlug("custom_field_user_values");
|
||||
$this->menuService->removeItemBySlug("custom_field_list");
|
||||
$this->menuService->removeItemBySlug("custom_field");
|
||||
|
||||
EntityRelation::removePropertyFromEntityRelations('user', 'user_custom_fields');
|
||||
}
|
||||
|
||||
public function formInputs(string $entity, Model $model = null): void
|
||||
{
|
||||
$fields = CustomFieldService::getCustomFields();
|
||||
|
||||
foreach ($fields as $field) {
|
||||
/* @var CustomField $field */
|
||||
if (isset($model->id)) {
|
||||
$value = UserCustomValuesService::getValueByFieldAndUser($field->id, $model->id);
|
||||
}
|
||||
|
||||
if ($field->type === "string"){
|
||||
$input = TextInputBuilder::build($field->slug, [
|
||||
'class' => 'form-control',
|
||||
'placeholder' => $field->label,
|
||||
'value' => $value->value ?? '',
|
||||
]);
|
||||
}
|
||||
else {
|
||||
$options = explode(", ", $field->field_options);
|
||||
$options = array_combine($options, $options);
|
||||
$input = SelectBuilder::build($field->slug, [
|
||||
'class' => 'form-control',
|
||||
'placeholder' => $field->label,
|
||||
'value' => $value->value ?? '',
|
||||
])->setOptions($options);
|
||||
}
|
||||
$input->setLabel($field->label);
|
||||
$input->create()->render();
|
||||
}
|
||||
}
|
||||
|
||||
public function saveInputs(string $entity, Model $model, Request $request): void
|
||||
{
|
||||
$service = new UserCustomValuesService();
|
||||
$form = new CreateUserCustomValueForm();
|
||||
$fields = CustomFieldService::getCustomFields();
|
||||
|
||||
foreach ($fields as $field){
|
||||
/* @var CustomField $field */
|
||||
if (isset($request->data[$field->slug])){
|
||||
UserCustomValuesService::deleteByUserAndField($model->id, $field->id);
|
||||
$form->load([
|
||||
'user_id' => $model->id,
|
||||
'custom_field_id' => $field->id,
|
||||
'value' => $request->data[$field->slug]
|
||||
]);
|
||||
$service->create($form);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getItem(string $entity, string $entity_id): string
|
||||
{
|
||||
$fields = UserCustomValuesService::getValuesByUserId($entity_id);
|
||||
$fieldsArr = [];
|
||||
foreach ($fields as $field){
|
||||
/* @var UserCustomValues $field */
|
||||
$fieldsArr[$field->customField->label] = $field->value;
|
||||
}
|
||||
$string = implode(', ', array_map(
|
||||
function ($key, $value) {
|
||||
return "$key: $value";
|
||||
},
|
||||
array_keys($fieldsArr),
|
||||
$fieldsArr
|
||||
));
|
||||
|
||||
return $string;
|
||||
}
|
||||
|
||||
public function getItems(string $entity, Model $model): string
|
||||
{
|
||||
$fields = UserCustomValuesService::getValuesByUserId($model->id);
|
||||
$fieldsArr = [];
|
||||
foreach ($fields as $field){
|
||||
/* @var UserCustomValues $field */
|
||||
$fieldsArr[$field->customField->label] = $field->value;
|
||||
}
|
||||
$string = implode(', ', array_map(
|
||||
function ($key, $value) {
|
||||
return "$key: $value";
|
||||
},
|
||||
array_keys($fieldsArr),
|
||||
$fieldsArr
|
||||
));
|
||||
|
||||
return $string;
|
||||
}
|
||||
}
|
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\controllers;
|
||||
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\NoReturn;
|
||||
use kernel\AdminController;
|
||||
use kernel\app_modules\user_custom_fields\models\forms\CreateCustomFieldForm;
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
|
||||
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
|
||||
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
|
||||
use kernel\app_modules\user_custom_fields\services\UserCustomValuesService;
|
||||
use kernel\Flash;
|
||||
use kernel\helpers\Debug;
|
||||
|
||||
class UserCustomFieldsController extends AdminController
|
||||
{
|
||||
private CustomFieldService $user_custom_fieldsService;
|
||||
protected function init(): void
|
||||
{
|
||||
parent::init();
|
||||
$this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/user_custom_fields/views/";
|
||||
$this->user_custom_fieldsService = new CustomFieldService();
|
||||
}
|
||||
|
||||
public function actionCreate(): void
|
||||
{
|
||||
$this->cgView->render("form.php");
|
||||
}
|
||||
|
||||
#[NoReturn] public function actionAdd(): void
|
||||
{
|
||||
$user_custom_fieldsForm = new CreateCustomFieldForm();
|
||||
$user_custom_fieldsForm->load($_REQUEST);
|
||||
if ($user_custom_fieldsForm->validate()){
|
||||
$user_custom_fields = $this->user_custom_fieldsService->create($user_custom_fieldsForm);
|
||||
if ($user_custom_fields){
|
||||
$this->redirect("/admin/custom_field/view/" . $user_custom_fields->id);
|
||||
}
|
||||
}
|
||||
Flash::setMessage("error", $user_custom_fieldsForm->getErrorsStr());
|
||||
$this->redirect("/admin/custom_field/create");
|
||||
}
|
||||
|
||||
public function actionIndex($page_number = 1): void
|
||||
{
|
||||
$this->cgView->render("index.php", ['page_number' => $page_number]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function actionView($id): void
|
||||
{
|
||||
$user_custom_fields = CustomField::find($id);
|
||||
|
||||
if (!$user_custom_fields){
|
||||
throw new Exception(message: "The user_custom_fields not found");
|
||||
}
|
||||
$this->cgView->render("view.php", ['user_custom_fields' => $user_custom_fields]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function actionUpdate($id): void
|
||||
{
|
||||
$model = CustomField::find($id);
|
||||
if (!$model){
|
||||
throw new Exception(message: "The user_custom_fields not found");
|
||||
}
|
||||
|
||||
$this->cgView->render("form.php", ['model' => $model]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function actionEdit($id): void
|
||||
{
|
||||
$user_custom_fields = CustomField::find($id);
|
||||
if (!$user_custom_fields){
|
||||
throw new Exception(message: "The user_custom_fields not found");
|
||||
}
|
||||
$user_custom_fieldsForm = new CreateCustomFieldForm();
|
||||
$user_custom_fieldsService = new CustomFieldService();
|
||||
$user_custom_fieldsForm->load($_REQUEST);
|
||||
if ($user_custom_fieldsForm->validate()) {
|
||||
$user_custom_fields = $user_custom_fieldsService->update($user_custom_fieldsForm, $user_custom_fields);
|
||||
if ($user_custom_fields) {
|
||||
$this->redirect("/admin/custom_field/view/" . $user_custom_fields->id);
|
||||
}
|
||||
}
|
||||
$this->redirect("/admin/custom_field/update/" . $id);
|
||||
}
|
||||
|
||||
#[NoReturn] public function actionDelete($id): void
|
||||
{
|
||||
$user_custom_fields = CustomField::find($id)->first();
|
||||
$user_custom_fields->delete();
|
||||
$this->redirect("/admin/custom_field/");
|
||||
}
|
||||
|
||||
public function actionUserCustomValuesList($page_number = 1): void
|
||||
{
|
||||
$this->cgView->render("values_index.php", ['page_number' => $page_number]);
|
||||
}
|
||||
|
||||
public function actionCreateUserCustomValues(): void
|
||||
{
|
||||
$this->cgView->render("values_form.php");
|
||||
}
|
||||
|
||||
#[NoReturn] public function actionAddUserCustomValues(): void
|
||||
{
|
||||
$service = new UserCustomValuesService();
|
||||
$form = new CreateUserCustomValueForm();
|
||||
$form->load($_REQUEST);
|
||||
|
||||
UserCustomValuesService::deleteByUserAndField($form->getItem('user_id'), $form->getItem('custom_field_id'));
|
||||
|
||||
if ($form->validate()){
|
||||
$model = $service->create($form);
|
||||
if ($model){
|
||||
$this->redirect("/admin/custom_field/user_values");
|
||||
}
|
||||
}
|
||||
Flash::setMessage("error", $form->getErrorsStr());
|
||||
$this->redirect("/admin/custom_field/user_values");
|
||||
}
|
||||
|
||||
#[NoReturn] public function actionDeleteUserCustomValues($id): void
|
||||
{
|
||||
$user_custom_values = UserCustomValues::find($id)->first();
|
||||
$user_custom_values->delete();
|
||||
Flash::setMessage("success", "Запись удалена");
|
||||
$this->redirect("/admin/custom_field/user_values");
|
||||
}
|
||||
}
|
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public string $migration;
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
\kernel\App::$db->schema->create('custom_field', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('slug')->unique(); // Название поля (например, 'phone')
|
||||
$table->string('type')->default('string'); // Тип поля (string, integer, boolean и т.д.)
|
||||
$table->string('entity')->nullable(true); // Сущность (user, post и т.д.)
|
||||
$table->string('label'); // Человекочитаемое название
|
||||
$table->text('field_options'); // Человекочитаемое название
|
||||
$table->integer('status')->default(1);
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
\kernel\App::$db->schema->create('user_custom_values', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('user_id');
|
||||
$table->unsignedBigInteger('custom_field_id');
|
||||
$table->text('value')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
// $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
|
||||
// $table->foreign('custom_field_id')->references('id')->on('custom_field')->onDelete('cascade');
|
||||
|
||||
// $table->unique(['user_id', 'custom_field_id']); // Уникальная пара пользователь-поле
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
\kernel\App::$db->schema->dropIfExists('user_custom_values');
|
||||
\kernel\App::$db->schema->dropIfExists('custom_field');
|
||||
}
|
||||
};
|
72
kernel/app_modules/user_custom_fields/models/CustomField.php
Normal file
72
kernel/app_modules/user_custom_fields/models/CustomField.php
Normal file
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
// Добавить @property
|
||||
/**
|
||||
* @property int $id
|
||||
* @property int $status
|
||||
* @property string $slug
|
||||
* @property string $label
|
||||
* @property string $type
|
||||
* @property string $entity
|
||||
* @property string $field_options
|
||||
*/
|
||||
class CustomField extends Model
|
||||
{
|
||||
const DISABLE_STATUS = 0;
|
||||
const ACTIVE_STATUS = 1;
|
||||
|
||||
const TYPE_STRING = 'string';
|
||||
|
||||
const TYPE_SELECT = 'select';
|
||||
|
||||
protected $table = 'custom_field';
|
||||
|
||||
protected $fillable = ['slug', 'label', 'type', 'entity', 'field_options', 'status']; // Заполнить массив. Пример: ['label', 'slug', 'status']
|
||||
|
||||
public static function labels(): array
|
||||
{
|
||||
// Заполнить массив
|
||||
// Пример: [
|
||||
// 'label' => 'Заголовок',
|
||||
// 'entity' => 'Сущность',
|
||||
// 'slug' => 'Slug',
|
||||
// 'status' => 'Статус',
|
||||
// ]
|
||||
|
||||
return [
|
||||
'slug' => 'Slug',
|
||||
'label' => 'Название',
|
||||
'type' => 'Тип',
|
||||
'entity' => 'Сущность',
|
||||
'field_options' => 'Опции поля',
|
||||
'status' => 'Статус',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getStatus(): array
|
||||
{
|
||||
return [
|
||||
self::DISABLE_STATUS => "Не активный",
|
||||
self::ACTIVE_STATUS => "Активный",
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getTypes(): array
|
||||
{
|
||||
return [
|
||||
self::TYPE_STRING => 'Текст',
|
||||
self::TYPE_SELECT => 'Список',
|
||||
];
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use kernel\modules\user\models\User;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property int $user_id
|
||||
* @property int $custom_field_id
|
||||
* @property string $value
|
||||
* @property string $created_at
|
||||
* @property string $updated_at
|
||||
*/
|
||||
class UserCustomValues extends Model
|
||||
{
|
||||
|
||||
const DISABLE_STATUS = 0;
|
||||
const ACTIVE_STATUS = 1;
|
||||
|
||||
protected $table = 'user_custom_values';
|
||||
|
||||
protected $fillable = ['user_id', 'custom_field_id', 'value'];
|
||||
|
||||
public static function labels(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => 'ID пользователя',
|
||||
'custom_field_id' => 'ID кастомного поля',
|
||||
'value' => 'Значение',
|
||||
'created_at' => 'Дата создания',
|
||||
'updated_at' => 'Дата обновления',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getStatus(): array
|
||||
{
|
||||
return [
|
||||
self::DISABLE_STATUS => "Не активный",
|
||||
self::ACTIVE_STATUS => "Активный",
|
||||
];
|
||||
}
|
||||
|
||||
public function customField(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CustomField::class);
|
||||
}
|
||||
|
||||
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\models\forms;
|
||||
|
||||
use kernel\FormModel;
|
||||
|
||||
class CreateCustomFieldForm extends FormModel
|
||||
{
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
// Заполнить массив правил
|
||||
// Пример:
|
||||
// return [
|
||||
// 'label' => 'required|min-str-len:5|max-str-len:30',
|
||||
// 'entity' => 'required',
|
||||
// 'slug' => '',
|
||||
// 'status' => ''
|
||||
// ];
|
||||
return [
|
||||
'slug' => 'required|min-str-len:3|max-str-len:30',
|
||||
'label' => 'required|min-str-len:3|max-str-len:50',
|
||||
'type' => 'required|min-str-len:3|max-str-len:30',
|
||||
'entity' => 'required|min-str-len:3|max-str-len:30',
|
||||
'field_options' => '',
|
||||
'status' => '',
|
||||
];
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\models\forms;
|
||||
|
||||
use kernel\FormModel;
|
||||
|
||||
class CreateUserCustomValueForm extends FormModel
|
||||
{
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
// Заполнить массив правил
|
||||
// Пример:
|
||||
// return [
|
||||
// 'label' => 'required|min-str-len:5|max-str-len:30',
|
||||
// 'entity' => 'required',
|
||||
// 'slug' => '',
|
||||
// 'status' => ''
|
||||
// ];
|
||||
return [
|
||||
'user_id' => 'required|integer|min:1',
|
||||
'custom_field_id' => 'required|integer|min:1',
|
||||
'value' => '',
|
||||
];
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use kernel\App;
|
||||
use kernel\CgRouteCollector;
|
||||
use Phroute\Phroute\RouteCollector;
|
||||
|
||||
App::$collector->group(["prefix" => "admin"], function (CgRouteCollector $router) {
|
||||
App::$collector->group(["before" => "auth"], function (RouteCollector $router) {
|
||||
App::$collector->group(["prefix" => "custom_field"], function (CGRouteCollector $router) {
|
||||
App::$collector->get('/', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionIndex']);
|
||||
App::$collector->get('/page/{page_number}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionIndex']);
|
||||
App::$collector->get('/create', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionCreate']);
|
||||
App::$collector->post("/", [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionAdd']);
|
||||
App::$collector->get('/view/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionView']);
|
||||
App::$collector->any('/update/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionUpdate']);
|
||||
App::$collector->any("/edit/{id}", [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionEdit']);
|
||||
App::$collector->get('/delete/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionDelete']);
|
||||
App::$collector->get('/user_values', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionUserCustomValuesList']);
|
||||
App::$collector->post('/user_values', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionAddUserCustomValues']);
|
||||
App::$collector->get('/user_values/create', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionCreateUserCustomValues']);
|
||||
App::$collector->get('/user_values/delete/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionDeleteUserCustomValues']);
|
||||
});
|
||||
});
|
||||
});
|
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\services;
|
||||
|
||||
use itguild\forms\builders\SelectBuilder;
|
||||
use itguild\forms\builders\TextInputBuilder;
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
use kernel\app_modules\user_custom_fields\models\forms\CreateCustomFieldForm;
|
||||
use kernel\FormModel;
|
||||
|
||||
class CustomFieldService
|
||||
{
|
||||
public function create(FormModel $form_model): false|CustomField
|
||||
{
|
||||
$model = new CustomField();
|
||||
// Пример заполнения:
|
||||
$model->slug = $form_model->getItem('slug');
|
||||
$model->label = $form_model->getItem('label');
|
||||
$model->type = $form_model->getItem('type');
|
||||
$model->entity = $form_model->getItem('entity');
|
||||
$model->field_options = $form_model->getItem('field_options');
|
||||
$model->status = $form_model->getItem('status');
|
||||
|
||||
if ($model->save()) {
|
||||
return $model;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function update(FormModel $form_model, CustomField $custom_field): false|CustomField
|
||||
{
|
||||
// Пример обновления:
|
||||
$custom_field->slug = $form_model->getItem('slug');
|
||||
$custom_field->label = $form_model->getItem('label');
|
||||
$custom_field->type = $form_model->getItem('type');
|
||||
$custom_field->entity = $form_model->getItem('entity');
|
||||
$custom_field->field_options = $form_model->getItem('field_options');
|
||||
$custom_field->status = $form_model->getItem('status');
|
||||
|
||||
if ($custom_field->save()) {
|
||||
return $custom_field;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getCustomFields()
|
||||
{
|
||||
$model = CustomField::where(['entity' => 'user'])->where(['status' => CustomField::ACTIVE_STATUS])->get();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
public static function getList(): array
|
||||
{
|
||||
return CustomField::select('id', 'label')->get()
|
||||
->pluck('label', 'id')
|
||||
->toArray();
|
||||
|
||||
}
|
||||
|
||||
public static function getCustomFieldHtml(CustomField $field, int $userId)
|
||||
{
|
||||
$value = UserCustomValuesService::getValueByFieldAndUser($field->id, $userId);
|
||||
|
||||
if ($field->type === "string"){
|
||||
$input = TextInputBuilder::build($field->slug, [
|
||||
'class' => 'form-control',
|
||||
'placeholder' => $field->label,
|
||||
'value' => $value->value ?? '',
|
||||
]);
|
||||
}
|
||||
else {
|
||||
$options = explode(", ", $field->field_options);
|
||||
$options = array_combine($options, $options);
|
||||
$input = SelectBuilder::build($field->slug, [
|
||||
'class' => 'form-control',
|
||||
'placeholder' => $field->label,
|
||||
'value' => $value->value ?? '',
|
||||
])->setOptions($options);
|
||||
}
|
||||
$input->setLabel($field->label);
|
||||
|
||||
return $input->create()->fetch();
|
||||
}
|
||||
|
||||
public static function getOrCreateBySlug(string $slug): CustomField
|
||||
{
|
||||
$model = CustomField::where('slug', $slug)->first();
|
||||
if (!$model) {
|
||||
$form = new CreateCustomFieldForm();
|
||||
$service = new self();
|
||||
$form->load([
|
||||
'slug' => $slug,
|
||||
'label' => $slug,
|
||||
'entity' => 'user',
|
||||
'type' => 'string',
|
||||
]);
|
||||
$model = $service->create($form);
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\services;
|
||||
|
||||
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
|
||||
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
|
||||
use kernel\FormModel;
|
||||
|
||||
class UserCustomValuesService
|
||||
{
|
||||
public function create(FormModel $form_model): false|UserCustomValues
|
||||
{
|
||||
$model = new UserCustomValues();
|
||||
$model->user_id = $form_model->getItem('user_id');
|
||||
$model->custom_field_id = $form_model->getItem('custom_field_id');
|
||||
$model->value = $form_model->getItem('value');
|
||||
|
||||
if ($model->save()) {
|
||||
return $model;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function update(FormModel $form_model, UserCustomValues $user_custom_value): false|UserCustomValues
|
||||
{
|
||||
$user_custom_value->user_id = $form_model->getItem('user_id');
|
||||
$user_custom_value->custom_field_id = $form_model->getItem('custom_field_id');
|
||||
$user_custom_value->value = $form_model->getItem('value');
|
||||
|
||||
if ($user_custom_value->save()) {
|
||||
return $user_custom_value;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getValuesByUserId(int $user_id): \Illuminate\Database\Eloquent\Collection
|
||||
{
|
||||
return UserCustomValues::with(['customField'])->where(['user_id' => $user_id])->get();
|
||||
}
|
||||
|
||||
public static function getValueByFieldAndUser(int $custom_field_id, int $user_id): UserCustomValues|null
|
||||
{
|
||||
return UserCustomValues::where([
|
||||
'custom_field_id' => $custom_field_id,
|
||||
'user_id' => $user_id
|
||||
])->first();
|
||||
}
|
||||
|
||||
public static function deleteByUserAndField(int $user_id, int $custom_field_id): bool
|
||||
{
|
||||
$record = self::getValueByFieldAndUser($custom_field_id, $user_id);
|
||||
|
||||
if ($record) {
|
||||
return $record->delete();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function save(int $userId, string $slug, string $value): UserCustomValues
|
||||
{
|
||||
$customField = CustomFieldService::getOrCreateBySlug($slug);
|
||||
$model = UserCustomValues::where('user_id', $userId)->where('custom_field_id', $customField->id)->first();
|
||||
if (!$model) {
|
||||
$service = new self();
|
||||
$form = new CreateUserCustomValueForm();
|
||||
$form->load([
|
||||
'custom_field_id' => $customField->id,
|
||||
'user_id' => $userId,
|
||||
'value' => $value,
|
||||
]);
|
||||
$model = $service->create($form);
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
96
kernel/app_modules/user_custom_fields/views/form.php
Normal file
96
kernel/app_modules/user_custom_fields/views/form.php
Normal file
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* @var CustomField $model
|
||||
*/
|
||||
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
|
||||
$form = new \itguild\forms\ActiveForm();
|
||||
$form->beginForm(isset($model) ? "/admin/custom_field/edit/" . $model->id : "/admin/custom_field", 'multipart/form-data');
|
||||
|
||||
// Пример формы:
|
||||
|
||||
|
||||
$form->field(\itguild\forms\inputs\TextInput::class, 'slug', [
|
||||
'class' => "form-control",
|
||||
'placeholder' => 'Slug',
|
||||
'value' => $model->slug ?? ''
|
||||
])
|
||||
->setLabel("Slug")
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\TextInput::class, 'label', [
|
||||
'class' => "form-control",
|
||||
'placeholder' => 'Название поля',
|
||||
'value' => $model->label ?? ''
|
||||
])
|
||||
->setLabel("Название поля")
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\Select::class, 'type', [
|
||||
'class' => "form-control",
|
||||
'value' => $model->type ?? ''
|
||||
])
|
||||
->setLabel("Тип")
|
||||
->setOptions(CustomField::getTypes())
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\TextInput::class, 'entity', [
|
||||
'class' => "form-control",
|
||||
'placeholder' => 'Сущность',
|
||||
'value' => $model->entity ?? ''
|
||||
])
|
||||
->setLabel("Сущность")
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\TextArea::class, 'field_options', [
|
||||
'class' => "form-control",
|
||||
'placeholder' => 'Вариант 1, Вариант2, Вариант 3',
|
||||
'value' => $model->field_options ?? ''
|
||||
])
|
||||
->setLabel("Опции поля (через запятую)")
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\Select::class, 'status', [
|
||||
'class' => "form-control",
|
||||
'value' => $model->status ?? ''
|
||||
])
|
||||
->setLabel("Статус")
|
||||
->setOptions(CustomField::getStatus())
|
||||
->render();
|
||||
|
||||
/*
|
||||
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
|
||||
'class' => "form-control",
|
||||
'value' => $model->user_id ?? ''
|
||||
])
|
||||
->setLabel("Пользователи")
|
||||
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
|
||||
->render();
|
||||
*/
|
||||
|
||||
?>
|
||||
<div class="row">
|
||||
<div class="col-sm-2">
|
||||
<?php
|
||||
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
|
||||
'class' => "btn btn-primary ",
|
||||
'value' => 'Отправить',
|
||||
'typeInput' => 'submit'
|
||||
])
|
||||
->render();
|
||||
?>
|
||||
</div>
|
||||
<div class="col-sm-2">
|
||||
<?php
|
||||
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
|
||||
'class' => "btn btn-warning",
|
||||
'value' => 'Сбросить',
|
||||
'typeInput' => 'reset'
|
||||
])
|
||||
->render();
|
||||
?>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
$form->endForm();
|
78
kernel/app_modules/user_custom_fields/views/index.php
Normal file
78
kernel/app_modules/user_custom_fields/views/index.php
Normal file
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @var \Illuminate\Database\Eloquent\Collection $user_custom_fields
|
||||
* @var int $page_number
|
||||
* @var \kernel\CgView $view
|
||||
*/
|
||||
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
use Itguild\EloquentTable\EloquentDataProvider;
|
||||
use Itguild\EloquentTable\ListEloquentTable;
|
||||
use kernel\widgets\IconBtn\IconBtnCreateWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnEditWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnViewWidget;
|
||||
|
||||
$view->setTitle("Список дополнительных полей");
|
||||
$view->setMeta([
|
||||
'description' => 'Список дополнительных полей системы'
|
||||
]);
|
||||
|
||||
//Для использования таблицы с моделью, необходимо создать таблицу в базе данных
|
||||
$table = new ListEloquentTable(new EloquentDataProvider(CustomField::class, [
|
||||
'currentPage' => $page_number,
|
||||
'perPage' => 8,
|
||||
'params' => ["class" => "table table-bordered", "border" => "2"],
|
||||
'baseUrl' => "/admin/custom_field"
|
||||
]));
|
||||
|
||||
|
||||
//$table = new \Itguild\Tables\ListJsonTable(json_encode(
|
||||
// [
|
||||
// 'meta' => [
|
||||
// 'total' => 0,
|
||||
// 'totalWithFilters' => 0,
|
||||
// 'columns' => [
|
||||
// 'title',
|
||||
// 'slug',
|
||||
// 'status',
|
||||
// ],
|
||||
// 'perPage' => 5,
|
||||
// 'currentPage' => 1,
|
||||
// 'baseUrl' => '/admin/some',
|
||||
// 'params' => [
|
||||
// 'class' => 'table table-bordered',
|
||||
// 'border' => 2
|
||||
// ]
|
||||
// ],
|
||||
// 'filters' => [],
|
||||
// 'data' => [],
|
||||
// ]
|
||||
//));
|
||||
|
||||
// Пример фильтра
|
||||
$table->columns([
|
||||
'slug' => [
|
||||
'filter' => [
|
||||
'class' => \Itguild\Tables\Filter\InputTextFilter::class,
|
||||
'value' => $get['title'] ?? ''
|
||||
]
|
||||
],
|
||||
]);
|
||||
|
||||
$table->beforePrint(function () {
|
||||
return IconBtnCreateWidget::create(['url' => '/admin/custom_field/create'])->run();
|
||||
});
|
||||
|
||||
$table->addAction(function($row) {
|
||||
return IconBtnViewWidget::create(['url' => '/admin/custom_field/view/' . $row['id']])->run();
|
||||
});
|
||||
$table->addAction(function($row) {
|
||||
return IconBtnEditWidget::create(['url' => '/admin/custom_field/update/' . $row['id']])->run();
|
||||
});
|
||||
$table->addAction(function($row) {
|
||||
return IconBtnDeleteWidget::create(['url' => '/admin/custom_field/delete/' . $row['id']])->run();
|
||||
});
|
||||
$table->create();
|
||||
$table->render();
|
72
kernel/app_modules/user_custom_fields/views/values_form.php
Normal file
72
kernel/app_modules/user_custom_fields/views/values_form.php
Normal file
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \kernel\app_modules\user_custom_fields\models\UserCustomValues $model
|
||||
*/
|
||||
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
|
||||
$form = new \itguild\forms\ActiveForm();
|
||||
$form->beginForm(isset($model) ? "/admin/custom_field/user_values/edit/" . $model->id : "/admin/custom_field/user_values", 'multipart/form-data');
|
||||
|
||||
// Пример формы:
|
||||
|
||||
$form->field(\itguild\forms\inputs\Select::class, 'user_id', [
|
||||
'class' => "form-control",
|
||||
'value' => $model->user_id ?? ''
|
||||
])
|
||||
->setLabel("Пользователь")
|
||||
->setOptions(\kernel\modules\user\service\UserService::getList())
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\Select::class, 'custom_field_id', [
|
||||
'class' => "form-control",
|
||||
'value' => $model->custom_field_id ?? ''
|
||||
])
|
||||
->setLabel("Поле")
|
||||
->setOptions(\kernel\app_modules\user_custom_fields\services\CustomFieldService::getList())
|
||||
->render();
|
||||
|
||||
$form->field(\itguild\forms\inputs\TextInput::class, 'value', [
|
||||
'class' => "form-control",
|
||||
'placeholder' => 'Значение',
|
||||
'value' => $model->value ?? ''
|
||||
])
|
||||
->setLabel("Значение")
|
||||
->render();
|
||||
|
||||
|
||||
/*
|
||||
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
|
||||
'class' => "form-control",
|
||||
'value' => $model->user_id ?? ''
|
||||
])
|
||||
->setLabel("Пользователи")
|
||||
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
|
||||
->render();
|
||||
*/
|
||||
|
||||
?>
|
||||
<div class="row">
|
||||
<div class="col-sm-2">
|
||||
<?php
|
||||
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
|
||||
'class' => "btn btn-primary ",
|
||||
'value' => 'Отправить',
|
||||
'typeInput' => 'submit'
|
||||
])
|
||||
->render();
|
||||
?>
|
||||
</div>
|
||||
<div class="col-sm-2">
|
||||
<?php
|
||||
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
|
||||
'class' => "btn btn-warning",
|
||||
'value' => 'Сбросить',
|
||||
'typeInput' => 'reset'
|
||||
])
|
||||
->render();
|
||||
?>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
$form->endForm();
|
85
kernel/app_modules/user_custom_fields/views/values_index.php
Normal file
85
kernel/app_modules/user_custom_fields/views/values_index.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @var \Illuminate\Database\Eloquent\Collection $user_custom_fields
|
||||
* @var int $page_number
|
||||
* @var \kernel\CgView $view
|
||||
*/
|
||||
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
use Itguild\EloquentTable\EloquentDataProvider;
|
||||
use Itguild\EloquentTable\ListEloquentTable;
|
||||
use kernel\modules\user\models\User;
|
||||
use kernel\widgets\IconBtn\IconBtnCreateWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnEditWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnViewWidget;
|
||||
|
||||
$view->setTitle("Список значений дополнительных полей");
|
||||
$view->setMeta([
|
||||
'description' => 'Список значений дополнительных полей системы'
|
||||
]);
|
||||
|
||||
//Для использования таблицы с моделью, необходимо создать таблицу в базе данных
|
||||
$table = new ListEloquentTable(new EloquentDataProvider(\kernel\app_modules\user_custom_fields\models\UserCustomValues::class, [
|
||||
'currentPage' => $page_number,
|
||||
'perPage' => 8,
|
||||
'params' => ["class" => "table table-bordered", "border" => "2"],
|
||||
'baseUrl' => "/admin/custom_field"
|
||||
]));
|
||||
|
||||
|
||||
//$table = new \Itguild\Tables\ListJsonTable(json_encode(
|
||||
// [
|
||||
// 'meta' => [
|
||||
// 'total' => 0,
|
||||
// 'totalWithFilters' => 0,
|
||||
// 'columns' => [
|
||||
// 'title',
|
||||
// 'slug',
|
||||
// 'status',
|
||||
// ],
|
||||
// 'perPage' => 5,
|
||||
// 'currentPage' => 1,
|
||||
// 'baseUrl' => '/admin/some',
|
||||
// 'params' => [
|
||||
// 'class' => 'table table-bordered',
|
||||
// 'border' => 2
|
||||
// ]
|
||||
// ],
|
||||
// 'filters' => [],
|
||||
// 'data' => [],
|
||||
// ]
|
||||
//));
|
||||
|
||||
// Пример фильтра
|
||||
$table->columns([
|
||||
'user_id' => [
|
||||
'value' => function ($data) {
|
||||
return User::find($data)->username;
|
||||
},
|
||||
'filter' => [
|
||||
'class' => \kernel\filters\BootstrapSelectFilter::class,
|
||||
'params' => [
|
||||
'options' => \kernel\modules\user\service\UserService::createUsernameArr(),
|
||||
'prompt' => 'Не выбрано'
|
||||
],
|
||||
'value' => $get['user_id'] ?? '',
|
||||
],
|
||||
],
|
||||
'custom_field_id' => [
|
||||
'value' => function ($data) {
|
||||
return CustomField::find($data)->label ?? '';
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
$table->beforePrint(function () {
|
||||
return IconBtnCreateWidget::create(['url' => '/admin/custom_field/user_values/create'])->run();
|
||||
});
|
||||
|
||||
$table->addAction(function($row) {
|
||||
return IconBtnDeleteWidget::create(['url' => '/admin/custom_field/user_values/delete/' . $row['id']])->run();
|
||||
});
|
||||
$table->create();
|
||||
$table->render();
|
25
kernel/app_modules/user_custom_fields/views/view.php
Normal file
25
kernel/app_modules/user_custom_fields/views/view.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @var \Illuminate\Database\Eloquent\Collection $user_custom_fields
|
||||
*/
|
||||
|
||||
use Itguild\EloquentTable\ViewEloquentTable;
|
||||
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
|
||||
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnEditWidget;
|
||||
use kernel\widgets\IconBtn\IconBtnListWidget;
|
||||
|
||||
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($user_custom_fields, [
|
||||
'params' => ["class" => "table table-bordered", "border" => "2"],
|
||||
'baseUrl' => "/admin/user_custom_fields",
|
||||
]));
|
||||
$table->beforePrint(function () use ($user_custom_fields) {
|
||||
$btn = IconBtnListWidget::create(['url' => '/admin/custom_field'])->run();
|
||||
$btn .= IconBtnEditWidget::create(['url' => '/admin/custom_field/update/' . $user_custom_fields->id])->run();
|
||||
$btn .= IconBtnDeleteWidget::create(['url' => '/admin/custom_field/delete/' . $user_custom_fields->id])->run();
|
||||
return $btn;
|
||||
});
|
||||
|
||||
$table->create();
|
||||
$table->render();
|
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace kernel\app_modules\user_custom_fields\widgets;
|
||||
|
||||
use kernel\app_modules\user_custom_fields\models\CustomField;
|
||||
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
|
||||
use kernel\helpers\Debug;
|
||||
use kernel\Widget;
|
||||
|
||||
class UserCustomFieldsInputsWidget extends Widget
|
||||
{
|
||||
|
||||
public function run()
|
||||
{
|
||||
$fields = CustomFieldService::getCustomFields();
|
||||
|
||||
Debug::dd($fields);
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user