Hello. Here I display image and text upload to admin side. Also update image and content by admin. Here I display its file and folder structure.
etc->di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Backend/etc/menu.xsd">
<menu>
<add id="chirag_banner::core" title="Banner Create" module="Chirag_Banner" sortOrder="40" resource="Chirag_Banner::sample"/>
<add id="chirag_banner::test" title="Upload Banner" module="Chirag_Banner" sortOrder="10" parent="chirag_banner::core" action="chirag_banner/post/" resource="Chirag_Banner::post"/>
</menu>
</config>
etc->adminhtml->routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="admin">
<route id="chirag_banner" frontName="chirag_banner">
<module name="Chirag_Banner" />
</route>
</router>
</config>
Setup->InstallSchema.php
<?php
namespace Chirag\Banner\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
/**
* Creating table chirag_banner_table
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('chirag_banner_table')
)->addColumn(
'banner_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Banner Id'
)->addColumn(
'imagename',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => false],
'Image Name'
)->addColumn(
'imagepath',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => false],
'Image Path'
)->addColumn(
'imagedata',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
['nullable' => false],
'Image Data Content'
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
1,
['nullable' => true,'default' => 1],
'Status'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false],
'Updated At'
)->setComment(
'Chirag Banner Table'
);
$installer->getConnection()->createTable($table);
$installer->endSetup();
}
}
Ui_Component->Listing->Column->BannerActions.php
<?php
namespace Chirag\Banner\Ui_Component\Listing\Column;
class BannerActions extends \Magento\Ui\Component\Listing\Columns\Column
{
const URL_PATH_EDIT = 'chirag_banner/post/edit';
/**
* URL builder
*
* @var \Magento\Framework\UrlInterface
*/
protected $_urlBuilder;
/**
* constructor
*
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Magento\Framework\View\Element\UiComponent\ContextInterface $context
* @param \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory
* @param array $components
* @param array $data
*/
public function __construct(
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Framework\View\Element\UiComponent\ContextInterface $context,
\Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = []
)
{
$this->_urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
//print_r($item);
$item[$this->getData('name')] = [
'edit' => [
'href' => $this->_urlBuilder->getUrl(
static::URL_PATH_EDIT,
[
'id' => $item['banner_id']
]
),
'label' => __('Edit')
],
];
}
}
return $dataSource;
}
}
Ui_Component->Listing->Column->Thumbnail.php
<?php
namespace Chirag\Banner\Ui_Component\Listing\Column;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
class Thumbnail extends \Magento\Ui\Component\Listing\Columns\Column
{
const NAME = 'thumbnail';
const ALT_FIELD = 'name';
private $_getModel;
/**
* @var string
*/
private $editUrl;
private $_objectManager = null;
/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param \Chirag\Banner\Model\ResourceModel\Image $imageHelper
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
\Chirag\Banner\Model\ResourceModel\Image\Image $imageHelper,
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $components = [],
array $data = []
) {
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->imageHelper = $imageHelper;
$this->urlBuilder = $urlBuilder;
//$this->_getModel = $model;
$this->_objectManager = $objectManager;
}
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$fieldName = $this->getData('name');
foreach ($dataSource['data']['items'] as & $item) {
//$filename = 'myimage.png';
$filename = $item['imagepath'];;
$item[$fieldName . '_src'] = $this->imageHelper->getBaseUrl().$filename;
$item[$fieldName . '_alt'] = $this->getAlt($item) ?: $filename;
$item[$fieldName . '_orig_src'] = $this->imageHelper->getBaseUrl().$filename;
}
}
return $dataSource;
}
/**
* @param array $row
*
* @return null|string
*/
protected function getAlt($row)
{
$altField = $this->getData('config/altField') ?: self::ALT_FIELD;
return isset($row[$altField]) ? $row[$altField] : null;
}
}
?>
view->adminhtml->layout->chirag_banner_post_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<update handle="styles"/>
<body>
<referenceContainer name="content">
<uiComponent name="chirag_banner_post_listing"/>
</referenceContainer>
</body>
</page>
view->adminhtml->layout->chirag_banner_post_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<update handle="editor"/>
<body>
<referenceContainer name="left">
<block class="Chirag\Banner\Block\Adminhtml\Post\Edit\Tabs" name="chirag_banner_post_edit_tabs">
<block class="Chirag\Banner\Block\Adminhtml\Post\Edit\Tab\Main" name="chirag_banner_post_edit_tab_main"/>
<action method="addTab">
<argument name="name" xsi:type="string">main_section</argument>
<argument name="block" xsi:type="string">chirag_banner_post_edit_tab_main</argument>
</action>
</block>
</referenceContainer>
<referenceContainer name="content">
<block class="Chirag\Banner\Block\Adminhtml\Post\Edit" name="test_post_edit"/>
</referenceContainer>
</body>
</page>
view->adminhtml->ui_component->chirag_banner_post_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<!-- ... other block of code -->
<listingToolbar name="listing_top">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="sticky" xsi:type="boolean">true</item>
</item>
</argument>
<bookmark name="bookmarks"/>
<columnsControls name="columns_controls"/>
<filterSearch name="fulltext"/>
<filters name="listing_filters" />
<massaction name="listing_massaction">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
</item>
</argument>
<action name="delete">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">delete</item>
<item name="label" xsi:type="string" translate="true">Delete</item>
<item name="url" xsi:type="url" path="chirag_banner/post/massDelete"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Delete Post</item>
<item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
<paging name="listing_paging"/>
<exportButton name="export_button"/>
</listingToolbar>
<!-- ... other block of code -->
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">chirag_banner_post_listing.chirag_banner_post_listing_data_source</item>
<item name="deps" xsi:type="string">chirag_banner_post_listing.chirag_banner_post_listing_data_source</item>
</item>
<item name="spinner" xsi:type="string">spinner_columns</item>
<item name="buttons" xsi:type="array">
<item name="add" xsi:type="array">
<item name="name" xsi:type="string">add</item>
<item name="label" xsi:type="string" translate="true">Add New Post22</item>
<item name="class" xsi:type="string">primary</item>
<item name="url" xsi:type="string">*/*/new</item>
</item>
</item>
</argument>
<dataSource name="nameOfDataSource">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
<argument name="name" xsi:type="string">chirag_banner_post_listing_data_source</argument>
<argument name="primaryFieldName" xsi:type="string">banner_id</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
<item name="update_url" xsi:type="url" path="mui/index/render"/>
<item name="storageConfig" xsi:type="array">
<item name="indexField" xsi:type="string">banner_id</item>
</item>
</item>
</argument>
</argument>
</dataSource>
<columns name="spinner_columns">
<selectionsColumn name="ids">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="resizeEnabled" xsi:type="boolean">false</item>
<item name="resizeDefaultWidth" xsi:type="string">55</item>
<item name="indexField" xsi:type="string">banner_id</item>
</item>
</argument>
</selectionsColumn>
<column name="banner_id">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">textRange</item>
<item name="sorting" xsi:type="string">asc</item>
<item name="label" xsi:type="string" translate="true">ID</item>
</item>
</argument>
</column>
<column name="imagepath" class="Chirag\Banner\Ui_Component\Listing\Column\Thumbnail">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
<item name="sortable" xsi:type="boolean">false</item>
<item name="altField" xsi:type="string">title</item>
<item name="has_preview" xsi:type="string">1</item>
<item name="label" xsi:type="string" translate="true">Thumbnail</item>
</item>
</argument>
</column>
<column name="imagename">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="editor" xsi:type="array">
<item name="editorType" xsi:type="string">text</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
</item>
</item>
<item name="label" xsi:type="string" translate="true">Image Name</item>
</item>
</argument>
</column>
<column name="imagedata">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="editor" xsi:type="array">
<item name="editorType" xsi:type="string">text</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
</item>
</item>
<item name="label" xsi:type="string" translate="true">Image Description</item>
</item>
</argument>
</column>
<column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
<item name="label" xsi:type="string" translate="true">Created</item>
</item>
</argument>
</column>
<column name="updated_at" class="Magento\Ui\Component\Listing\Columns\Date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
<item name="label" xsi:type="string" translate="true">Modified</item>
</item>
</argument>
</column>
<actionsColumn name="actions" class="Chirag\Banner\Ui_Component\Listing\Column\BannerActions">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">banner_id</item>
<item name="urlEntityParamName" xsi:type="string">id</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing>
Model->Post.php
<?php
namespace Chirag\Banner\Model;
use Magento\Framework\Model\AbstractModel;
class Post extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init('Chirag\Banner\Model\ResourceModel\Post');
}
}
?>
Model->ResourceModel->Post.php
<?php
namespace Chirag\Banner\Model\ResourceModel;
class Post extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init('chirag_banner_table', 'banner_id'); //here "chirag_banner_table" is table name and "banner_id" is the primary key of custom table
}
}
Model->ResourceModel->Image->Image.php
<?php
namespace Chirag\Banner\Model\ResourceModel\Image;
use Magento\Framework\UrlInterface;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
//protected $subDir = 'chirag/banner/image';
/**
* url builder
*
* @var \Magento\Framework\UrlInterface
*/
protected $urlBuilder;
/**
* @var \Magento\Framework\Filesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
//return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image/';
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]);
}
}
?>
Model->ResourceModel->Post->Collection.php
<?php
namespace Chirag\Banner\Model\ResourceModel\Post;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'banner_id';
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(
'Chirag\Banner\Model\Post',
'Chirag\Banner\Model\ResourceModel\Post'
);
}
}
?>
Block->Adminhtml->Post.php
<?php
namespace Chirag\Banner\Block\Adminhtml;
class Post extends \Magento\Backend\Block\Widget\Grid\Container
{
/**
* Constructor
*
* @return void
*/
protected function _construct()
{
$this->_controller = 'post';
$this->_headerText = __('Post');
$this->_addButtonLabel = __('Add New Post12345');
parent::_construct();
}
}
Block->Adminhtml->Post->Edit.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post;
class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
/**
* @param \Magento\Backend\Block\Widget\Context $context
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Widget\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_coreRegistry = $registry;
parent::__construct($context, $data);
}
/**
* Initialize form
* Add standard buttons
* Add "Save and Continue" button
*
* @return void
*/
protected function _construct()
{
$this->_objectId = 'id';
$this->_controller = 'adminhtml_post';
$this->_blockGroup = 'Chirag_Banner';
parent::_construct();
$this->buttonList->add(
'save_and_continue_edit',
[
'class' => 'save',
'label' => __('Save and Continue Edit'),
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form']],
]
],
10
);
}
/**
* Getter for form header text
*
* @return \Magento\Framework\Phrase
*/
public function getHeaderText()
{
$item = $this->_coreRegistry->registry('current_chirag_banner_post');
if ($item->getId()) {
return __("Edit Banner '%1'", $this->escapeHtml($item->getImagename()));
} else {
return __('New Banner');
}
}
}
Block->Adminhtml->Post->Edit->Form.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post\Edit;
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* Constructor
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('banner_post_form');
$this->setTitle(__('Banner Information'));
}
/**
* Prepare form before rendering HTML
*
* @return $this
*/
protected function _prepareForm()
{
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form',
//'action' => $this->getUrl('chirag_events/items/save'),
'action' => $this->getUrl('chirag_banner/post/save'),
'method' => 'post',
'enctype' => 'multipart/form-data'
],
]
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
?>
Block->Adminhtml->Post->Edit->Tabs.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post\Edit;
class Tabs extends \Magento\Backend\Block\Widget\Tabs
{
/**
* Constructor
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('chirag_banner_post_edit_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(__('Banner'));
}
}
Block->Adminhtml->Post->Edit->Tab->Main.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post\Edit\Tab;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
class Main extends Generic implements TabInterface
{
protected $_wysiwygConfig;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
array $data = []
)
{
$this->_wysiwygConfig = $wysiwygConfig;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* {@inheritdoc}
*/
public function getTabLabel()
{
return __('Banner Information');
}
/**
* {@inheritdoc}
*/
public function getTabTitle()
{
return __('Banner Information');
}
/**
* {@inheritdoc}
*/
public function canShowTab()
{
return true;
}
/**
* {@inheritdoc}
*/
public function isHidden()
{
return false;
}
/*public function myfunction(){
echo "<script> alert('ram')</script>";
}*/
/**
* Prepare form before rendering HTML
*
* @return $this
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('current_chirag_banner_post');
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('banner_');
$dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
$timeFormat = $this->_localeDate->getTimeFormat(\IntlDateFormatter::SHORT);
$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Add Banner Data Here')]);
if ($model->getId()) {
$fieldset->addField('banner_id', 'hidden', ['name' => 'banner_id']);
}
$fieldset->addField(
'imagename',
'text',
['name' => 'imagename', 'label' => __('Image Name'), 'title' => __('Image Name'), 'required' => true]
);
/*$fieldset->addField(
'imagedata',
'text',
['name' => 'imagedata', 'label' => __('Image Details'), 'title' => __('Image Details'), 'required' => true]
);*/
$fieldset->addField(
'imagedata',
'editor',
[
'name' => 'imagedata',
'label' => __('Content'),
'title' => __('Content'),
'style' => 'height:26em;',
'required' => true,
'config' => $this->_wysiwygConfig->getConfig(),
'wysiwyg' => true
]
);
$fieldset->addField(
'imagepath',
'image',
['name' => 'imagepath', 'label' => __('Image Upload'), 'title' => __('Image Upload'), 'required' => true]
);
// $fieldset->addField(
// 'date',
// 'date',
// ['name' => 'date', 'label' => __('Choose Date'), 'title' => __('Choose Date'), 'required' => true, 'date_format' => $dateFormat]
// );
// $fieldset->addField(
// 'savedata',
// 'button',
// ['name' => 'savedata', 'label' => __('Save Data'), 'title' => __('Save Data'), 'onclick' => 'myfunction()']
// );
/* $fieldset->addField(
'image',
'image',
[
'name' => 'image',
'label' => __('Image'),
'title' => __('Image'),
'required' => false
]
); */
/* $fieldset->addField(
'status',
'select',
['name' => 'status', 'label' => __('Status'), 'title' => __('Status'), 'options' => [0 => 'Disable', 1 => 'Enable'], 'required' => true]
); */
/* $fieldset->addField(
'content',
'editor',
[
'name' => 'content',
'label' => __('Content'),
'title' => __('Content'),
'style' => 'height:26em;',
'required' => true,
'config' => $this->_wysiwygConfig->getConfig(),
'wysiwyg' => true
]
); */
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
}
Controller->Adminhtml->Post.php
<?php
namespace Chirag\Banner\Controller\Adminhtml;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;
/**
* Items controller
*/
abstract class Post extends \Magento\Backend\App\Action
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* @var \Magento\Backend\Model\View\Result\ForwardFactory
*/
protected $resultForwardFactory;
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
protected $uploaderFactory;
protected $adapterFactory;
protected $filesystem;
/**
* Initialize Group Controller
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
DirectoryList $directoryList,
UploaderFactory $uploaderFactory,
AdapterFactory $adapterFactory,
Filesystem $filesystem,
\Magento\Framework\Filesystem\Driver\File $file
) {
$this->_coreRegistry = $coreRegistry;
parent::__construct($context);
$this->resultForwardFactory = $resultForwardFactory;
$this->resultPageFactory = $resultPageFactory;
$this->directoryList = $directoryList;
$this->uploaderFactory = $uploaderFactory;
$this->adapterFactory = $adapterFactory;
$this->filesystem = $filesystem;
$this->_file = $file;
}
/**
* Initiate action
*
* @return this
*/
protected function _initAction()
{
$this->_view->loadLayout();
$this->_setActiveMenu('Chirag_Banner::post')->_addBreadcrumb(__('Post'), __('Post'));
return $this;
}
/**
* Determine if authorized to perform group actions.
*
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Chirag_Banner::post');
}
}
Controller->Adminhtml->Post->Index.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory = false;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->prepend((__('Postsss')));
return $resultPage;
}
}
Controller->Adminhtml->Post->Delete.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class Delete extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
$id = $this->getRequest()->getParam('id');
if ($id) {
try {
$model = $this->_objectManager->create('Chirag\Banner\Model\Post');
$model->load($id);
$model->delete();
$this->messageManager->addSuccess(__('You deleted the post.'));
$this->_redirect('chirag_banner/*/');
return;
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addError(
__('We can\'t delete post right now. Please review the log and try again.')
);
$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
$this->_redirect('chirag_banner/*/edit', ['id' => $this->getRequest()->getParam('id')]);
return;
}
}
$this->messageManager->addError(__('We can\'t find a post to delete.'));
$this->_redirect('chirag_banner/*/');
}
}
Controller->Adminhtml->Post->Edit.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class Edit extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
$id = $this->getRequest()->getParam('id');
$model = $this->_objectManager->create('Chirag\Banner\Model\Post');
if ($id) {
$model->load($id);
if (!$model->getId()) {
$this->messageManager->addError(__('This post no longer exists.'));
$this->_redirect('chirag_banner/*');
return;
}
}
// set entered data if was error when we do save
$data = $this->_objectManager->get('Magento\Backend\Model\Session')->getPageData(true);
if (!empty($data)) {
$model->addData($data);
}
$this->_coreRegistry->register('current_chirag_banner_post', $model);
$this->_initAction();
if ($model->getId()) {
$title = __('Edit Post');
} else {
$title = __('New Post Create Form');
}
$this->_view->getPage()->getConfig()->getTitle()->prepend($title);
$this->_view->getLayout()->getBlock('post_post_edit');
$this->_view->renderLayout();
}
}
Controller->Adminhtml->Post->MassDelete.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;
use Chirag\Banner\Model\ResourceModel\Post\CollectionFactory;
class MassDelete extends \Magento\Backend\App\Action
{
/**
* @var Filter
*/
protected $filter;
/**
* @var CollectionFactory
*/
protected $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
{
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
* @throws \Magento\Framework\Exception\LocalizedException|\Exception
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$collectionSize = $collection->getSize();
foreach ($collection as $record) {
$record->delete();
}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $collectionSize));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
Controller->Adminhtml->Post->MassStatus.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;
use Chirag\Banner\Model\ResourceModel\Post\CollectionFactory;
class MassStatus extends \Magento\Backend\App\Action
{
/**
* @var Filter
*/
protected $filter;
/**
* @var CollectionFactory
*/
protected $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
{
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
* @throws \Magento\Framework\Exception\LocalizedException|\Exception
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$collectionSize = $collection->getSize();
foreach ($collection as $record) {
$record->setStatus($this->getRequest()->getParam('status'))->save();
}
if($this->getRequest()->getParam('status') == 1){$status = 'enabled';}else{$status = 'disabled';}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been '.$status, $collectionSize));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
Controller->Adminhtml->Post->NewAction.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class NewAction extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
$this->_forward('edit');
}
}
Controller->Adminhtml->Post->Save.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
if ($this->getRequest()->getPostValue()) {
try {
$model = $this->_objectManager->create('Chirag\Banner\Model\Post');
$data = $this->getRequest()->getPostValue();
//print_r($_FILES['imgtemp']['name']); exit("-----");
if(isset($_FILES['imagepath']['name']) && $_FILES['imagepath']['name'] != '') {
try{
$uploaderFactory = $this->uploaderFactory->create(['fileId' => 'imagepath']);
$uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$imageAdapter = $this->adapterFactory->create();
$uploaderFactory->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
$uploaderFactory->setAllowRenameFiles(true);
$uploaderFactory->setFilesDispersion(true);
$mediaDirectory = $this->filesystem->getDirectoryRead($this->directoryList::MEDIA);
$destinationPath = $mediaDirectory->getAbsolutePath('chirag/banner');
$result = $uploaderFactory->save($destinationPath);
if (!$result) {
throw new LocalizedException(
__('File cannot be saved to path: $1', $destinationPath)
);
}
$imagePath = 'chirag/banner'.$result['file'];
$data['imagepath'] = $imagePath;
} catch (\Exception $e) {$this->messageManager->addError(__('File is not uploaded !'));
}
}
if(isset($data['imagepath']['delete']) && $data['imagepath']['delete'] == 1) {
$mediaDirectory = $this->filesystem->getDirectoryRead($this->directoryList::MEDIA)->getAbsolutePath();
$file = $data['imagepath']['value'];
$imgPath = $mediaDirectory.$file;
if ($this->_file->isExists($imgPath)) {
$this->_file->deleteFile($imgPath);
}
$data['imagepath'] = NULL;
}
if (isset($data['imagepath']['value'])){
$data['imagepath'] = $data['imagepath']['value'];
}
$inputFilter = new \Zend_Filter_Input(
[],
[],
$data
);
$data = $inputFilter->getUnescaped();
$id = $this->getRequest()->getParam('id');
if ($id) {
$model->load($id);
if ($id != $model->getId()) {
throw new \Magento\Framework\Exception\LocalizedException(__('The wrong post is specified.'));
}
}
$timezone = $this->_objectManager->create('Magento\Framework\Stdlib\DateTime\TimezoneInterface');
$fromTz = $timezone->getConfigTimezone();
$toTz = $timezone->getDefaultTimezone();
$date = new \DateTime(date('m/d/Y'), new \DateTimeZone($fromTz));
$date->setTimezone(new \DateTimeZone($toTz));
$data['date'] = $date->format('m/d/Y H:i:s');
$timezone = $this->_objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
$data['updated_at'] = $timezone->gmtDate();
$model->setData($data);
$session = $this->_objectManager->get('Magento\Backend\Model\Session');
$session->setPageData($model->getData());
$model->save();
$this->messageManager->addSuccess(__('You saved the banner.'));
$session->setPageData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('chirag_banner/*/edit', ['id' => $model->getId()]);
return;
}
$this->_redirect('chirag_banner/*/');
return;
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
$id = (int)$this->getRequest()->getParam('id');
if (!empty($id)) {
$this->_redirect('chirag_banner/*/edit', ['id' => $id]);
} else {
$this->_redirect('chirag_banner/*/new');
}
return;
} catch (\Exception $e) {
$this->messageManager->addError(
__('Something went wrong while saving the banner data. Please review the error log.')
);
$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
$this->_objectManager->get('Magento\Backend\Model\Session')->setPageData($data);
$this->_redirect('chirag_banner/*/edit', ['id' => $this->getRequest()->getParam('id')]);
return;
}
}
$this->_redirect('chirag_banner/*/');
}
}
Here its screenshots for better understanding.
Here its code.
Chirag->Banner->registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Chirag_Banner',
__DIR__
);
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Chirag_Banner',
__DIR__
);
?>
etc->di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="chirag_banner_post_listing_data_source" xsi:type="string">Chirag\Banner\Model\ResourceModel\Post\Grid\Collection</item>
</argument>
</arguments>
</type>
<virtualType name="Chirag\Banner\Model\ResourceModel\Post\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">chirag_banner_table</argument>
<argument name="resourceModel" xsi:type="string">Chirag\Banner\Model\ResourceModel\Post</argument>
</arguments>
</virtualType>
</config>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="chirag_banner_post_listing_data_source" xsi:type="string">Chirag\Banner\Model\ResourceModel\Post\Grid\Collection</item>
</argument>
</arguments>
</type>
<virtualType name="Chirag\Banner\Model\ResourceModel\Post\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">chirag_banner_table</argument>
<argument name="resourceModel" xsi:type="string">Chirag\Banner\Model\ResourceModel\Post</argument>
</arguments>
</virtualType>
</config>
etc->module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Chirag_Banner" setup_version="1.0.1" />
</config>
etc->adminhtml->menu.xml<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Chirag_Banner" setup_version="1.0.1" />
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Backend/etc/menu.xsd">
<menu>
<add id="chirag_banner::core" title="Banner Create" module="Chirag_Banner" sortOrder="40" resource="Chirag_Banner::sample"/>
<add id="chirag_banner::test" title="Upload Banner" module="Chirag_Banner" sortOrder="10" parent="chirag_banner::core" action="chirag_banner/post/" resource="Chirag_Banner::post"/>
</menu>
</config>
etc->adminhtml->routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="admin">
<route id="chirag_banner" frontName="chirag_banner">
<module name="Chirag_Banner" />
</route>
</router>
</config>
Setup->InstallSchema.php
<?php
namespace Chirag\Banner\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
/**
* Creating table chirag_banner_table
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('chirag_banner_table')
)->addColumn(
'banner_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Banner Id'
)->addColumn(
'imagename',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => false],
'Image Name'
)->addColumn(
'imagepath',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => false],
'Image Path'
)->addColumn(
'imagedata',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
['nullable' => false],
'Image Data Content'
)->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
1,
['nullable' => true,'default' => 1],
'Status'
)->addColumn(
'created_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false],
'Created At'
)->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['nullable' => false],
'Updated At'
)->setComment(
'Chirag Banner Table'
);
$installer->getConnection()->createTable($table);
$installer->endSetup();
}
}
Ui_Component->Listing->Column->BannerActions.php
<?php
namespace Chirag\Banner\Ui_Component\Listing\Column;
class BannerActions extends \Magento\Ui\Component\Listing\Columns\Column
{
const URL_PATH_EDIT = 'chirag_banner/post/edit';
/**
* URL builder
*
* @var \Magento\Framework\UrlInterface
*/
protected $_urlBuilder;
/**
* constructor
*
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Magento\Framework\View\Element\UiComponent\ContextInterface $context
* @param \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory
* @param array $components
* @param array $data
*/
public function __construct(
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Framework\View\Element\UiComponent\ContextInterface $context,
\Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = []
)
{
$this->_urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
//print_r($item);
$item[$this->getData('name')] = [
'edit' => [
'href' => $this->_urlBuilder->getUrl(
static::URL_PATH_EDIT,
[
'id' => $item['banner_id']
]
),
'label' => __('Edit')
],
];
}
}
return $dataSource;
}
}
Ui_Component->Listing->Column->Thumbnail.php
<?php
namespace Chirag\Banner\Ui_Component\Listing\Column;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
class Thumbnail extends \Magento\Ui\Component\Listing\Columns\Column
{
const NAME = 'thumbnail';
const ALT_FIELD = 'name';
private $_getModel;
/**
* @var string
*/
private $editUrl;
private $_objectManager = null;
/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param \Chirag\Banner\Model\ResourceModel\Image $imageHelper
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
\Chirag\Banner\Model\ResourceModel\Image\Image $imageHelper,
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Framework\ObjectManagerInterface $objectManager,
array $components = [],
array $data = []
) {
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->imageHelper = $imageHelper;
$this->urlBuilder = $urlBuilder;
//$this->_getModel = $model;
$this->_objectManager = $objectManager;
}
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$fieldName = $this->getData('name');
foreach ($dataSource['data']['items'] as & $item) {
//$filename = 'myimage.png';
$filename = $item['imagepath'];;
$item[$fieldName . '_src'] = $this->imageHelper->getBaseUrl().$filename;
$item[$fieldName . '_alt'] = $this->getAlt($item) ?: $filename;
$item[$fieldName . '_orig_src'] = $this->imageHelper->getBaseUrl().$filename;
}
}
return $dataSource;
}
/**
* @param array $row
*
* @return null|string
*/
protected function getAlt($row)
{
$altField = $this->getData('config/altField') ?: self::ALT_FIELD;
return isset($row[$altField]) ? $row[$altField] : null;
}
}
?>
view->adminhtml->layout->chirag_banner_post_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<update handle="styles"/>
<body>
<referenceContainer name="content">
<uiComponent name="chirag_banner_post_listing"/>
</referenceContainer>
</body>
</page>
view->adminhtml->layout->chirag_banner_post_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<update handle="editor"/>
<body>
<referenceContainer name="left">
<block class="Chirag\Banner\Block\Adminhtml\Post\Edit\Tabs" name="chirag_banner_post_edit_tabs">
<block class="Chirag\Banner\Block\Adminhtml\Post\Edit\Tab\Main" name="chirag_banner_post_edit_tab_main"/>
<action method="addTab">
<argument name="name" xsi:type="string">main_section</argument>
<argument name="block" xsi:type="string">chirag_banner_post_edit_tab_main</argument>
</action>
</block>
</referenceContainer>
<referenceContainer name="content">
<block class="Chirag\Banner\Block\Adminhtml\Post\Edit" name="test_post_edit"/>
</referenceContainer>
</body>
</page>
view->adminhtml->ui_component->chirag_banner_post_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<!-- ... other block of code -->
<listingToolbar name="listing_top">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="sticky" xsi:type="boolean">true</item>
</item>
</argument>
<bookmark name="bookmarks"/>
<columnsControls name="columns_controls"/>
<filterSearch name="fulltext"/>
<filters name="listing_filters" />
<massaction name="listing_massaction">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
</item>
</argument>
<action name="delete">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">delete</item>
<item name="label" xsi:type="string" translate="true">Delete</item>
<item name="url" xsi:type="url" path="chirag_banner/post/massDelete"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Delete Post</item>
<item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
<paging name="listing_paging"/>
<exportButton name="export_button"/>
</listingToolbar>
<!-- ... other block of code -->
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">chirag_banner_post_listing.chirag_banner_post_listing_data_source</item>
<item name="deps" xsi:type="string">chirag_banner_post_listing.chirag_banner_post_listing_data_source</item>
</item>
<item name="spinner" xsi:type="string">spinner_columns</item>
<item name="buttons" xsi:type="array">
<item name="add" xsi:type="array">
<item name="name" xsi:type="string">add</item>
<item name="label" xsi:type="string" translate="true">Add New Post22</item>
<item name="class" xsi:type="string">primary</item>
<item name="url" xsi:type="string">*/*/new</item>
</item>
</item>
</argument>
<dataSource name="nameOfDataSource">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
<argument name="name" xsi:type="string">chirag_banner_post_listing_data_source</argument>
<argument name="primaryFieldName" xsi:type="string">banner_id</argument>
<argument name="requestFieldName" xsi:type="string">id</argument>
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
<item name="update_url" xsi:type="url" path="mui/index/render"/>
<item name="storageConfig" xsi:type="array">
<item name="indexField" xsi:type="string">banner_id</item>
</item>
</item>
</argument>
</argument>
</dataSource>
<columns name="spinner_columns">
<selectionsColumn name="ids">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="resizeEnabled" xsi:type="boolean">false</item>
<item name="resizeDefaultWidth" xsi:type="string">55</item>
<item name="indexField" xsi:type="string">banner_id</item>
</item>
</argument>
</selectionsColumn>
<column name="banner_id">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">textRange</item>
<item name="sorting" xsi:type="string">asc</item>
<item name="label" xsi:type="string" translate="true">ID</item>
</item>
</argument>
</column>
<column name="imagepath" class="Chirag\Banner\Ui_Component\Listing\Column\Thumbnail">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
<item name="sortable" xsi:type="boolean">false</item>
<item name="altField" xsi:type="string">title</item>
<item name="has_preview" xsi:type="string">1</item>
<item name="label" xsi:type="string" translate="true">Thumbnail</item>
</item>
</argument>
</column>
<column name="imagename">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="editor" xsi:type="array">
<item name="editorType" xsi:type="string">text</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
</item>
</item>
<item name="label" xsi:type="string" translate="true">Image Name</item>
</item>
</argument>
</column>
<column name="imagedata">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="editor" xsi:type="array">
<item name="editorType" xsi:type="string">text</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
</item>
</item>
<item name="label" xsi:type="string" translate="true">Image Description</item>
</item>
</argument>
</column>
<column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
<item name="label" xsi:type="string" translate="true">Created</item>
</item>
</argument>
</column>
<column name="updated_at" class="Magento\Ui\Component\Listing\Columns\Date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
<item name="label" xsi:type="string" translate="true">Modified</item>
</item>
</argument>
</column>
<actionsColumn name="actions" class="Chirag\Banner\Ui_Component\Listing\Column\BannerActions">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">banner_id</item>
<item name="urlEntityParamName" xsi:type="string">id</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing>
Model->Post.php
<?php
namespace Chirag\Banner\Model;
use Magento\Framework\Model\AbstractModel;
class Post extends AbstractModel
{
/**
* Define resource model
*/
protected function _construct()
{
$this->_init('Chirag\Banner\Model\ResourceModel\Post');
}
}
?>
Model->ResourceModel->Post.php
<?php
namespace Chirag\Banner\Model\ResourceModel;
class Post extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Define main table
*/
protected function _construct()
{
$this->_init('chirag_banner_table', 'banner_id'); //here "chirag_banner_table" is table name and "banner_id" is the primary key of custom table
}
}
Model->ResourceModel->Image->Image.php
<?php
namespace Chirag\Banner\Model\ResourceModel\Image;
use Magento\Framework\UrlInterface;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
//protected $subDir = 'chirag/banner/image';
/**
* url builder
*
* @var \Magento\Framework\UrlInterface
*/
protected $urlBuilder;
/**
* @var \Magento\Framework\Filesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
//return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image/';
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]);
}
}
?>
Model->ResourceModel->Post->Collection.php
<?php
namespace Chirag\Banner\Model\ResourceModel\Post;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'banner_id';
/**
* Define model & resource model
*/
protected function _construct()
{
$this->_init(
'Chirag\Banner\Model\Post',
'Chirag\Banner\Model\ResourceModel\Post'
);
}
}
?>
Block->Adminhtml->Post.php
<?php
namespace Chirag\Banner\Block\Adminhtml;
class Post extends \Magento\Backend\Block\Widget\Grid\Container
{
/**
* Constructor
*
* @return void
*/
protected function _construct()
{
$this->_controller = 'post';
$this->_headerText = __('Post');
$this->_addButtonLabel = __('Add New Post12345');
parent::_construct();
}
}
Block->Adminhtml->Post->Edit.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post;
class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry = null;
/**
* @param \Magento\Backend\Block\Widget\Context $context
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Widget\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_coreRegistry = $registry;
parent::__construct($context, $data);
}
/**
* Initialize form
* Add standard buttons
* Add "Save and Continue" button
*
* @return void
*/
protected function _construct()
{
$this->_objectId = 'id';
$this->_controller = 'adminhtml_post';
$this->_blockGroup = 'Chirag_Banner';
parent::_construct();
$this->buttonList->add(
'save_and_continue_edit',
[
'class' => 'save',
'label' => __('Save and Continue Edit'),
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form']],
]
],
10
);
}
/**
* Getter for form header text
*
* @return \Magento\Framework\Phrase
*/
public function getHeaderText()
{
$item = $this->_coreRegistry->registry('current_chirag_banner_post');
if ($item->getId()) {
return __("Edit Banner '%1'", $this->escapeHtml($item->getImagename()));
} else {
return __('New Banner');
}
}
}
Block->Adminhtml->Post->Edit->Form.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post\Edit;
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* Constructor
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('banner_post_form');
$this->setTitle(__('Banner Information'));
}
/**
* Prepare form before rendering HTML
*
* @return $this
*/
protected function _prepareForm()
{
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form',
//'action' => $this->getUrl('chirag_events/items/save'),
'action' => $this->getUrl('chirag_banner/post/save'),
'method' => 'post',
'enctype' => 'multipart/form-data'
],
]
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
?>
Block->Adminhtml->Post->Edit->Tabs.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post\Edit;
class Tabs extends \Magento\Backend\Block\Widget\Tabs
{
/**
* Constructor
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('chirag_banner_post_edit_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(__('Banner'));
}
}
Block->Adminhtml->Post->Edit->Tab->Main.php
<?php
namespace Chirag\Banner\Block\Adminhtml\Post\Edit\Tab;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
class Main extends Generic implements TabInterface
{
protected $_wysiwygConfig;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
array $data = []
)
{
$this->_wysiwygConfig = $wysiwygConfig;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* {@inheritdoc}
*/
public function getTabLabel()
{
return __('Banner Information');
}
/**
* {@inheritdoc}
*/
public function getTabTitle()
{
return __('Banner Information');
}
/**
* {@inheritdoc}
*/
public function canShowTab()
{
return true;
}
/**
* {@inheritdoc}
*/
public function isHidden()
{
return false;
}
/*public function myfunction(){
echo "<script> alert('ram')</script>";
}*/
/**
* Prepare form before rendering HTML
*
* @return $this
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('current_chirag_banner_post');
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('banner_');
$dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
$timeFormat = $this->_localeDate->getTimeFormat(\IntlDateFormatter::SHORT);
$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Add Banner Data Here')]);
if ($model->getId()) {
$fieldset->addField('banner_id', 'hidden', ['name' => 'banner_id']);
}
$fieldset->addField(
'imagename',
'text',
['name' => 'imagename', 'label' => __('Image Name'), 'title' => __('Image Name'), 'required' => true]
);
/*$fieldset->addField(
'imagedata',
'text',
['name' => 'imagedata', 'label' => __('Image Details'), 'title' => __('Image Details'), 'required' => true]
);*/
$fieldset->addField(
'imagedata',
'editor',
[
'name' => 'imagedata',
'label' => __('Content'),
'title' => __('Content'),
'style' => 'height:26em;',
'required' => true,
'config' => $this->_wysiwygConfig->getConfig(),
'wysiwyg' => true
]
);
$fieldset->addField(
'imagepath',
'image',
['name' => 'imagepath', 'label' => __('Image Upload'), 'title' => __('Image Upload'), 'required' => true]
);
// $fieldset->addField(
// 'date',
// 'date',
// ['name' => 'date', 'label' => __('Choose Date'), 'title' => __('Choose Date'), 'required' => true, 'date_format' => $dateFormat]
// );
// $fieldset->addField(
// 'savedata',
// 'button',
// ['name' => 'savedata', 'label' => __('Save Data'), 'title' => __('Save Data'), 'onclick' => 'myfunction()']
// );
/* $fieldset->addField(
'image',
'image',
[
'name' => 'image',
'label' => __('Image'),
'title' => __('Image'),
'required' => false
]
); */
/* $fieldset->addField(
'status',
'select',
['name' => 'status', 'label' => __('Status'), 'title' => __('Status'), 'options' => [0 => 'Disable', 1 => 'Enable'], 'required' => true]
); */
/* $fieldset->addField(
'content',
'editor',
[
'name' => 'content',
'label' => __('Content'),
'title' => __('Content'),
'style' => 'height:26em;',
'required' => true,
'config' => $this->_wysiwygConfig->getConfig(),
'wysiwyg' => true
]
); */
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
}
Controller->Adminhtml->Post.php
<?php
namespace Chirag\Banner\Controller\Adminhtml;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;
/**
* Items controller
*/
abstract class Post extends \Magento\Backend\App\Action
{
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* @var \Magento\Backend\Model\View\Result\ForwardFactory
*/
protected $resultForwardFactory;
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
protected $uploaderFactory;
protected $adapterFactory;
protected $filesystem;
/**
* Initialize Group Controller
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
DirectoryList $directoryList,
UploaderFactory $uploaderFactory,
AdapterFactory $adapterFactory,
Filesystem $filesystem,
\Magento\Framework\Filesystem\Driver\File $file
) {
$this->_coreRegistry = $coreRegistry;
parent::__construct($context);
$this->resultForwardFactory = $resultForwardFactory;
$this->resultPageFactory = $resultPageFactory;
$this->directoryList = $directoryList;
$this->uploaderFactory = $uploaderFactory;
$this->adapterFactory = $adapterFactory;
$this->filesystem = $filesystem;
$this->_file = $file;
}
/**
* Initiate action
*
* @return this
*/
protected function _initAction()
{
$this->_view->loadLayout();
$this->_setActiveMenu('Chirag_Banner::post')->_addBreadcrumb(__('Post'), __('Post'));
return $this;
}
/**
* Determine if authorized to perform group actions.
*
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Chirag_Banner::post');
}
}
Controller->Adminhtml->Post->Index.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory = false;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->prepend((__('Postsss')));
return $resultPage;
}
}
Controller->Adminhtml->Post->Delete.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class Delete extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
$id = $this->getRequest()->getParam('id');
if ($id) {
try {
$model = $this->_objectManager->create('Chirag\Banner\Model\Post');
$model->load($id);
$model->delete();
$this->messageManager->addSuccess(__('You deleted the post.'));
$this->_redirect('chirag_banner/*/');
return;
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addError(
__('We can\'t delete post right now. Please review the log and try again.')
);
$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
$this->_redirect('chirag_banner/*/edit', ['id' => $this->getRequest()->getParam('id')]);
return;
}
}
$this->messageManager->addError(__('We can\'t find a post to delete.'));
$this->_redirect('chirag_banner/*/');
}
}
Controller->Adminhtml->Post->Edit.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class Edit extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
$id = $this->getRequest()->getParam('id');
$model = $this->_objectManager->create('Chirag\Banner\Model\Post');
if ($id) {
$model->load($id);
if (!$model->getId()) {
$this->messageManager->addError(__('This post no longer exists.'));
$this->_redirect('chirag_banner/*');
return;
}
}
// set entered data if was error when we do save
$data = $this->_objectManager->get('Magento\Backend\Model\Session')->getPageData(true);
if (!empty($data)) {
$model->addData($data);
}
$this->_coreRegistry->register('current_chirag_banner_post', $model);
$this->_initAction();
if ($model->getId()) {
$title = __('Edit Post');
} else {
$title = __('New Post Create Form');
}
$this->_view->getPage()->getConfig()->getTitle()->prepend($title);
$this->_view->getLayout()->getBlock('post_post_edit');
$this->_view->renderLayout();
}
}
Controller->Adminhtml->Post->MassDelete.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;
use Chirag\Banner\Model\ResourceModel\Post\CollectionFactory;
class MassDelete extends \Magento\Backend\App\Action
{
/**
* @var Filter
*/
protected $filter;
/**
* @var CollectionFactory
*/
protected $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
{
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
* @throws \Magento\Framework\Exception\LocalizedException|\Exception
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$collectionSize = $collection->getSize();
foreach ($collection as $record) {
$record->delete();
}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $collectionSize));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
Controller->Adminhtml->Post->MassStatus.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;
use Chirag\Banner\Model\ResourceModel\Post\CollectionFactory;
class MassStatus extends \Magento\Backend\App\Action
{
/**
* @var Filter
*/
protected $filter;
/**
* @var CollectionFactory
*/
protected $collectionFactory;
/**
* @param Context $context
* @param Filter $filter
* @param CollectionFactory $collectionFactory
*/
public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
{
$this->filter = $filter;
$this->collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Execute action
*
* @return \Magento\Backend\Model\View\Result\Redirect
* @throws \Magento\Framework\Exception\LocalizedException|\Exception
*/
public function execute()
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$collectionSize = $collection->getSize();
foreach ($collection as $record) {
$record->setStatus($this->getRequest()->getParam('status'))->save();
}
if($this->getRequest()->getParam('status') == 1){$status = 'enabled';}else{$status = 'disabled';}
$this->messageManager->addSuccess(__('A total of %1 record(s) have been '.$status, $collectionSize));
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
Controller->Adminhtml->Post->NewAction.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
class NewAction extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
$this->_forward('edit');
}
}
Controller->Adminhtml->Post->Save.php
<?php
namespace Chirag\Banner\Controller\Adminhtml\Post;
use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends \Chirag\Banner\Controller\Adminhtml\Post
{
public function execute()
{
if ($this->getRequest()->getPostValue()) {
try {
$model = $this->_objectManager->create('Chirag\Banner\Model\Post');
$data = $this->getRequest()->getPostValue();
//print_r($_FILES['imgtemp']['name']); exit("-----");
if(isset($_FILES['imagepath']['name']) && $_FILES['imagepath']['name'] != '') {
try{
$uploaderFactory = $this->uploaderFactory->create(['fileId' => 'imagepath']);
$uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$imageAdapter = $this->adapterFactory->create();
$uploaderFactory->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
$uploaderFactory->setAllowRenameFiles(true);
$uploaderFactory->setFilesDispersion(true);
$mediaDirectory = $this->filesystem->getDirectoryRead($this->directoryList::MEDIA);
$destinationPath = $mediaDirectory->getAbsolutePath('chirag/banner');
$result = $uploaderFactory->save($destinationPath);
if (!$result) {
throw new LocalizedException(
__('File cannot be saved to path: $1', $destinationPath)
);
}
$imagePath = 'chirag/banner'.$result['file'];
$data['imagepath'] = $imagePath;
} catch (\Exception $e) {$this->messageManager->addError(__('File is not uploaded !'));
}
}
if(isset($data['imagepath']['delete']) && $data['imagepath']['delete'] == 1) {
$mediaDirectory = $this->filesystem->getDirectoryRead($this->directoryList::MEDIA)->getAbsolutePath();
$file = $data['imagepath']['value'];
$imgPath = $mediaDirectory.$file;
if ($this->_file->isExists($imgPath)) {
$this->_file->deleteFile($imgPath);
}
$data['imagepath'] = NULL;
}
if (isset($data['imagepath']['value'])){
$data['imagepath'] = $data['imagepath']['value'];
}
$inputFilter = new \Zend_Filter_Input(
[],
[],
$data
);
$data = $inputFilter->getUnescaped();
$id = $this->getRequest()->getParam('id');
if ($id) {
$model->load($id);
if ($id != $model->getId()) {
throw new \Magento\Framework\Exception\LocalizedException(__('The wrong post is specified.'));
}
}
$timezone = $this->_objectManager->create('Magento\Framework\Stdlib\DateTime\TimezoneInterface');
$fromTz = $timezone->getConfigTimezone();
$toTz = $timezone->getDefaultTimezone();
$date = new \DateTime(date('m/d/Y'), new \DateTimeZone($fromTz));
$date->setTimezone(new \DateTimeZone($toTz));
$data['date'] = $date->format('m/d/Y H:i:s');
$timezone = $this->_objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
$data['updated_at'] = $timezone->gmtDate();
$model->setData($data);
$session = $this->_objectManager->get('Magento\Backend\Model\Session');
$session->setPageData($model->getData());
$model->save();
$this->messageManager->addSuccess(__('You saved the banner.'));
$session->setPageData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('chirag_banner/*/edit', ['id' => $model->getId()]);
return;
}
$this->_redirect('chirag_banner/*/');
return;
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
$id = (int)$this->getRequest()->getParam('id');
if (!empty($id)) {
$this->_redirect('chirag_banner/*/edit', ['id' => $id]);
} else {
$this->_redirect('chirag_banner/*/new');
}
return;
} catch (\Exception $e) {
$this->messageManager->addError(
__('Something went wrong while saving the banner data. Please review the error log.')
);
$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
$this->_objectManager->get('Magento\Backend\Model\Session')->setPageData($data);
$this->_redirect('chirag_banner/*/edit', ['id' => $this->getRequest()->getParam('id')]);
return;
}
}
$this->_redirect('chirag_banner/*/');
}
}