slider CRUD

This commit is contained in:
Билай Станислав 2024-12-09 12:57:12 +03:00
parent 95a9b47fd5
commit ccd46636cf
19 changed files with 438 additions and 82 deletions

View File

@ -1,35 +0,0 @@
<?php
namespace app\modules\slider\controllers;
use app\modules\slider\models\Slider;
use Exception;
use kernel\AdminController;
class SliderController extends AdminController
{
protected function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/photo/views/";
}
public function actionIndex($page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
$slide = Slider::find($id);
if (!$slide){
throw new Exception(message: "The slide not found");
}
$this->cgView->render("view.php", ['slider' => $slide]);
}
}

View File

@ -1,13 +0,0 @@
{
"name": "Slider",
"version": "0.1",
"author": "ITGuild",
"slug": "slider",
"type": "entity",
"description": "Slider module",
"app_module_path": "{APP}/modules/{slug}",
"module_class": "app\\modules\\slider\\SliderModule",
"module_class_file": "{APP}/modules/slider/SliderModule.php",
"routs": "routs/slider.php",
"dependence": "menu, user"
}

View File

@ -1,20 +0,0 @@
<?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" => "slider"], function (CGRouteCollector $router) {
App::$collector->get('/', [\app\modules\slider\controllers\SliderController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\app\modules\slider\controllers\SliderController::class, 'actionIndex']);
App::$collector->get('/create', [\app\modules\slider\controllers\SliderController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\slider\controllers\SliderController::class, 'actionAdd']);
App::$collector->get('/view/{id}', [\app\modules\slider\controllers\SliderController::class, 'actionView']);
App::$collector->any('/update/{id}', [\app\modules\slider\controllers\SliderController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\app\modules\slider\controllers\SliderController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\modules\slider\controllers\SliderController::class]);
});
});
});

View File

@ -7,6 +7,7 @@ use kernel\AdminController;
use kernel\Flash; use kernel\Flash;
use kernel\helpers\Debug; use kernel\helpers\Debug;
use kernel\modules\secure\models\forms\LoginForm; use kernel\modules\secure\models\forms\LoginForm;
use kernel\modules\secure\models\forms\RegisterForm;
use kernel\modules\user\service\UserService; use kernel\modules\user\service\UserService;
class SecureController extends AdminController class SecureController extends AdminController
@ -16,7 +17,6 @@ class SecureController extends AdminController
protected function init(): void protected function init(): void
{ {
parent::init(); parent::init();
// $this->cgView->viewPath = KERNEL_DIR . "/views/secure/";
$this->cgView->viewPath = KERNEL_MODULES_DIR. "/secure/views/"; $this->cgView->viewPath = KERNEL_MODULES_DIR. "/secure/views/";
$this->cgView->layout = "/login.php"; $this->cgView->layout = "/login.php";
$this->userService = new UserService(); $this->userService = new UserService();
@ -61,4 +61,31 @@ class SecureController extends AdminController
$this->redirect("/", code: 302); $this->redirect("/", code: 302);
} }
public function actionRegister()
{
$this->cgView->render('register.php');
}
public function actionRegistration(): void
{
$regForm = new RegisterForm();
$regForm->load($_REQUEST);
if ($this->userService->getByField('username', $regForm->getItem("username"))) {
Flash::setMessage("error", "Username already exists.");
$this->redirect("/admin/register", code: 302);
}
if ($this->userService->getByField('email', $regForm->getItem("email"))) {
Flash::setMessage("error", "Email already exists.");
$this->redirect("/admin/register", code: 302);
}
$user = $this->userService->create($regForm);
if ($user){
setcookie('user_id', $user->id, time()+60*60*24, '/', $_SERVER['SERVER_NAME'], false);
$this->redirect("/admin", code: 302);
}
}
} }

View File

@ -0,0 +1,19 @@
<?php
namespace kernel\modules\secure\models\forms;
use kernel\FormModel;
class RegisterForm extends FormModel
{
public function rules(): array
{
return [
'username' => 'required|min-str-len:5|max-str-len:50',
'email' => 'required|email|max-str-len:50',
'password' => 'required|min-str-len:6|max-str-len:50',
];
}
}

View File

@ -14,6 +14,8 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){
App::$collector->get('/login', [\kernel\modules\secure\controllers\SecureController::class, 'actionLogin']); App::$collector->get('/login', [\kernel\modules\secure\controllers\SecureController::class, 'actionLogin']);
App::$collector->get('/logout', [\kernel\modules\secure\controllers\SecureController::class, 'actionLogout']); App::$collector->get('/logout', [\kernel\modules\secure\controllers\SecureController::class, 'actionLogout']);
App::$collector->post('/auth', [\kernel\modules\secure\controllers\SecureController::class, 'actionAuth']); App::$collector->post('/auth', [\kernel\modules\secure\controllers\SecureController::class, 'actionAuth']);
App::$collector->get('/register', [\kernel\modules\secure\controllers\SecureController::class, 'actionRegister']);
App::$collector->post('/registration', [\kernel\modules\secure\controllers\SecureController::class, 'actionRegistration']);
}); });
App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router){ App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router){

View File

@ -24,6 +24,9 @@
</div> </div>
<div class="col-lg-8"> <div class="col-lg-8">
<div class="card-body py-5 px-md-5"> <div class="card-body py-5 px-md-5">
<div class="row md-4 text-md-center">
<h1>Авторизация</h1>
</div>
<form action="/admin/auth" method="post"> <form action="/admin/auth" method="post">
<!-- Email input --> <!-- Email input -->
@ -48,10 +51,15 @@
</div> </div>
</div> </div>
<div class="col"> <div class="col-3">
<!-- Simple link --> <!-- Simple link -->
<a href="#!">Забыл пароль?</a> <a href="#!">Забыл пароль?</a>
</div> </div>
<div class="col">
<!-- Simple link -->
<a href="/admin/register">Регистрация</a>
</div>
</div> </div>
<!-- Submit button --> <!-- Submit button -->

View File

@ -0,0 +1,71 @@
<!-- Section: Design Block -->
<section class=" text-center text-lg-start">
<style>
.rounded-t-5 {
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;
}
@media (min-width: 992px) {
.rounded-tr-lg-0 {
border-top-right-radius: 0;
}
.rounded-bl-lg-5 {
border-bottom-left-radius: 0.5rem;
}
}
</style>
<div class="card mb-3">
<div class="row g-0 d-flex align-items-center">
<div class="col-lg-4 d-none d-lg-flex">
<img src="https://mdbootstrap.com/img/new/ecommerce/vertical/004.jpg" alt="Trendy Pants and Shoes"
class="w-100 rounded-t-5 rounded-tr-lg-0 rounded-bl-lg-5" />
</div>
<div class="col-lg-8">
<div class="card-body py-5 px-md-5">
<div class="row md-4 text-md-center">
<h1>Регистрация</h1>
</div>
<form action="/admin/registration" method="post">
<!--Username input -->
<div data-mdb-input-init class="form-outline mb-4">
<input type="text" id="form2Example1" class="form-control" name="username" />
<label class="form-label" for="form2Example1">Логин</label>
</div>
<!-- Email input -->
<div data-mdb-input-init class="form-outline mb-4">
<input type="email" id="form2Example1" class="form-control" name="email" />
<label class="form-label" for="form2Example1">Email</label>
</div>
<!-- Password input -->
<div data-mdb-input-init class="form-outline mb-4">
<input type="password" id="form2Example2" class="form-control" name="password" />
<label class="form-label" for="form2Example2">Пароль</label>
</div>
<div class="row mb-4">
<div class="col-4">
<!-- Submit button -->
<button type="submit" data-mdb-button-init data-mdb-ripple-init class="btn btn-primary btn-block mb-4">Регистрация</button>
</div>
<div class="col-4">
<!-- Simple link -->
<a href="/admin/login">Войти в существующий аккаунт</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Section: Design Block -->

View File

@ -1,6 +1,6 @@
<?php <?php
namespace app\modules\slider; namespace kernel\modules\slider;
use kernel\Module; use kernel\Module;
use kernel\modules\menu\service\MenuService; use kernel\modules\menu\service\MenuService;
@ -22,7 +22,7 @@ class SliderModule extends Module
*/ */
public function init(): void public function init(): void
{ {
$this->migrationService->runAtPath("{APP}/modules/slider/migrations"); $this->migrationService->runAtPath("{KERNEL_MODULES}/slider/migrations");
$this->menuService->createItem([ $this->menuService->createItem([
"label" => "Слайдер", "label" => "Слайдер",

View File

@ -0,0 +1,118 @@
<?php
namespace kernel\modules\slider\controllers;
use kernel\helpers\Debug;
use kernel\modules\slider\models\forms\CreateSliderForm;
use kernel\modules\slider\models\Slider;
use kernel\modules\slider\services\SliderService;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\EntityRelation;
use kernel\Request;
class SliderController extends AdminController
{
private SliderService $sliderService;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_MODULES_DIR . "/slider/views/";
$this->sliderService = new SliderService();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
#[NoReturn] public function actionAdd(): void
{
$sliderForm = new CreateSliderForm();
$sliderForm->load($_REQUEST);
if ($sliderForm->validate()) {
$slider = $this->sliderService->create($sliderForm);
$entityRelation = new EntityRelation();
$entityRelation->saveEntityRelation(entity: "post", model: $slider, request: new Request());
if ($slider) {
$this->redirect("/admin/slider/view/" . $slider->id);
}
}
$this->redirect("/admin/slider/create", 302);
}
public function actionIndex($page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
$slide = Slider::find($id);
if (!$slide){
throw new Exception(message: "The slide not found");
}
$this->cgView->render("view.php", ['slider' => $slide]);
}
/**
* @throws Exception
*/
public function actionUpdate(int $id): void
{
$model = Slider::find($id);
if (!$model){
throw new Exception(message: "The slide not found");
}
$this->cgView->render("form.php", ['model' => $model]);
}
/**
* @throws Exception
*/
public function actionEdit(int $id): void
{
$slide = Slider::find($id);
if (!$slide){
throw new Exception(message: "The slide not found");
}
$sliderForm = new CreateSliderForm();
$sliderForm->load($_REQUEST);
if ($sliderForm->validate()) {
$slide = $this->sliderService->update($sliderForm, $slide);
$entityRelation = new EntityRelation();
$entityRelation->saveEntityRelation(entity: "slider", model: $slide, request: new Request());
if ($slide) {
$this->redirect("/admin/slider/view/" . $slide->id, 302);
}
}
$this->redirect("/admin/slider/update/" . $id, 302);
}
/**
* @throws Exception
*/
#[NoReturn] public function actionDelete(int $id): void
{
$slide = Slider::find($id)->first();
if (!$slide){
throw new Exception(message: "The slide not found");
}
$entityRelation = new EntityRelation();
$entityRelation->deleteEntityRelation(entity: "slider", model: $slide);
$slide->delete();
$this->redirect("/admin/slider/", 302);
}
}

View File

@ -0,0 +1,13 @@
{
"name": "Slider",
"version": "0.1",
"author": "ITGuild",
"slug": "slider",
"type": "entity",
"description": "Slider module",
"module_class": "kernel\\modules\\slider\\SliderModule",
"module_class_file": "{KERNEL_MODULES}/slider/SliderModule.php",
"routs": "routs/slider.php",
"migration_path": "migrations",
"dependence": "menu"
}

View File

@ -1,14 +1,15 @@
<?php <?php
namespace app\modules\slider\models; namespace kernel\modules\slider\models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
/** /**
* @property int $id * @property int $id
* @property string $title * @property string $title
* @property string $additionalInformation * @property string $additional_information
* @property string $content * @property string $content
* @property string $link
*/ */
class Slider extends Model class Slider extends Model
@ -17,14 +18,16 @@ class Slider extends Model
const int ACTIVE_STATUS = 1; const int ACTIVE_STATUS = 1;
protected $table = "slider"; protected $table = "slider";
protected $fillable = ['title', 'additional_information', 'content']; protected $fillable = ['title', 'additional_information', 'content', 'link'];
public static function labels() public static function labels()
{ {
return [ return [
'title' => 'Заголовок', 'title' => 'Заголовок',
'content' => 'Контент',
'link' => 'Ссылка',
'additional_information' => 'Дополнительная информация', 'additional_information' => 'Дополнительная информация',
'content' => 'Контент' 'status' => 'Статус'
]; ];
} }

View File

@ -0,0 +1,19 @@
<?php
namespace kernel\modules\slider\models\forms;
use kernel\FormModel;
class CreateSliderForm extends FormModel
{
public function rules(): array
{
return [
'title' => 'required|min-str-len:5',
'additional_information' => 'nullable',
'content' => 'required|min-str-len:10',
'link' => '',
'status' => 'required|integer',
];
}
}

View File

@ -0,0 +1,20 @@
<?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" => "slider"], function (CGRouteCollector $router) {
App::$collector->get('/', [\kernel\modules\slider\controllers\SliderController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\kernel\modules\slider\controllers\SliderController::class, 'actionIndex']);
App::$collector->get('/create', [\kernel\modules\slider\controllers\SliderController::class, 'actionCreate']);
App::$collector->post("/", [\kernel\modules\slider\controllers\SliderController::class, 'actionAdd']);
App::$collector->get('/view/{id}', [\kernel\modules\slider\controllers\SliderController::class, 'actionView']);
App::$collector->any('/update/{id}', [\kernel\modules\slider\controllers\SliderController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\kernel\modules\slider\controllers\SliderController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\kernel\modules\slider\controllers\SliderController::class, 'actionDelete']);
});
});
});

View File

@ -0,0 +1,39 @@
<?php
namespace kernel\modules\slider\services;
use kernel\modules\slider\models\Slider;
use kernel\helpers\Debug;
use kernel\helpers\Slug;
use kernel\modules\post\models\Post;
use kernel\FormModel;
class SliderService
{
public function create(FormModel $form_model): false|Slider
{
$model = new Slider();
$model->title = $form_model->getItem('title');
$model->content = $form_model->getItem('content');
$model->additional_information = $form_model->getItem('additional_information');
$model->link = $form_model->getItem('link');
if ($model->save()){
return $model;
}
return false;
}
public function update(FormModel $form_model, Slider $slider): false|Slider
{
$slider->title = $form_model->getItem('title');
$slider->content = $form_model->getItem('content');
$slider->additional_information = $form_model->getItem('additional_information');
$slider->link = $form_model->getItem('link');
if ($slider->save()){
return $slider;
}
return false;
}
}

View File

@ -0,0 +1,85 @@
<?php
/**
* @var Slider $slider
*/
use kernel\modules\slider\models\Slider;
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/slider/edit/" . $model->id : "/admin/slider", 'multipart/form-data');
$form->field(\itguild\forms\inputs\TextInput::class, 'title', [
'class' => "form-control",
'placeholder' => 'Заголовок',
'value' => $model->title ?? ''
])
->setLabel("Заголовок")
->render();
$form->field(class: \itguild\forms\inputs\TextArea::class, name: "content", params: [
'class' => "form-control",
'placeholder' => 'Контент',
'rows' => '10',
'value' => $model->content ?? ''
])
->setLabel("Контент")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "additional_information", params: [
'class' => "form-control",
'placeholder' => 'Дополнительная информация',
'rows' => '10',
'value' => $model->additional_information ?? ''
])
->setLabel("Дополнительная информация")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "link", params: [
'class' => "form-control",
'placeholder' => 'Ссылка',
'rows' => '10',
'value' => $model->link ?? ''
])
->setLabel("Ссылка")
->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "status", params: [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(Slider::getStatus())
->render();
$entityRelations = new \kernel\EntityRelation();
if (!isset($model)) {
$model = new Slider();
}
$entityRelations->renderEntityAdditionalPropertyFormBySlug("slider", $model);
?>
<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();

View File

@ -3,7 +3,7 @@
* @var int $page_number * @var int $page_number
*/ */
use app\modules\slider\models\Slider; use kernel\modules\slider\models\Slider;
use Itguild\EloquentTable\EloquentDataProvider; use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable; use Itguild\EloquentTable\ListEloquentTable;
use kernel\app_modules\photo\models\Photo; use kernel\app_modules\photo\models\Photo;
@ -16,7 +16,7 @@ $table = new ListEloquentTable(new EloquentDataProvider(Slider::class, [
'currentPage' => $page_number, 'currentPage' => $page_number,
'perPage' => 8, 'perPage' => 8,
'params' => ["class" => "table table-bordered", "border" => "2"], 'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/photo", 'baseUrl' => "/admin/slider",
])); ]));
$table->beforePrint(function () { $table->beforePrint(function () {

View File

@ -15,14 +15,14 @@ $table = new ViewEloquentTable(new ViewJsonTableEloquentModel($slider, [
'baseUrl' => "/admin/slider", 'baseUrl' => "/admin/slider",
])); ]));
$table->beforePrint(function () use ($slider) { $table->beforePrint(function () use ($slider) {
$btn = PrimaryBtn::create("Список", "/admin/slider")->fetch(); $btn = \kernel\widgets\IconBtn\IconBtnListWidget::create(['url' => "/admin/slider"])->run();
$btn .= SuccessBtn::create("Редактировать", "/admin/slider/update/" . $slider->id)->fetch(); $btn .= \kernel\widgets\IconBtn\IconBtnEditWidget::create(['url' => "/admin/slider/update/" . $slider->id])->run();
$btn .= DangerBtn::create("Удалить", "/admin/slider/delete/" . $slider->id)->fetch(); $btn .= \kernel\widgets\IconBtn\IconBtnDeleteWidget::create(['url' => "/admin/slider/delete/" . $slider->id])->run();
return $btn; return $btn;
}); });
$table->rows([ $table->rows([
'status' => (function ($data) { 'status' => (function ($data) {
return \app\modules\slider\models\Slider::getStatus()[$data]; return \kernel\modules\slider\models\Slider::getStatus()[$data];
}) })
]); ]);
$table->create(); $table->create();