Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Добавляем dictator (Мой генератор админки) в зависимости:
- composer config minimum-stability dev
- composer require "uavn/dictator"
- В конфиги config/dev.php и config/prod.php добавь параметры подключения к БД:
- $app['db.options'] = [
- 'host' => 'localhost',
- 'user' => 'root',
- 'password' => 'root',
- 'dbname' => 'vladia'
- ];
- Только настрой согласно своим параметрам БД
- кроме того в config/prod.php добавь:
- // Admin: count items on list page
- $app['admin.items_per_page'] = 10;
- в src/app.php перед return $app; вставь:
- // PDO Service
- $app['db'] = function() use ($app) {
- return new \PDO(
- sprintf(
- 'mysql:host=%s;dbname=%s',
- $app['db.options']['host'],
- $app['db.options']['dbname']
- ),
- $app['db.options']['user'],
- $app['db.options']['password'],
- [
- PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
- ]
- );
- };
- // Admin Generator Service
- $app['dictator'] = function() use ($app) {
- return (new \Uavn\Dictator)
- ->setConnection($app['db'])
- ->setOptions([
- 'Actions' => 'Действия',
- 'Edit' => 'Редактировать',
- 'Delete' => 'Удалить',
- 'New row' => 'Новая запись',
- 'Edit row' => 'Редактировать запись',
- 'Page' => 'Страница',
- 'Sure?' => 'Уверены?',
- 'Search' => 'Найти',
- 'Save' => 'Сохранить',
- 'List rows' => 'Все записи',
- 'Saved successful' => 'Успешно сохранено',
- 'ipp' => $app['admin.items_per_page']
- ]);
- };
- далее админка, добавь в файл config/prod.php
- $app['admin.credentials'] = [
- 'admin' => 'admin'
- ];
- по этим логин-пароль можно будет попасть в админку
- создай файл src/controllers/admin.php папку src/controllers предварительно тоже создай
- в файл src/controllers/admin.php запиши следующее:
- <?php
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\RedirectResponse;
- use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
- use Silex\Application;
- // define controllers for a blog
- $admin = $app['controllers_factory'];
- // HTTP Auth
- $admin->before(function(Request $request, Application $app) {
- $users = $app['admin.credentials'];
- $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
- $pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
- $validated = (array_key_exists($user, $users)) && ($pass == $users[$user]);
- if (!$validated) {
- header('WWW-Authenticate: Basic realm="Security Zone"');
- header('HTTP/1.0 401 Unauthorized');
- die ("Not authorized");
- }
- });
- $admin->get('/', function (Application $app) {
- return $app['twig']->render('admin/index.html.twig', [
- ]);
- })->bind('admin.index');
- // Prefix /admin for all actions
- $app->mount('/admin', $admin);
- в файл src/controllers.php допиши после всех use-ов:
- require_once __DIR__ . '/controllers/admin.php';
- создай файл templates/admin-layout.html.twig:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
- <title>{% block title 'Vladia' %}</title>
- <!-- Latest compiled and minified CSS -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
- <link href="{{ asset('css/adminstyle.css') }}" rel="stylesheet">
- <link href="{{ asset('css/main.css') }}" rel="stylesheet" type="text/css" />
- <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
- <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
- <!--[if lt IE 9]>
- <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
- <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
- <![endif]-->
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
- <div class="container-fluid">
- <div class="collapse navbar-collapse">
- <ul class="nav navbar-nav">
- <li>
- <a href="{{ url('admin.index') }}">
- <span class="glyphicon glyphicon-list-alt"></span>
- Админка
- </a>
- </li>
- <li>
- <a href="{{ url('admin.category') }}">
- <span class="glyphicon glyphicon-list-alt"></span>
- Категории
- </a>
- </li>
- <li>
- <a href="{{ url('admin.section') }}">
- <span class="glyphicon glyphicon-list-alt"></span>
- Секции
- </a>
- </li>
- <li>
- <a href="{{ url('admin.product') }}">
- <span class="glyphicon glyphicon-list-alt"></span>
- Товары
- </a>
- </li>
- </ul>
- </div><!-- /.nav-collapse -->
- </div><!-- /.container -->
- </div><!-- /.navbar -->
- <div class="container-fluid">
- <div class="_row">
- {% block content %}{% endblock%}
- </div>
- </div>
- <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
- <script>
- $(document).on('click', 'th input[type=checkbox]', function() {
- if ( $(this).is(':checked') ) {
- $('td input[type=checkbox]').prop('checked', true);
- } else {
- $('td input[type=checkbox]').prop('checked', false);
- }
- });
- $(document).on('click', 'td input[type=checkbox]', function() {
- if( $('td input[type=checkbox]:checked').length == $('td input[type=checkbox]').length ) {
- $('th input[type=checkbox]').prop('checked', true);
- } else {
- $('th input[type=checkbox]').prop('checked', false);
- }
- });
- </script>
- <!-- Latest compiled and minified JavaScript -->
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
- </body>
- </html>
- и хак для интеграции админки в бутстрап, создай файл web/css/adminstyle.css:
- body {
- padding-top: 50px;
- }
- h1 .new {
- font-size: 14px;
- }
- .dictator-search {
- background-color: #eee;
- padding: 10px;
- margin: 20px 0;
- }
- .dictator-search label {
- margin-right: 10px;
- }
- .dictator-sort-asc, .dictator-sort-desc {
- padding-left: 10px;
- background-repeat: no-repeat;
- background-position: -6px -3px;
- }
- .dictator-sort-desc {
- background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABZ0RVh0Q3JlYXRpb24gVGltZQAwNC8xNC8wOFZL9aYAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzQGstOgAAAAj0lEQVQ4jWP8//8/AzUBE1VNGzVwhBjIgk9yr4AAzkTq/OEDI8kGMjAwMJhWVGCIne7owKker5ddPn5khGn+sX8/3LBc459YXcfAwMDA8P//f5wYJr+Hn///x/b2/3v4+f/jU////38GRnx5mZER4ZA9/Pz/t0+RZfr+8zMTAwPD36nJD7DrGS0cRg0kHQAAYMtZjBTUt+kAAAAASUVORK5CYII=');
- }
- .dictator-sort-asc {
- background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABZ0RVh0Q3JlYXRpb24gVGltZQAwNC8xNC8wOFZL9aYAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzQGstOgAAAApUlEQVQ4je2TMQ7CMAxFv6MKIYbEV2HIASquwcYhmhv0BD0NibpxDkbGsrGkZkB0ajxAByT6JUuWv/6TLNkkIlhSZlHaCvwTYKWZRDT10Tm57XfV5bgBgNydrvMhESnW24/Oyb1tJTJLtM5oGXXls7WUmMWHgEffwzcNYCgn5mJOBRLR6EMAAGzrGgBeUCAXM9ovJ+aieRgGmpurwE/0+3e4Ar/XEybDVp50x3YfAAAAAElFTkSuQmCC');
- }
- .dictator-pager {
- margin: 30px 0;
- }
- .dictator-current {
- background-color: #fff000;
- }
- .dictator-page, .dictator-current {
- padding: 3px;
- }
- .dictator-pager a {
- color: #000;
- }
- th .form-control[type=checkbox], td .form-control[type=checkbox] {
- height: 15px;
- width: 15px;
- }
- .table {
- margin-bottom: 0 !important;
- }
- .nowrap {
- white-space: nowrap;
- }
- .nowrap a {
- color: #000;
- }
- .nowrap a:hover {
- text-decoration: none;
- border-bottom: 1px solid #2A6496;
- color: #2A6496;
- }
- .dictator-row {
- max-width: 800px;
- margin-bottom: 20px;
- }
- .dictator-row [type=checkbox] {
- width: 15px;
- height: 15px;
- display: inline;
- vertical-align: middle;
- margin: 0;
- }
- .dictator-row textarea {
- min-height: 300px;
- }
- .dictator-list-rows {
- margin-left: 20px;
- }
- .dictator-saved {
- background-color: #DFF0D8;
- border-color: #D6E9C6;
- color: #3C763D;
- padding: 15px;
- margin-bottom: 20px;
- border: 1px solid rgba(0, 0, 0, 0);
- border-radius: 4px;
- }
- .wysibb .powered {
- display: none;
- }
- th {
- background-color: #333 !important;
- color: #fff;
- border-color: #111 !important;
- border-top: 1px solid #111 !important;
- }
- th a {
- color: #fff;
- }
- .inp-little {
- display: inline !important;
- max-width: 200px;
- }
- .info-row {
- margin-bottom: 10px;
- }
- .shop-item {
- float: left;
- margin-right: 10px;
- }
- .clr {
- clear: both;
- }
- .one-less-shop {
- float: left;
- margin-top: 25px;
- }
- .shop-row {
- margin-bottom: 20px;
- }
- .object-tobuy {
- margin-bottom: 10px;
- }
- body {
- }
- #msg {
- width: 900px;
- height: 300px;
- }
- .dictator-search label {
- vertical-align: top;
- }
- .dictator-search .selectize-control {
- width: 200px;
- }
- .dictator-search .btn {
- margin-top: 20px;
- }
- #files img {
- width: 150px;
- display: inline-block;
- margin: 5px;
- }
- #files img:hover {
- opacity: 0.8;
- cursor: pointer;
- }
- создай файл templates/admin/index.html.twig:
- {% extends "admin-layout.html.twig" %}
- {% block content %}
- <div class="row">
- <div class="content">
- Welcome to your Admin Page
- </div>
- </div>
- {% endblock %}
- создай файл templates/admin/dictator.html.twig:
- {% extends "admin-layout.html.twig" %}
- {% block content %}
- <div class="row">
- <div class="col-md-12">
- {{ html|raw }}
- </div>
- </div>
- {% endblock %}
- Далее исправь titile в таблице product на title
- Далее добавь перед $app->mount... в controllers/admin.php:
- $admin->match('/category', function (Application $app) {
- $dictator = $app['dictator']
- ->setTable('category', 'Категории')
- ->addField('id', 'ID')
- ->addField('name', 'Название')
- ;
- return $app['twig']->render('admin/dictator.html.twig', [
- 'html' => $dictator->generate()
- ]);
- })->bind('admin.category');
- $admin->match('/section', function (Application $app) {
- $dictator = $app['dictator']
- ->setTable('section', 'Секции')
- ->addField('id', 'ID')
- ->addField('name', 'Название')
- ;
- return $app['twig']->render('admin/dictator.html.twig', [
- 'html' => $dictator->generate()
- ]);
- })->bind('admin.section');
- $admin->match('/product', function (Application $app) {
- $dictator = $app['dictator']
- ->setTable('product', 'Товары')
- ->addField('id', 'ID')
- ->addField('title', 'Название')
- ->addField('text', 'Описание')
- ->addTextWidget('text')
- ->addFilter('text', function( $text ) {
- if ( $text ) {
- $substr = mb_substr($text, 0, 200, 'UTF-8');
- return $substr . '…';
- }
- return '—';
- })
- ->addField('price', 'Цена')
- ->addFilter('price', function( $price ) {
- if ( $price ) {
- $nf = number_format($price, 2, '.', ' ');
- return $nf . ' грн';
- }
- return '—';
- })
- ->addField('sectionId', 'Секция')
- ->addRelation('sectionId', 'category', 'name')
- ->addField('categoryId', 'Категория')
- ->addRelation('categoryId', 'category', 'name')
- ;
- return $app['twig']->render('admin/dictator.html.twig', [
- 'html' => $dictator->generate()
- ]);
- })->bind('admin.product');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement