Commit 3a46d13e by halweg

Merge branch 'developer' into haowei/topmenu

parents 88ada62f 99a3b291
<?php
namespace Joshine\Banner\Block\Adminhtml\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class BackButton extends GenericButton implements ButtonProviderInterface
{
public function getButtonData()
{
// TODO: Implement getButtonData() method.
return [
'label'=> __('Back'),
'on_click' => sprintf("location.href='%s';",$this->getBackUrl()),
'class' => 'back',
'sort_order' => 10
];
}
public function getBackUrl(){
return $this->getUrl('*/*/');
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Block\Adminhtml\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class DeleteButton extends GenericButton implements ButtonProviderInterface
{
public function getButtonData()
{
// TODO: Implement getButtonData() method.
$data = [];
if ($this->getId()){
$data = [
'label' => __('Delete'),
'class' => 'delete primary',
'on_click' => 'deleteConfirm(\'' . __(
'Are you sure you want to do this?'
) . '\', \'' . $this->getDeleteUrl() . '\')',
'sort_order' => 20,
];
}
return $data;
}
public function getDeleteUrl()
{
return $this->getUrl('*/*/delete',['id'=>$this->getId()]);
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Block\Adminhtml\Edit;
use Magento\Backend\Block\Widget\Context;
use Magento\Framework\Exception\NoSuchEntityException;
class GenericButton
{
public function __construct(Context $context){
$this->context = $context;
}
public function getId(){
try {
return $this->context->getRequest()->getParam('id');
}catch (NoSuchEntityException $e){
}
return null;
}
public function getUrl($route = '',$params = []){
return $this->context->getUrlBuilder()->getUrl($route,$params);
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Block\Adminhtml\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class SaveButton extends GenericButton implements ButtonProviderInterface
{
public function getButtonData()
{
// TODO: Implement getButtonData() method.
return [
'label' => __('Save'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 90,
];
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Block;
use Joshine\Banner\Model\BassFactory;
class Index extends \Magento\Framework\View\Element\Template{
protected $collectionFactory;
protected $helper;
public function __construct(\Magento\Framework\View\Element\Template\Context $context,
\Joshine\Banner\Model\ResourceModel\Bass\CollectionFactory $collectionFactory,
\Joshine\Banner\Helper\Data $helper,
array $data = []
)
{
$this->collectionFactory = $collectionFactory;
$this->helper = $helper;
parent::__construct($context, $data);
}
public function getTitle(){
return 'hello banner';
}
public function getCollection(){
$collection = $this->collectionFactory->create();
if (!empty($this->getIds())){
$collection->addFieldToFilter('id',['in' => $this->getids()]);
}
$collection->addFieldToFilter('status',1);
$collection->setOrder('sort','desc');
return $collection;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Joshine\Banner\Model\BassFactory;
class Index extends \Magento\Framework\App\Action\Action{
protected $_pageFactory;
protected $_bassFactory;
public function __construct(Context $context,PageFactory $pageFactory, BassFactory $bassFactory)
{
$this->_bassFactory = $bassFactory;
$this->_pageFactory = $pageFactory;
return parent::__construct($context);
}
public function execute()
{
// TODO: Implement execute() method.
return $this->_pageFactory->create();
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Adminhtml\Index;
use \Magento\Backend\App\Action;
class Add extends Action
{
public function execute()
{
// TODO: Implement execute() method.
$this->_forward('edit');
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Adminhtml\Index;
use \Magento\Backend\App\Action;
class Delete extends Action
{
const ADMIN_RESOURCE = 'Joshine_Banner::index';
public function execute()
{
// TODO: Implement execute() method.
$id = $this->getRequest()->getParam('id');
if ($id > 0){
$model = $this->_objectManager->create('Joshine\Banner\Model\Bass');
$model->load($id);
try {
$model->delete();
$this->messageManager->addSuccessMessage(__('Deleted success.'));
}catch (\Exception $e){
$this->messageManager->addSuccess(__('Deleted error.'));
}
}
$this->_redirect('joshine_banner/index');
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Adminhtml\Index;
use \Magento\Backend\App\Action;
use \Magento\Backend\App\Action\Context;
use \Magento\Framework\View\Result\PageFactory;
use \Magento\Framework\Registry;
use Magento\Shipping\Model\Rate\ResultFactory;
use Joshine\Banner\Model\BassFactory;
class Edit extends Action
{
const ADMIN_RESOURCE = "Joshine_Banner::index";
protected $_coreRegistry;
protected $resultPageFactory;
protected $factory;
public function __construct
(
Context $context,
PageFactory $pageFactory,
Registry $registry,
BassFactory $factory
)
{
$this->factory = $factory;
$this->_coreRegistry = $registry;
$this->resultPageFactory = $pageFactory;
parent::__construct($context);
}
public function execute()
{
// TODO: Implement execute() method.
$id = $this->getRequest()->getParam('id');
$model = $this->_objectManager->create(\Joshine\Banner\Model\Bass::class);
if ($id){
$model->load($id);
if (!$model->getId()){
$this->messageManager->addErrorMessage(__('This banner no longer exists.'));
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('*/*/');
}
}
$this->_coreRegistry->register('banner',$model);
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->prepend($id? __('Edit Banner') : __('New Banner'));
return $resultPage;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Adminhtml\Index\FileUploader;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\UrlInterface;
use \Magento\Framework\Controller\ResultFactory;
class Save extends Action
{
const ADMIN_RESOURCE = "Joshine_Banner::index";
const FILE_DIR = 'joshine/banner';
protected $_fileUploaderFactory;
protected $_filesystem;
protected $mediaDirectory;
protected $storeManager;
protected $resultFactory;
public function __construct(
\Magento\Framework\Filesystem $filesystem,
\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
Action\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
ResultFactory $resultFactory
) {
$this->_filesystem = $filesystem;
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->resultFactory = $resultFactory;
parent::__construct($context);
}
public function execute()
{
try {
$imageId = $this->_request->getParam('param_name');
$uploader = $this->_fileUploaderFactory->create(['fileId' => $imageId]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(self::FILE_DIR );
$result = $uploader->save($path);
$result['path'] = $this->getMediaPath($result['file']);
$result['url'] = $this->getMediaUrl($result['file']);
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
} catch (LocalizedException $e) {
return ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
} catch (\Throwable $e) {
return ['error' => 'Something went wrong while saving the file(s).', 'errorcode' => 0];
}
}
protected function getMediaPath($file){
return '/' . $this->mediaDirectory->getRelativePath(self::FILE_DIR) . '/' . $this->prepareFile($file);
}
protected function getMediaUrl($file)
{
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. self::FILE_DIR . '/' . $this->prepareFile($file);
}
protected function prepareFile($file)
{
return ltrim(str_replace('\\', '/', $file), '/');
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Adminhtml\Index;
use \Magento\Backend\App\Action;
use \Magento\Backend\App\Action\Context;
use \Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
const ADMIN_RESOURCE = "Joshine_Banner::index";
protected $_resultPageFactory;
public function __construct(Context $context,Pagefactory $resultPageFactory)
{
parent::__construct($context);
$this->_resultPageFactory = $resultPageFactory;
}
public function execute()
{
// TODO: Implement execute() method.
$resultPage = $this->_resultPageFactory->create();
$resultPage->setActiveMenu('Joshine_Banner::index');
$resultPage->getConfig()->getTitle()->prepend((__('Banners')));
return $resultPage;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Controller\Adminhtml\Index;
use Magento\Backend\App\Action\Context;
use Joshine\Banner\Model\BassFactory;
class Save extends \Magento\Backend\App\Action
{
const ADMIN_RESOURCE = "Joshine_Banner::index";
protected $factory;
public function __construct(Context $context,BassFactory $factory)
{
$this->factory = $factory;
parent::__construct($context);
}
public function execute()
{
// TODO: Implement execute() method.
$data = $this->getRequest()->getPostValue();
if (!$data){
$this->_redirect('joshine_banner/index/add');
return;
}
$data['status'] = $data['active'];
if (isset($data['pcImage'][0]['path'])){
$data['img_patch'] = $data['pcImage'][0]['path'];
unset($data['pcImage']);
}
if (isset($data['phoneImage'][0]['path'])){
$data['phone_img_patch'] = $data['phoneImage'][0]['path'];
unset($data['phoneImage']);
}
unset($data['active']);
$rowData = $this->factory->create();
$rowData->setData($data);
if (isset($data['id'])){
$rowData->setEntityId($data['id']);
}
$rowData->save();
$this->messageManager->addSuccess(__('Row data has been successfully saved.'));
$this->_redirect('*/*/index');
}
}
<?php
namespace Joshine\Banner\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
class Data extends AbstractHelper
{
public function getStoreConfig(){
return true;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Model;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\DataObject\IdentityInterface;
class Bass extends AbstractModel implements IdentityInterface
{
const CACHE_TAG = 'joshine_banner_bass';
protected $_cacheTat = 'joshine_banner_bass';
protected $_eventPrefix = 'joshine_banner_bass';
protected function _construct()
{
$this->_init('Joshine\Banner\Model\ResourceModel\Bass');
}
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
public function getDefaultValues()
{
$values = [];
return $values;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
class Bass extends AbstractDb
{
public function __construct(Context $context)
{
parent::__construct($context);
}
protected function _construct()
{
$this->_init('joshine_banner_bass','id');
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Model\ResourceModel\Bass;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected $_idFieldName = 'id';
protected $_eventPrefix = 'joshine_banner_bass_collection';
protected $_eventObject = 'bass_collection';
protected function _construct(){
$this->_init('Joshine\Banner\Model\Bass','Joshine\Banner\Model\ResourceModel\Bass');
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Ui\Component\Listing\Column;
use Magento\Catalog\Helper\Image;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Listing\Columns\Column;
class ImgPatch extends \Magento\Ui\Component\Listing\Columns\Column
{
const ALT_FIELD = 'title';
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
protected $imageHelper;
protected $urlBuilder;
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
Image $imageHelper,
UrlInterface $urlBuilder,
StoreManagerInterface $storeManager,
array $components = [],
array $data = []
) {
$this->storeManager = $storeManager;
$this->imageHelper = $imageHelper;
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$fieldName = $this->getData('name');
foreach($dataSource['data']['items'] as &$item) {
$url = '';
if($item[$fieldName] != '') {
$url = $this->storeManager->getStore()->getBaseUrl(
UrlInterface::URL_TYPE_MEDIA
). $item[$fieldName];
}
$item[$fieldName . '_src'] = $url;
$item[$fieldName . '_orig_src'] = $url;
}
}
return $dataSource;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Ui\Component\Listing\Column;
use Magento\Catalog\Helper\Image;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Listing\Columns\Column;
class PhoneImagePatch extends \Magento\Ui\Component\Listing\Columns\Column
{
const ALT_FIELD = 'phone_img_patch';
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
protected $imageHelper;
protected $urlBuilder;
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
Image $imageHelper,
UrlInterface $urlBuilder,
StoreManagerInterface $storeManager,
array $components = [],
array $data = []
) {
$this->storeManager = $storeManager;
$this->imageHelper = $imageHelper;
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$fieldName = $this->getData('name');
foreach($dataSource['data']['items'] as &$item) {
$url = '';
if($item[$fieldName] != '') {
$url = $this->storeManager->getStore()->getBaseUrl(
UrlInterface::URL_TYPE_MEDIA
). $item[$fieldName];
}
$item[$fieldName . '_src'] = $url;
$item[$fieldName . '_orig_src'] = $url;
}
}
return $dataSource;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Ui\Component\Listing\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;
class PostActions extends Column
{
const URL_EDIT='joshine_banner/index/edit';
const URL_DELETE = 'joshine_banner/index/delete';
protected $urlBuilder;
public function __construct(ContextInterface $context, UiComponentFactory $uiComponentFactory, array $components = [], array $data = [],UrlInterface $urlBuilder)
{
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
// TODO: Change the autogenerated stub
if (isset($dataSource['data']['items'])){
foreach ($dataSource['data']['items'] as &$item){
if (isset($item)){
$item[$this->getData('name')] = [
'edit'=>[
'href' => $this->urlBuilder->getUrl(self::URL_EDIT,['id'=>$item['id']]),
'label' => __('Edit')
],
'delete'=>[
'href' => $this->urlBuilder->getUrl(self::URL_DELETE,['id'=>$item['id']]),
'label' => __('Delete'),
'confirm' => [
'title' => __('Delete'),
'message' => __('Are you sure you wan\'t to delete record?')
]
]
];
}
}
}
return $dataSource;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\Ui\Component\Listing\Column;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
class Status extends \Magento\Ui\Component\Listing\Columns\Column
{
public function __construct(ContextInterface $context, UiComponentFactory $uiComponentFactory, array $components = [], array $data = [])
{
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
// TODO: Change the autogenerated stub
if (isset($dataSource['data']['items'])){
foreach ($dataSource['data']['items'] as & $item){
$item['status'] = $item['status'] ==1 ? __('YES'):__('NO');
}
}
return $dataSource;
}
}
\ No newline at end of file
<?php
namespace Joshine\Banner\UiForm\Model;
use Magento\Ui\DataProvider\AbstractDataProvider;
use Magento\Framework\App\RequestInterface;
use Joshine\Banner\Model\ResourceModel\Bass\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
class DataProvider extends AbstractDataProvider
{
protected $_request;
protected $collection;
protected $loadedData;
protected $storeManager;
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
array $meta = [],
array $data = [],
RequestInterface $request,
CollectionFactory $collectionFactory,
StoreManagerInterface $storeManager
)
{
$this->storeManager = $storeManager;
$this->collection = $collectionFactory->create();
$this->_request = $request;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
}
public function getData()
{
if (isset($this->loadedData)) {
return $this->loadedData;
}
$id = $this->_request->getParam('id');
$items = $this->collection->getItems();
foreach ($items as $item) {
$this->loadedData[$item->getId()] = $item->getData();
$m['active'] = $item->getStatus();
$imgPatch = $item->getImgPatch();
if ($imgPatch) {
$m['pcImage'][0]['name'] = $this->getFileName($imgPatch);
$m['pcImage'][0]['url'] = $this->getMediaUrl($imgPatch);
$m['pcImage'][0]['type'] = 'image';
}
$phoneImg = $item->getPhoneImgPatch();
if ($phoneImg){
$m['phoneImage'][0]['name'] = $this->getFileName($phoneImg);
$m['phoneImage'][0]['url'] = $this->getMediaUrl($phoneImg);
$m['phoneImage'][0]['type'] = 'image';
$m['phoneImage'][0]['size'] = '20kb';
}
$this->loadedData[$item->getId()] = array_merge($this->loadedData[$item->getId()],$m);
}
return $this->loadedData;
}
public function getMediaUrl($fileName)
{
$mediaUrl = $this->storeManager->getStore() ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).$fileName;
return $mediaUrl;
}
public function getFileName($name){
$info = basename($name);
return $info;
}
}
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Magento_Backend::joshine" title="Jpshone" sortOrder="40">
<resource id="Magento_Backend::Joshine_banner" title="Banner" sortOrder="10">
<resource id="Joshine_Banner::index" title="Index" sortOrder="10"></resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
<add
id="Magento_Backend::joshine"
title="Joshine"
module="Magento_Backend"
sortOrder="99"
resource="Magento_Backend::joshine"
/>
<add
id="Magento_Backend::joshine_banner"
title="Joshine"
translate="title"
module="Magento_Backend"
sortOrder="10"
parent="Magento_Backend::joshine"
resource="Magento_Backend::joshine_banner"
/>
<add
id="Joshine_Banner::joshine"
title="Banner"
module="Joshine_Banner"
sortOrder="10"
parent="Magento_Backend::joshine_banner"
action="joshine_banner/index/index"
resource="Joshine_Banner::index"
/>
<add id="Sparsh_FreeShippingBar::free_shipping_bar_management"
title="Free Shipping Bar"
translate="title"
action="sparsh_free_shipping_bar/entity"
module="Sparsh_FreeShippingBar"
parent="Magento_Backend::joshine_banner"
sortOrder="20"
resource="Sparsh_FreeShippingBar::free_shipping_bar_management"
dependsOnConfig="sparsh_free_shipping_bar/general/enable"/>
</menu>
</config>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="joshine_banner" frontName="joshine_banner">
<module name="Joshine_Banner"/>
</route>
</router>
</config>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="joshine" translate="label" sortOrder="100">
<label>Joshine</label>
</tab>
<section id="joshine_banner" translate="label" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<class>separator-top</class>
<label>Banner</label>
<tab>joshine</tab>
<resource>Joshine_Banner::configuration</resource>
<group id="options" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Options</label>
<field id="autoplay" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Autoplay</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment></comment>
</field>
<field id="loop" translate="label" type="select" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Loop</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<comment></comment>
</field>
</group>
</section>
</system>
</config>
\ No newline at end of file
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<joshine_banner>
<options>
<autoplay>1</autoplay>
<loop>1</loop>
</options>
</joshine_banner>
</default>
</config>
\ No newline at end of file
<?xml version="1.0" ?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd" >
<table name="joshine_banner_bass">
<column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" comment="ID" identity="true" />
<column xsi:type="varchar" name="title" default="" nullable="false" length="255" comment="TITLE" />
<column xsi:type="smallint" name="status" default="1" nullable="false" padding="2" comment="STATUS 1=ENABLE 0=DISABLE"/>
<column xsi:type="varchar" name="desc" default="" nullable="false" length="255" comment="DESC" />
<column xsi:type="varchar" name="url" default="" nullable="false" length="255" comment="URL" />
<column xsi:type="smallint" name="sort" default="0" nullable="false" padding="2" comment="SORT" />
<column xsi:type="varchar" name="img_patch" default="" nullable="false" length="255" comment="IMG PATCH" />
<column xsi:type="varchar" name="phone_img_patch" default="" nullable="false" length="255" comment="IMG PATCH" />
<column xsi:type="timestamp" name="created_at" default="CURRENT_TIMESTAMP" on_update="false" comment="CREATED AT" />
<column xsi:type="timestamp" name="updated_at" default="CURRENT_TIMESTAMP" on_update="true" comment="UPDATED AT" />
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="id" />
</constraint>
</table>
</schema>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="joshine_banner_index_listing_data_source" xsi:type="string">Joshine\Banner\Model\ResourceModel\Bass\Grid\Collection</item>
</argument>
</arguments>
</type>
<virtualType name="Joshine\Banner\Model\ResourceModel\Bass\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">joshine_banner_bass</argument>
<argument name="resourceModel" xsi:type="string">Joshine\Banner\Model\ResourceModel\Bass</argument>
</arguments>
</virtualType>
</config>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd" >
<router id="standard">
<route frontName="banner" id="banner">
<module name="Joshine_Banner"/>
</route>
</router>
</config>
\ No newline at end of file
<?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="Joshine_Banner" setup_version="1.0.0" />
</config>
\ No newline at end of file
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Joshine_Banner',
__DIR__
);
\ No newline at end of file
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<uiComponent name="joshine_banner_index_form"/>
</referenceContainer>
</body>
</page>
\ No newline at end of file
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<uiComponent name="joshine_banner_index_listing"/>
</referenceContainer>
</body>
</page>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">joshine_banner_index_form.joshine_banner_index_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Banner</item>
<item name="template" xsi:type="string">templates/form/collapsible</item>
</argument>
<settings>
<buttons>
<button name="save" class="Joshine\Banner\Block\Adminhtml\Edit\SaveButton"></button>
<button name="delete" class="Joshine\Banner\Block\Adminhtml\Edit\DeleteButton"></button>
<button name="back" class="Joshine\Banner\Block\Adminhtml\Edit\BackButton"></button>
</buttons>
<namespace>joshine_banner_index_form</namespace>
<dataScope>data</dataScope>
<deps>
<dep>joshine_banner_index_form.joshine_banner_index_form_data_source</dep>
</deps>
</settings>
<dataSource name="joshine_banner_index_from_data_source">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
<settings>
<submitUrl path="joshine_banner/index/save"/>
</settings>
<dataProvider class="Joshine\Banner\UiForm\Model\DataProvider" name="joshine_banner_index_form_data_source">
<settings>
<requestFieldName>id</requestFieldName>
<primaryFieldName>id</primaryFieldName>
</settings>
</dataProvider>
</dataSource>
<fieldset name="general">
<settings>
<label></label>
</settings>
<!--select选择框-->
<field name="active" sortOrder="0" formElement="select">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>number</dataType>
<label translate="true">Active</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="title" sortOrder="10" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Title</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="desc" sortOrder="20" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Description</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="url" sortOrder="30" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Url</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="pcImage" sortOrder="40" formElement="imageUploader">
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">PC Image</label>
<visible>true</visible>
<required>true</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="joshine_banner/index_fileUploader/save"/>
</uploaderConfig>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
<field name="phoneImage" sortOrder="50" formElement="imageUploader">
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">Phone Image</label>
<visible>true</visible>
<required>true</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="joshine_banner/index_fileUploader/save"/>
</uploaderConfig>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
<field name="sort" sortOrder="60" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Sort</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
</fieldset>
</form>
\ No newline at end of file
<?xml version="1.0" ?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<!--配置声明旧的组件结构 settings节点进行替换和配置 name=data必须 可嵌套-->
<argument name="data" xsi:type="array">
<!--所有其他子节点都声明为项。<item name="config"> ...</item>包含描述当前 UI 组件配置的子节点。请注意,尽管所有组件的配置都不同,但不同组件的基本属性基本相同。例如,我们可以使用<item name="component">...</item>定义哪个 JS 文件将用作上述示例中的 Fieldset UI 组件的模型。对该 JS 文件的引用可以是该文件的完整路径,也可以是require.js配置中定义的别名。在这个例子中,我们只展示了可能配置的一小部分。
包含该项添加和声明了组件
-->
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">joshine_banner_index_listing.joshine_banner_index_listing_data_source</item>
<item name="deps" xsi:type="string">joshine_banner_index_listing.joshine_banner_index_listing_data_source</item>
</item>
<!--组件的名称 [ComponentName].[ComponentName]_data_source -->
<item name="spinner" xsi:type="string">joshine_banner_items_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 Banner</item>
<item name="class" xsi:type="string">primary</item>
<item name="url" xsi:type="string">*/*/add</item>
</item>
</item>
</argument>
<!--数据源 component属性注册的magento组件名称-->
<dataSource name="joshine_banner_index_listing_data_source" component="Magento_Ui/js/grid/provider">
<!--声明新的结构-->
<settings>
<updateUrl path="mui/index/render" />
</settings>
<!--<aclResource>Joshine::Banner<aclResource/> 数据提供者 名称-->
<dataProvider class="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider" name="joshine_banner_index_listing_data_source">
<settings>
<!--请求字段名一般为主键-->
<requestFieldName>id</requestFieldName>
<!--主键-->
<primaryFieldName>id</primaryFieldName>
</settings>
</dataProvider>
</dataSource>
<!-- 工具条 -->
<container name="listing_top">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="template" xsi:type="string">ui/grid/toolbar</item>
</item>
</argument>
<!--过滤器-->
<filters name="listing_filters"/>
<!--书签-->
<bookmark name="bookmark"/>
<!--控制显示字段-->
<columnsControls name="columns_controls"/>
<!--导出-->
<exportButton name="export_button"/>
<!--分页-->
<paging name="listing_paging"/>
</container>
<!-- 显示字段 columns name一定要改不然会出现load图片和遮罩层一直存在的bug -->
<columns name="joshine_banner_items_columns">
<column name="id">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
</item>
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">id</item>
<item name="filter" xsi:type="string">text</item>
<item name="sorting" xsi:type="string">desc</item>
<item name="label" xsi:type="string" translate="true">ID</item>
</item>
</argument>
</column>
<column name="title">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Title</item>
</item>
</argument>
</column>
<column name="desc">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Description</item>
<item name="resizeEnabled" xsi:type="boolean">true</item>
<item name="resizeDefaultWidth" xsi:type="string">60</item>
</item>
</argument>
</column>
<column name="url">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Url</item>
<item name="resizeEnabled" xsi:type="boolean">true</item>
<item name="resizeDefaultWidth" xsi:type="string">60</item>
</item>
</argument>
</column>
<column name="sort">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Sort</item>
</item>
</argument>
</column>
<column name="status" class="Joshine\Banner\Ui\Component\Listing\Column\Status">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Status</item>
</item>
</argument>
</column>
<column name="img_patch" class="Joshine\Banner\Ui\Component\Listing\Column\ImgPatch">
<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="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Pc Image patch</item>
</item>
</argument>
</column>
<column name="phone_img_patch" class="Joshine\Banner\Ui\Component\Listing\Column\PhoneImagePatch">
<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="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Phone Image patch</item>
</item>
</argument>
</column>
<actionsColumn name="actions" class="Joshine\Banner\Ui\Component\Listing\Column\PostActions">
<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">10</item>
<item name="indexField" xsi:type="string">id</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing>
\ No newline at end of file
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="Joshine\Banner\Block\Index" name="banner_index_index" template="Joshine_Banner::index.phtml" />
</referenceContainer>
</page>
\ No newline at end of file
var config = {
paths: {
'banner': 'Joshine_Banner/js/banner',
'owlcarousel': "Joshine_Banner/js/owl.carousel"
},
shim: {
'banner': ['jquery'],
'owlcarousel': ['jquery']
}
}
\ No newline at end of file
<?php
/** @var $block \Joshine\Banner\Block\Index */
$collection = $block->getCollection();
?>
<div class="banner1" style="background-color: #f0f0f0;height: 10px;"></div>
<?php foreach ($collection->getItems() as $item):?>
<?php echo $item->getData('name');?>
<?php endforeach;?>
<link rel="stylesheet" type="text/css" href="<?php echo $block->getViewFileUrl('Joshine_Banner::css/banner.css'); ?>">
<script type="text/javascript">
require(['jquery','banner'],function ($){
var img_arr =
[
<?php foreach ($collection->getItems() as $item):?>
[
<?php echo "'/media/" . $item->getData('img_patch') . "',";?>
<?php echo "'/media/" . $item->getData('phone_img_patch') . "',";?>
],
<?php endforeach;?>
];
var href = [
<?php foreach ($collection->getItems() as $item):?>
<?php echo "'" . $item->getData('url') . "',";?>
<?php endforeach;?>
];
jQuery('.banner1').banner({
img: img_arr,
href:href,
btn: true,
list: true,
autoPlay: true,
delayTime: 5000,
moveTime: 500,
index: 0
});
window.onload = function (){
var h_max = 0;
$('.top_banner').each(function (i,v){
var h = $(this).height();
h_max = h > h_max ? h : h_max;
});
$('.banner1').height(h_max);
$('.banner1').css('line-height',h_max+'px');
var buttonTop = h_max/2;
$('#left').css({'top':buttonTop,'line-height': 0});
$('#right').css({'top':buttonTop,'line-height': 0});
}
});
</script>
\ No newline at end of file
.banner1,.banner1 >.imgbox, .banner1 >.imgbox > a, .banner1 >.imgbox > a >img{
height: 634px;
}
.top_banner{
width: 100%;
}
input#left,input#right {
top:300px;
padding-top: 2px;
}
@media (max-width: 768px) {
.banner1, .banner1 > .imgbox, .banner1 > .imgbox > a, .banner1 > .imgbox > a > img,.top_banner {
height: 577px;
}
input#left, input#right {
top:280px;
padding: 1px;
}
}
@media (max-width: 1024px) {
.rating-result::before, .rating-result>span::before {
-webkit-mask-size: 1rem 1rem;
}
.rating-result{
width: 5rem;
height: 1rem;
}
p.flashsale-title{
font-size: 18px;
}
}
\ No newline at end of file
define(['jquery'],function ($){
$.fn.banner = function(options){
var that = this;
options = options || {};
this._obj = {
btn:options.btn===false ? false : true,
list:options.list===false ? false : true,
autoPlay:options.autoPlay===false ? false : true,
delayTime:options.delayTime || 2000,
moveTime:options.moveTime || 200,
index:options.index || 0,
iPrev:options.img.length-1,
img:options.img || [],
href:options.href || [],
};
this._obj.init = function(){
var str = ``;
for(var i=0;i<this.img.length;i++){
str += `<a href="${this.href[i]}"><picture>
<source media="(max-width: 768px)" srcset="${this.img[i][1]}" />
<source media="(min-width: 769px)" srcset="${this.img[i][0]}" />
<img src="${this.img[i][0]}" loading="lazy" class="top_banner" /></picture></a>`
}
that.html(`<div class="imgbox">${str}</div>`).css({
"width":"100%",
"height":"auto",
position:"relative",
overflow:"hidden"
}).children(".imgbox").css({
"width":"100%",
}).children("a").css({
position: "absolute",
left:1920,
top:0,
"width":"100%",
}).eq(0).css({
left:0
}).end().children("img").css({
"width":"100%",
});
}
this._obj.init();
this._obj.leftClick=function () {
if (that._obj.index ==0){
that._obj.index = that._obj.img.length-1;
that._obj.iPrev=0;
}else{
that._obj.index--;
that._obj.iPrev=that._obj.index+1;
}
that._obj.btnMove(1);
}
this._obj.rightClick=function(){
if (that._obj.index ==that._obj.img.length-1){
that._obj.index = 0;
that._obj.iPrev=that._obj.img.length-1;
}else{
that._obj.index++;
that._obj.iPrev=that._obj.index-1;
}
that._obj.btnMove(-1);
}
if (this._obj.btn){
$("<input type='button' id='left' value='<'>").css({
left:0,
}).appendTo(this).
after($("<input type='button' id='right' value='>'>").css({
right:0,
})).parent()
.children("input").css({
position:"absolute",
width:30,
height:30,
border:"none",
background:"rgba(200,200,200,0.5)",
borderRadius:"50%",
color:"#ffffff"
})
this.on("click","#left",that._obj.leftClick)
this.on("click","#right",that._obj.rightClick)
this._obj.btnMove=function (type) {
let imgs=that.children(".imgbox").children("a");
imgs.eq(this.iPrev).css({
left:0
}).stop().animate({
left:imgs.eq(0).width()*type
},this.moveTime).end().eq(this.index).css({
left:-imgs.eq(0).width()*type
}).stop().animate({
left:0
},this.moveTime)
if(!this.list) return;
$(".list").children("li").css("background","rgba(200,200,200,0.6)")
.eq(this.index).css("background","#005caf")
}
}
if (this._obj.list){
let str="";
for (var i=0;i<this._obj.img.length;i++){
str+=`<li></li>`;
}
$("<ul class='list'>").html(str).appendTo(this).css({
margin:0,
padding:0,
listStyle:"none",
width:"100%",
height:40,
bottom:0,
position:"absolute",
display:"flex",
justifyContent:"center",
lineHeight:"40px",
textAlign:"center"
}).children("li").css({
width:40,
height:6,
background:"rgba(200,200,200,0.6)",
margin:"0 5px",
textAlign: "center",
cursor:"pointer"
}).eq(0).css({
background:"#005caf"
}).end().click(function () {
if ($(this).index()>that._obj.index){
that._obj.listMove($(this).index(),-1)
}
if ($(this).index()<that._obj.index){
that._obj.listMove($(this).index(),1)
}
that._obj.index = $(this).index();
})
this._obj.listMove=function (iNow,type) {
let imgs=that.children(".imgbox").children("a");
imgs.eq(this.index).css({
left:0
}).stop().animate({
left:imgs.eq(0).width()*type
},this.moveTime).end().eq(iNow).css({
left:-imgs.eq(0).width()*type
}).stop().animate({
left:0
},this.moveTime)
$(".list").children("li").css("background","rgba(200,200,200,0.6)")
.eq(iNow).css("background","#005caf")
}
}
if (this._obj.autoPlay){
this._obj.t=setInterval(()=>{
this._obj.rightClick();
},this._obj.delayTime);
this.hover(function () {
clearInterval(that._obj.t)
},function () {
that._obj.t=setInterval(()=>{
that._obj.rightClick();
},that._obj.delayTime);
})
}
}
});
\ No newline at end of file
<?php
namespace Sparsh\FreeShippingBar\Api\Data;
/**
* Interface EntityInterface
* @package Sparsh\FreeShippingBar\Api\Data
*/
interface EntityInterface
{
/**
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const ENTITY_ID = 'entity_id';
const ENTITY_NAME = 'name';
const FROM_DATE = 'from_date';
const TO_DATE = 'to_date';
const GOAL = 'goal';
const INITIAL_GOAL_MESSAGE = 'initial_goal_message';
const ACHIEVE_GOAL_MESSAGE = 'achieve_goal_message';
const IS_CLICKABLE = 'is_clickable';
const BAR_LINK_URL = 'bar_link_url';
const IS_LINK_OPEN_IN_NEW_PAGE = 'is_link_open_in_new_page';
const BAR_BACKGROUND_COLOR = 'bar_background_color';
const BAR_TEXT_COLOR = 'bar_text_color';
const GOAL_TEXT_COLOR = 'goal_text_color';
const BAR_FONT_SIZE = 'bar_font_size';
const BAR_LAYOUT_POSITION = 'bar_layout_position';
const IS_ACTIVE = 'is_active';
const SORT_ORDER = 'sort_order';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
/**
* Get bar entity id.
*
* @return int|null
*/
public function getEntityId();
/**
* Set bar entity id.
*
* @param int $entityId
* @return $this
*/
public function setEntityId($entityId);
/**
* Get bar entity name.
*
* @return string
*/
public function getName();
/**
* Set bar entity name.
*
* @param string $name
* @return $this
*/
public function setName($name);
/**
* Get the start date when the bar entity is active.
*
* @return string|null
*/
public function getFromDate();
/**
* Set the start date when the bar entity is active.
*
* @param string $fromDate
* @return $this
*/
public function setFromDate($fromDate);
/**
* Get the end date when the bar entity is active
*
* @return string|null
*/
public function getToDate();
/**
* Set the end date when the bar entity is active.
*
* @param string $toDate
* @return $this
*/
public function setToDate($toDate);
/**
* Get goal value.
*
* @return string
*/
public function getGoal();
/**
* Set goal value.
*
* @param string $goal
* @return $this
*/
public function setGoal($goal);
/**
* Get initial goal message.
*
* @return string
*/
public function getInitialGoalMessage();
/**
* Set initial goal message.
*
* @param string $initialgoalMessage
* @return $this
*/
public function setInitialGoalMessage($initialgoalMessage);
/**
* Get achieve goal message.
*
* @return string
*/
public function getAchieveGoalMessage();
/**
* Set achieve goal message.
*
* @param string $achievegoalMessage
* @return $this
*/
public function setAchieveGoalMessage($achievegoalMessage);
/**
* Whether the bar is clickable.
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function isClickable();
/**
* Set whether the bar is clickable.
*
* @param bool isClickable
* @return bool
*/
public function setIsClickable($isClickable);
/**
* Get bar link url.
*
* @return string
*/
public function getBarLinkUrl();
/**
* Set bar link url.
*
* @param string $barLinkUrl
* @return $this
*/
public function setBarLinkUrl($barLinkUrl);
/**
* Whether the bar link opens in new page.
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function isLinkOpenInNewPage();
/**
* Set whether the bar link opens in new page.
*
* @param bool $isLinkOpenInNewPage
* @return bool
*/
public function setIsLinkOpenInNewPage($isLinkOpenInNewPage);
/**
* Get bar background color.
*
* @return string
*/
public function getBarBackgroundColor();
/**
* Set bar background color.
*
* @param string $barBackgroundColor
* @return $this
*/
public function setBarBackgroundColor($barBackgroundColor);
/**
* Get bar background color.
*
* @return string
*/
public function getBarTextColor();
/**
* Set bar text color.
*
* @param string $barTextColor
* @return $this
*/
public function setBarTextColor($barTextColor);
/**
* Get goal text color.
*
* @return string
*/
public function getGoalTextColor();
/**
* Set goal text color.
*
* @param string $goalTextColor
* @return $this
*/
public function setGoalTextColor($goalTextColor);
/**
* Get bar font size.
*
* @return string
*/
public function getBarFontSize();
/**
* Set bar font size.
*
* @param string $barFontSize
* @return $this
*/
public function setBarFontSizer($barFontSize);
/**
* Get bar layout position.
*
* @return string
*/
public function getBarLayoutPosition();
/**
* Set bar layout position.
*
* @param string $barLayoutPosition
* @return $this
*/
public function setBarLayoutPosition($barLayoutPosition);
/**
* Whether the bar entity is active.
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function isActive();
/**
* Set whether the bar entity is active.
*
* @param bool $isActive
* @return bool
*/
public function setIsActive($isActive);
/**
* Get sort order.
*
* @return int
*/
public function getSortOrder();
/**
* Set sort order.
*
* @param int $sortOrder
* @return $this
*/
public function setSortOrder($sortOrder);
/**
* Get bar entity creation date and time.
*
* @return string|null
*/
public function getCreatedAt();
/**
* Set bar entity creation date and time.
*
* @param string $createdAt
* @return $this
*/
public function setCreatedAt($createdAt);
/**
* Get bar entity last update date and time.
*
* @return string|null
*/
public function getUpdatedAt();
/**
* Set bar entity last update date and time.
*
* @param string $updatedAt
* @return $this
*/
public function setUpdatedAt($updatedAt);
}
<?php
namespace Sparsh\FreeShippingBar\Block\Adminhtml\Entity;
/**
* Class Edit
* @package Sparsh\FreeShippingBar\Block\Adminhtml\Entity
*/
class Edit extends \Magento\Backend\Block\Widget\Form\Container
{
/**
* Initialize form.
*
* @return void
*/
protected function _construct()
{
$this->_objectId = 'entity_id';
$this->_blockGroup = 'Sparsh_FreeShippingBar';
$this->_controller = 'adminhtml_entity';
parent::_construct();
if ($this->_isAllowedAction('Sparsh_FreeShippingBar::free_shipping_bar_management')) {
$this->buttonList->add(
'saveandcontinue',
[
'label' => __('Save and Continue Edit'),
'class' => 'save',
'data_attribute' => [
'mage-init' => [
'button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form'],
],
]
],
-100
);
} else {
$this->buttonList->remove('save');
$this->buttonList->remove('delete');
}
}
/**
* Check permission for passed action.
*
* @param string $resourceId
* @return bool
*/
protected function _isAllowedAction($resourceId)
{
return $this->_authorization->isAllowed($resourceId);
}
}
<?php
namespace Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit;
/**
* Class Form
* @package Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit
*/
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* Prepare form before rendering HTML.
*
* @return \Magento\Integration\Block\Adminhtml\Integration\Edit\Form
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _prepareForm()
{
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post','enctype'=>'multipart/form-data']]
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
<?php
namespace Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab;
use Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
/**
* Class Main
* @package Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab
*/
class Main extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* @var \Magento\Store\Model\System\Store
*/
protected $_systemStore;
/**
* @var \Magento\Customer\Ui\Component\Listing\Column\Group\Options
*/
private $_customerGroup;
/**
* Main constructor.
*
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Data\FormFactory $formFactory
* @param \Magento\Store\Model\System\Store $systemStore
* @param \Magento\Customer\Ui\Component\Listing\Column\Group\Options $customerGroup
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Magento\Customer\Ui\Component\Listing\Column\Group\Options $customerGroup,
array $data = []
) {
parent::__construct($context, $registry, $formFactory, $data);
$this->_systemStore = $systemStore;
$this->_customerGroup = $customerGroup;
}
/**
* Set form id prefix, declare fields for shipping bar info.
*
* @return \Magento\Backend\Block\Widget\Form\Generic
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _prepareForm()
{
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
);
$form->setHtmlIdPrefix('sparsh_free_shipping_bar_entity_');
$model = $this->_coreRegistry->registry(Entity::REGISTRY_KEY_CURRENT_ENTITY);
$this->_addGeneralFieldset($form, $model);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
/**
* @param \Magento\Framework\Data\Form $form
* @param $model
*/
protected function _addGeneralFieldset(\Magento\Framework\Data\Form $form, $model)
{
$fieldset = $form->addFieldset('general_fieldset', ['legend' => __('Shipping Bar Information')]);
$isElementDisabled = !$this->_isAllowedAction(Entity::ADMIN_RESOURCE);
if ($model->getEntityId()) {
$fieldset->addField(
'entity_id',
'hidden',
[
'name' => 'entity_id'
]
);
} else {
if (!$model->hasData('is_active')) {
$model->setData('is_active', $isElementDisabled ? '0' : '1');
$model->setIsActive(1);
}
}
$fieldset->addField(
'name',
'text',
[
'label' => __('Name'),
'title' => __('Name'),
'name' => 'name',
'required' => true,
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'is_active',
'select',
[
'label' =>__('Status'),
'title' => __('Status'),
'name' => 'is_active',
'required' => true,
'options' => ['1' => __('Enabled'), '0' => __('Disabled')],
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'sort_order',
'text',
[
'label' => __('Priority'),
'title' => __('Priority'),
'name' => 'sort_order',
'class' => 'validate-number',
'disabled' => $isElementDisabled
]
);
if (!$this->_storeManager->hasSingleStore()) {
$field = $fieldset->addField(
'store_id',
'multiselect',
[
'label' => __('Store Views'),
'title' => __('Store Views'),
'name' => 'store_id',
'required' => true,
'values' => $this->_systemStore->getStoreValuesForForm(false, true),
'disabled' => $isElementDisabled
]
);
$renderer = $this->getLayout()->createBlock(
\Magento\Backend\Block\Store\Switcher\Form\Renderer\Fieldset\Element::class
);
$field->setRenderer($renderer);
} else {
$fieldset->addField(
'store_id',
'hidden',
['name' => 'store_id', 'value' => $this->_storeManager->getStore(true)->getId()]
);
}
$fieldset->addField(
'customer_group_id',
'multiselect',
[
'label' => __('Customer Groups'),
'title' => __('Customer Groups'),
'name' => 'customer_group_id',
'required' => true,
'values' => $this->_customerGroup->toOptionArray(),
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'from_date',
'date',
[
'label' => __('From Date'),
'title' => __('From Date'),
'name' => 'from_date',
'required' => true,
'date_format' => 'yyyy-MM-dd',
'class' => 'validate-date validate-date-range date-range-attribute-from',
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'to_date',
'date',
[
'label' => __('To Date'),
'title' => __('To Date'),
'name' => 'to_date',
'date_format' => 'yyyy-MM-dd',
'class' => 'validate-date validate-date-range date-range-attribute-to',
'disabled' => $isElementDisabled
]
);
}
/**
* Check permission for passed action.
*
* @param string $resourceId
* @return bool
*/
protected function _isAllowedAction($resourceId)
{
return $this->_authorization->isAllowed($resourceId);
}
}
<?php
namespace Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab;
use Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
/**
* Class WhereToDisplay
* @package Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab
*/
class WhereToDisplay extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* @return \Magento\Backend\Block\Widget\Form\Generic
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _prepareForm()
{
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
);
$form->setHtmlIdPrefix('sparsh_free_shipping_bar_entity_');
$model = $this->getCurrentBar();
$this->_addWhereToDisplayFieldset($form);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
/**
* @param \Magento\Framework\Data\Form $form
*/
protected function _addWhereToDisplayFieldset(\Magento\Framework\Data\Form $form)
{
$fieldset = $form->addFieldset('where_to_display_fieldset', ['legend' => __('Where to display')]);
$isElementDisabled = !$this->_isAllowedAction(Entity::ADMIN_RESOURCE);
$fieldset->addField(
'bar_layout_position',
'select',
[
'label' => __('Layout Position'),
'title' => __('Layout Position'),
'name' => 'bar_layout_position',
'required' => true,
'options' => [
'page_top' => __('Page Top'),
'page_bottom' => __('Page Bottom'),
'insert_snippet' => __('Insert Snippet')
],
'disabled' => $isElementDisabled
]
);
}
/**
* Prepare form Html. call the phtml file with form.
*
* @return string
*/
public function getFormHtml()
{
$html = parent::getFormHtml();
$html .= $this->setTemplate('Sparsh_FreeShippingBar::form/snippet_code.phtml')->toHtml();
return $html;
}
/**
* Check permission for passed action.
*
* @param string $resourceId
* @return bool
*/
protected function _isAllowedAction($resourceId)
{
return $this->_authorization->isAllowed($resourceId);
}
/**
* Get current shipping bar entity.
*
* @return array|null
*/
public function getCurrentBar()
{
return $this->_coreRegistry->registry(Entity::REGISTRY_KEY_CURRENT_ENTITY);
}
/**
* @return bool
*/
public function getEntityId()
{
$model = $this->getCurrentBar();
if ($model->getEntityId()) {
return $model->getEntityId();
}
return false;
}
}
<?php
namespace Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit;
/**
* Class Tabs
* @package Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit
*/
class Tabs extends \Magento\Backend\Block\Widget\Tabs
{
/**
* Initialize free shipping bar edit page tabs.
*
* @return void
* @codeCoverageIgnore
*/
protected function _construct()
{
parent::_construct();
$this->setId('sparsh_free_shipping_bar_entity_edit_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(__('Free Shipping Bar Information'));
}
/**
* @return \Magento\Backend\Block\Widget\Tabs
* @throws \Exception
*/
protected function _beforeToHtml()
{
$this->addTab(
'main',
[
'label' => __('General'),
'title' => __('General'),
'content' => $this->getChildHtml('main'),
'active' => true
]
);
$this->addTab(
'what_to_display',
[
'label' => __('What to Display'),
'title' => __('What to Display'),
'content' => $this->getChildHtml('what_to_display')
]
);
$this->addTab(
'where_to_display',
[
'label' => __('Where to Display'),
'title' => __('Where to Display'),
'content' => $this->getChildHtml('where_to_display')
]
);
return parent::_beforeToHtml();
}
}
<?php
namespace Sparsh\FreeShippingBar\Block\Entity;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
/**
* Class FreeShippingBar
* @package Sparsh\FreeShippingBar\Block\Entity
*/
class FreeShippingBar extends \Magento\Framework\View\Element\Template
{
/**
* @var \Sparsh\FreeShippingBar\Helper\Data
*/
private $barDataHelper;
protected $_store;
/**
* FreeShippingBar constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\Locale\CurrencyInterface $localeCurrency
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Sparsh\FreeShippingBar\Helper\Data $barDataHelper
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Locale\CurrencyInterface $localeCurrency,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Sparsh\FreeShippingBar\Helper\Data $barDataHelper,
StoreManagerInterface $_store,
array $data = []
) {
parent::__construct($context, $data);
$this->_store = $_store;
$this->localeCurrency = $localeCurrency;
$this->storeManager = $storeManager;
$this->barDataHelper = $barDataHelper;
}
/**
* Retrieve config value.
*
* @return string
*/
public function getConfig($config)
{
return $this->barDataHelper->getConfig($config);
}
/**
* Retrieve current currency symbol.
*
* @return string
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getCurrentCurrencySymbol()
{
$currencyCode = $this->storeManager->getStore()->getCurrentCurrencyCode();
$currencySymbol = $this->localeCurrency->getCurrency($currencyCode)->getSymbol();
return $currencySymbol;
}
/**
* Retrieve shipping bar data.
*
* @return bool|mixed
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getFreeShippingBar()
{
return $this->barDataHelper->getShippingBar();
}
/**
* Retrieve shipping bar data by entity id.
*
* @param $entityId
* @return array|bool
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getFreeShippingBarByEntityId($entityId)
{
return $this->barDataHelper->getShippingBarByEntityId($entityId);
}
public function getImgUrl($img){
$mediaUrl = $this->storeManager->getStore() ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).$img;
return $mediaUrl;
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml;
/**
* Class Entity
* @package Sparsh\FreeShippingBar\Controller\Adminhtml
*/
abstract class Entity extends \Magento\Backend\App\Action
{
/**
* Authorization level of a basic admin session.
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Sparsh_FreeShippingBar::free_shipping_bar_management';
/**
* Current free shipping bar entity
*/
const REGISTRY_KEY_CURRENT_ENTITY = 'current_sparsh_free_shipping_bar_entity';
/**
* @var \Magento\Framework\Registry
*/
protected $coreRegistry;
/**
* @var \Sparsh\FreeShippingBar\Model\EntityFactory
*/
protected $entityFactory;
/**
* Entity constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
) {
parent::__construct($context);
$this->coreRegistry = $coreRegistry;
$this->entityFactory = $entityFactory;
}
/**
* Init action.
*
* @return $this
*/
protected function _initAction()
{
$this->_view->loadLayout();
$this->_setActiveMenu('Magento_Backend::marketing')
->_addBreadcrumb(__('Sparsh Free Shipping Bar'), __('Sparsh Free Shipping Bar'));
return $this;
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\App\ActionInterface;
/**
* Class Delete
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class Delete extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements ActionInterface
{
/**
* @return void
*/
public function execute()
{
$entityId = $this->getRequest()->getParam('entity_id');
if ($entityId) {
try {
$model = $this->entityFactory->create();
$model->load($entityId);
$model->delete();
$this->messageManager->addSuccess(__('The shipping bar is deleted successfully.'));
$this->_redirect('*/*/');
return;
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
$this->_redirect('*/*/edit', ['entity_id' => $entityId]);
return;
}
}
$this->messageManager->addError(__('We can\'t find a bar to delete.'));
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\View\Result\PageFactory;
use Sparsh\FreeShippingBar\Helper\Data;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
/**
* Class Edit
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class Edit extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpGetActionInterface
{
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var Data
*/
private $data;
/**
* Index constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
* @param PageFactory $resultPageFactory
* @param Data $data
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory,
PageFactory $resultPageFactory,
Data $data
) {
$this->resultPageFactory = $resultPageFactory;
$this->data = $data;
parent::__construct($context, $coreRegistry, $entityFactory);
}
/**
* @return void
*/
public function execute()
{
if ($this->data->getConfig('sparsh_free_shipping_bar/general/enable') == 0) {
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('admin/dashboard/index', ['_current' => true]);
}
$entityId = $this->getRequest()->getParam('entity_id');
/** @var $model \Sparsh\FreeShippingBar\Model\Entity */
$model = $this->entityFactory->create();
if ($entityId) {
$model->load($entityId);
if (!$model->getEntityId()) {
$this->messageManager->addErrorMessage(__('This shipping bar no longer exist.'));
$this->_redirect('*/*/');
return;
}
}
$this->coreRegistry->register(self::REGISTRY_KEY_CURRENT_ENTITY, $model);
$this->_initAction();
$this->_view->getPage()->getConfig()->getTitle()->prepend(__('Free Shipping Bar'));
$this->_view->getPage()->getConfig()->getTitle()->prepend(
$model->getEntityId() ? $model->getName() : __('New Shipping Bar')
);
$breadcrumb = $entityId ? __('Edit Shipping Bar') : __('New Shipping Bar');
$this->_addBreadcrumb($breadcrumb, $breadcrumb);
$this->_view->renderLayout();
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\View\Result\PageFactory;
use Sparsh\FreeShippingBar\Helper\Data;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
/**
* Class Index
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class Index extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpGetActionInterface
{
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var Data
*/
private $data;
/**
* Index constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
* @param PageFactory $resultPageFactory
* @param Data $data
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory,
PageFactory $resultPageFactory,
Data $data
) {
$this->resultPageFactory = $resultPageFactory;
$this->data = $data;
parent::__construct($context, $coreRegistry, $entityFactory);
}
/**
* @return void
*/
public function execute()
{
if ($this->data->getConfig('sparsh_free_shipping_bar/general/enable') == 0) {
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setPath('admin/dashboard/index', ['_current' => true]);
}
$this->_initAction()->_addBreadcrumb(__('Manage Free Shipping Bar'), __('Manage Free Shipping Bar'));
$this->_view->getPage()->getConfig()->getTitle()->prepend(__('Free Shipping Bar'));
$this->_view->renderLayout();
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
/**
* Class MassDelete
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class MassDelete extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpPostActionInterface
{
/**
* @var \Magento\Ui\Component\MassAction\Filter
*/
protected $filter;
/**
* MassDelete constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
* @param \Magento\Ui\Component\MassAction\Filter $filter
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory,
\Magento\Ui\Component\MassAction\Filter $filter
) {
parent::__construct($context, $coreRegistry, $entityFactory);
$this->filter = $filter;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute()
{
$collection = $this->filter->getCollection($this->entityFactory->create()->getCollection());
$collectionSize = $collection->getSize();
foreach ($collection as $item) {
$item->delete();
}
try {
$this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $collectionSize));
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong. Please try again.'));
}
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
/**
* Class MassDisable
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class MassDisable extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpPostActionInterface
{
/**
* @var \Magento\Ui\Component\MassAction\Filter
*/
protected $filter;
/**
* MassDisable constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
* @param \Magento\Ui\Component\MassAction\Filter $filter
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory,
\Magento\Ui\Component\MassAction\Filter $filter
) {
parent::__construct($context, $coreRegistry, $entityFactory);
$this->filter = $filter;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute()
{
$collection = $this->filter->getCollection($this->entityFactory->create()->getCollection());
foreach ($collection as $item) {
$item->setIsActive(false);
$item->save();
}
try {
$this->messageManager->addSuccess(__('A total of %1 record(s) have been disabled.', $collection->getSize()));
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong. Please try again.'));
}
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
/**
* Class MassEnable
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class MassEnable extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpPostActionInterface
{
/**
* @var \Magento\Ui\Component\MassAction\Filter
*/
protected $filter;
/**
* MassEnable constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
* @param \Magento\Ui\Component\MassAction\Filter $filter
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory,
\Magento\Ui\Component\MassAction\Filter $filter
) {
parent::__construct($context, $coreRegistry, $entityFactory);
$this->filter = $filter;
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute()
{
$collection = $this->filter->getCollection($this->entityFactory->create()->getCollection());
foreach ($collection as $item) {
$item->setIsActive(true);
$item->save();
}
try {
$this->messageManager->addSuccess(__('A total of %1 record(s) have been enabled.', $collection->getSize()));
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong. Please try again.'));
}
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('*/*/');
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
/**
* Class NewAction
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class NewAction extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpGetActionInterface
{
/**
* @return void
*/
public function execute()
{
$this->_forward('edit');
}
}
<?php
namespace Sparsh\FreeShippingBar\Controller\Adminhtml\Entity;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\Driver\File;
/**
* Class Save
* @package Sparsh\FreeShippingBar\Controller\Adminhtml\Entity
*/
class Save extends \Sparsh\FreeShippingBar\Controller\Adminhtml\Entity implements HttpPostActionInterface
{
/**
* DateFilter
*
* @var \Magento\Framework\Stdlib\DateTime\Filter\Date
*/
private $dateFilter;
const FILE_DIR = 'sparsh/free_shipping_bar';
protected $_fileUploaderFactory;
protected $_filesystem;
protected $_file;
/**
* Save constructor.
*
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\Registry $coreRegistry
* @param \Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory
* @param \Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Sparsh\FreeShippingBar\Model\EntityFactory $entityFactory,
\Magento\Framework\Stdlib\DateTime\Filter\Date $dateFilter,
\Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
\Magento\Framework\Filesystem $filesystem,
File $file
) {
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_file = $file;
$this->_filesystem = $filesystem;
$this->dateFilter = $dateFilter;
parent::__construct($context, $coreRegistry, $entityFactory);
}
/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
*/
public function execute()
{
$data = $this->getRequest()->getPostValue();
if ($data) {
try {
if (empty($data['entity_id'])) {
unset($data['entity_id']);
}
/** @var $model \Sparsh\FreeShippingBar\Model\Entity */
$model = $this->entityFactory->create();
$entityId = (int)$this->getRequest()->getParam('entity_id');
if ($entityId) {
$model->load($entityId);
}
if (!$data['to_date']) {
$data['to_date'] = null;
}
//pc img delete
if (isset($data['background_img']['delete']) && $data['background_img']['delete']==1){
$this->deleteImg($data['background_img']['value']);
$data['background_img'] = '';
}
//phone img deletc
if (isset($data['background_img_phone']['delete']) && $data['background_img_phone']['delete']==1){
$this->deleteImg($data['background_img_phone']['value']);
$data['background_img_phone'] = '';
}
//pc img upload
if (isset($_FILES['background_img']['name']) && $_FILES['background_img']['name']){
$this->saveImg('background_img');
$data['background_img'] = '/'.self::FILE_DIR.'/'.$_FILES['background_img']['name'];
}
//phone img upload
if (isset($_FILES['background_img_phone']['name']) && $_FILES['background_img_phone']['name']){
$this->saveImg('background_img_phone');
$data['background_img_phone'] = '/'.self::FILE_DIR.'/'.$_FILES['background_img_phone']['name'];
}
//not request img info
if (isset($data['background_img']) && is_array($data['background_img'])){
//no delete and no upload new img
unset($data['background_img']);
}
if (isset($data['background_img_phone']) && is_array($data['background_img_phone'])){
//no delete and no upload new img
unset($data['background_img_phone']);
}
$model->setData($data);
$model->save();
$this->messageManager->addWarningMessage(
__('Please, refresh the full page cache for the changes to take effect.')
);
$this->messageManager->addSuccessMessage(__('The shipping bar is saved successfully.'));
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', ['entity_id' => $model->getEntityId()]);
return;
}
$this->_redirect('*/*/');
return;
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the shipping bar data. Please review the error log.')
);
$this->_redirect('*/*/edit', ['entity_id' => (int)$this->getRequest()->getParam('entity_id')]);
return;
}
$this->_redirect('*/*/');
return;
}
}
public function saveImg($img){
$uploader = $this->_fileUploaderFactory->create(['fileId' => $img]);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(self::FILE_DIR );
$result = $uploader->save($path);
return $result;
}
public function deleteImg($img){
$fileName = $img;// replace this with some codes to get the $fileName
$mediaRootDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
if ($this->_file->isExists($mediaRootDir . $fileName)) {
$this->_file->deleteFile($mediaRootDir . $fileName);
return true;
}
return false;
}
}
<?php
namespace Sparsh\FreeShippingBar\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Sparsh\FreeShippingBar\Model\EntityFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\Http\Context as HttpContext;
/**
* Class Data
* @package Sparsh\FreeShippingBar\Helper
*/
class Data extends AbstractHelper
{
/**
* @var EntityFactory
*/
private $entityFactory;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var CustomerSession
*/
private $customerSession;
/**
* @var HttpContext
*/
private $httpContext;
/**
* @var ResourceConnection
*/
private $resourceConnection;
/**
* Data constructor.
* @param Context $context
* @param EntityFactory $entityFactory
* @param StoreManagerInterface $storeManager
* @param CustomerSession $customerSession
* @param HttpContext $httpContext
* @param \Magento\Framework\App\ResourceConnection $resourceConnection
*/
public function __construct(
Context $context,
EntityFactory $entityFactory,
StoreManagerInterface $storeManager,
CustomerSession $customerSession,
HttpContext $httpContext,
\Magento\Framework\App\ResourceConnection $resourceConnection
) {
parent::__construct($context);
$this->entityFactory = $entityFactory;
$this->storeManager = $storeManager;
$this->customerSession = $customerSession;
$this->httpContext = $httpContext;
$this->_resource = $resourceConnection;
}
/**
* Retrieve config value.
*
* @return string
*/
public function getConfig($config)
{
return $this->scopeConfig->getValue($config, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
/**
* Retrieve shipping bar collection.
*
* @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getShippingBarCollection($entityId = null)
{
$barEntity = $this->entityFactory->create();
$collection = $barEntity->getCollection();
if ($entityId) {
$freeShippingBarStoreTable = $this->_resource->getTableName('sparsh_free_shipping_bar_store');
$freeShippingBarCustomerGroupTable = $this->_resource->getTableName('sparsh_free_shipping_bar_customer_group');
$collection
->join(
['st'=>$freeShippingBarStoreTable],
"main_table.entity_id = st.entity_id"
)
->join(
['ct' => $freeShippingBarCustomerGroupTable],
"main_table.entity_id = ct.entity_id"
)
->addFieldToFilter('main_table.entity_id', ['eq' => $entityId])
->addFieldToFilter('main_table.from_date', ['lteq' => date("Y-m-d")])
->addFieldToFilter('main_table.to_date', [['null' => true],['gteq' => date("Y-m-d")]])
->addFieldToFilter('main_table.is_active', ['eq' => 1]);
} else {
$collection->addFieldToFilter('from_date', ['lteq' => date("Y-m-d")])
->addFieldToFilter('to_date', [['null' => true],['gteq' => date("Y-m-d")]])
->addFieldToFilter('is_active', ['eq' => 1])
->setOrder('sort_order', 'ASC');
}
return $collection;
}
/**
* Retrieve shipping bar data.
*
* @return array|false
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getShippingBar()
{
$collection = $this->getShippingBarCollection();
if ($collection->getData()) {
foreach ($collection as $barItem) {
if ($this->isStoreMatched($barItem['store_id']) &&
$this->isCustomerGroupMatched($barItem['customer_group_id'])) {
return $barItem->getData();
}
}
}
return false;
}
/**
* Retrieve shipping bar goal.
*
* @return string|false
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getShippingGoal()
{
$barData = $this->getShippingBar();
if ($barData) {
return $barData['goal'];
}
return false;
}
/**
* Retrieve shipping bar data by entity id.
*
* @param $entityId
* @return array|false
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getShippingBarByEntityId($entityId)
{
$collection = $this->getShippingBarCollection($entityId)->getData();
$collectionArray = [];
if ($collection) {
foreach ($collection as $barItem) {
foreach ($barItem as $barKeyItem => $barValItem) {
if ($barKeyItem == 'store_id') {
if (!isset($collectionArray['store_id']) || !in_array($barValItem, $collectionArray['store_id'])) {
$collectionArray['store_id'][] = $barValItem;
}
} elseif ($barKeyItem == 'customer_group_id') {
if (!isset($collectionArray['customer_group_id']) || !in_array($barValItem, $collectionArray['customer_group_id'])) {
$collectionArray['customer_group_id'][] = $barValItem;
}
} else {
$collectionArray[$barKeyItem] = $barValItem;
}
}
}
}
if ($collectionArray) {
if ($this->isStoreMatched($collectionArray['store_id']) &&
$this->isCustomerGroupMatched($collectionArray['customer_group_id'])) {
return $collectionArray;
}
}
return false;
}
/**
* Check if given store id(s) include current store id.
*
* @param $storeId
* @return bool
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function isStoreMatched($storeId)
{
$currentStoreId = $this->storeManager->getStore()->getId();
if (in_array(0, $storeId) || in_array($currentStoreId, $storeId)) {
return true;
}
return false;
}
/**
* Check if given customer group id(s) include current customer group id.
*
* @param $customerGroupId
* @return bool
*/
public function isCustomerGroupMatched($customerGroupId)
{
$isLoggedIn = $this->customerSession->isLoggedIn() ? $this->customerSession->isLoggedIn() : $this->isLoggedIn();
$currentCustomerGroupId = $isLoggedIn ? $this->customerSession->getCustomer()->getGroupId() : 0;
if (in_array($currentCustomerGroupId, $customerGroupId)) {
return true;
}
return false;
}
/**
* Check if customer logged in.
*
* @return bool
*/
public function isLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
}
<?php
namespace Sparsh\FreeShippingBar\Model;
use Sparsh\FreeShippingBar\Api\Data\EntityInterface;
use Magento\Framework\DataObject\IdentityInterface;
/**
* Class Entity
* @package Sparsh\FreeProducts\Model
*/
class Entity extends \Magento\Framework\Model\AbstractModel implements EntityInterface, IdentityInterface
{
/**
* CMS page cache tag
*/
const CACHE_TAG = 'sparsh_free_shipping_bar_entity';
/**
* Prefix of model events names
*
* @var string
*/
protected $_eventPrefix = 'sparsh_free_shipping_bar_entity';
/**
* Parameter name in event
*
* In observe method you can use $observer->getEvent()->getEntity() in this case
*
* @var string
*/
protected $_eventObject = 'entity';
/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(\Sparsh\FreeShippingBar\Model\ResourceModel\Entity::class);
}
/**
* Return unique ID(s) for each object in system
*
* @return array
*/
public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}
/**
* Get entity id.
*
* @return int|null
*/
public function getEntityId()
{
return $this->getData(self::ENTITY_ID);
}
/**
* Set entity id.
*
* @param int $entityId
* @return $this
*/
public function setEntityId($entityId)
{
return $this->setData(self::ENTITY_ID, $entityId);
}
/**
* Get entity name.
*
* @return string
*/
public function getName()
{
return $this->getData(self::ENTITY_NAME);
}
/**
* Set entity name.
*
* @param string $name
* @return $this
*/
public function setName($name)
{
return $this->setData(self::ENTITY_NAME, $name);
}
/**
* Get the start date when the entity is active.
*
* @return string|null
*/
public function getFromDate()
{
return $this->getData(self::FROM_DATE);
}
/**
* Set the start date when the entity is active.
*
* @param string $fromDate
* @return $this
*/
public function setFromDate($fromDate)
{
return $this->setData(self::FROM_DATE, $fromDate);
}
/**
* Get the end date when the entity is active
*
* @return string|null
*/
public function getToDate()
{
return $this->getData(self::TO_DATE);
}
/**
* Set the end date when the entity is active.
*
* @param string $toDate
* @return $this
*/
public function setToDate($toDate)
{
return $this->setData(self::TO_DATE, $toDate);
}
/**
* Whether the entity is active.
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function isActive()
{
return $this->getData(self::IS_ACTIVE);
}
/**
* Set whether the entity is active.
*
* @param bool $isActive
* @return Entity
*/
public function setIsActive($isActive)
{
return $this->setData(self::IS_ACTIVE, $isActive);
}
/**
* Get sort order.
*
* @return int
*/
public function getSortOrder()
{
return $this->getData(self::SORT_ORDER);
}
/**
* Set sort order.
*
* @param int $sortOrder
* @return $this
*/
public function setSortOrder($sortOrder)
{
return $this->setData(self::SORT_ORDER, $sortOrder);
}
/**
* Get entity creation date and time.
*
* @return string|null
*/
public function getCreatedAt()
{
return $this->getData(self::CREATED_AT);
}
/**
* Set entity creation date and time.
*
* @param string $createdAt
* @return $this
*/
public function setCreatedAt($createdAt)
{
return $this->setData(self::CREATED_AT, $createdAt);
}
/**
* Get entity last update date and time.
*
* @return string|null
*/
public function getUpdatedAt()
{
return $this->getData(self::UPDATED_AT);
}
/**
* Set entity last update date and time.
*
* @param string $updatedAt
* @return $this
*/
public function setUpdatedAt($updatedAt)
{
return $this->setData(self::UPDATED_AT, $updatedAt);
}
/**
* Get goal value.
*
* @return string
*/
public function getGoal()
{
return $this->getData(self::GOAL);
}
/**
* Set goal value.
*
* @param string $goal
* @return $this
*/
public function setGoal($goal)
{
return $this->setData(self::GOAL, $goal);
}
/**
* Get initial goal message.
*
* @return string
*/
public function getInitialGoalMessage()
{
return $this->getData(self::INITIAL_GOAL_MESSAGE);
}
/**
* Set initial goal message.
*
* @param string $initialgoalMessage
* @return $this
*/
public function setInitialGoalMessage($initialgoalMessage)
{
return $this->setData(self::INITIAL_GOAL_MESSAGE, $initialgoalMessage);
}
/**
* Get achieve goal message.
*
* @return string
*/
public function getAchieveGoalMessage()
{
return $this->getData(self::ACHIEVE_GOAL_MESSAGE);
}
/**
* Set achieve goal message.
*
* @param string $achievegoalMessage
* @return $this
*/
public function setAchieveGoalMessage($achievegoalMessage)
{
return $this->setData(self::ACHIEVE_GOAL_MESSAGE, $achievegoalMessage);
}
/**
* Whether the bar is clickable.
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function isClickable()
{
return $this->getData(self::IS_CLICKABLE);
}
/**
* Set whether the bar is clickable.
*
* @param bool isClickable
* @return Entity
*/
public function setIsClickable($isClickable)
{
return $this->setData(self::IS_CLICKABLE, $isClickable);
}
/**
* Get bar link url.
*
* @return string
*/
public function getBarLinkUrl()
{
return $this->getData(self::BAR_LINK_URL);
}
/**
* Set bar link url.
*
* @param string $barLinkUrl
* @return $this
*/
public function setBarLinkUrl($barLinkUrl)
{
return $this->setData(self::BAR_LINK_URL, $barLinkUrl);
}
/**
* Whether the bar link opens in new page.
*
* @return bool
* @SuppressWarnings(PHPMD.BooleanGetMethodName)
*/
public function isLinkOpenInNewPage()
{
return $this->getData(self::IS_LINK_OPEN_IN_NEW_PAGE);
}
/**
* Set whether the bar link opens in new page.
*
* @param bool $isLinkOpenInNewPage
* @return Entity
*/
public function setIsLinkOpenInNewPage($isLinkOpenInNewPage)
{
return $this->setData(self::IS_LINK_OPEN_IN_NEW_PAGE, $isLinkOpenInNewPage);
}
/**
* Get bar background color.
*
* @return string
*/
public function getBarBackgroundColor()
{
return $this->getData(self::BAR_BACKGROUND_COLOR);
}
/**
* Set bar background color.
*
* @param string $barBackgroundColor
* @return $this
*/
public function setBarBackgroundColor($barBackgroundColor)
{
return $this->setData(self::BAR_BACKGROUND_COLOR, $barBackgroundColor);
}
/**
* Get bar background color.
*
* @return string
*/
public function getBarTextColor()
{
return $this->getData(self::BAR_TEXT_COLOR);
}
/**
* Set bar text color.
*
* @param string $barTextColor
* @return $this
*/
public function setBarTextColor($barTextColor)
{
return $this->setData(self::BAR_TEXT_COLOR, $barTextColor);
}
/**
* Get goal text color.
*
* @return string
*/
public function getGoalTextColor()
{
return $this->getData(self::GOAL_TEXT_COLOR);
}
/**
* Set goal text color.
*
* @param string $goalTextColor
* @return $this
*/
public function setGoalTextColor($goalTextColor)
{
return $this->setData(self::GOAL_TEXT_COLOR, $goalTextColor);
}
/**
* Get bar font size.
*
* @return string
*/
public function getBarFontSize()
{
return $this->getData(self::BAR_FONT_SIZE);
}
/**
* Set bar font size.
*
* @param string $barFontSize
* @return $this
*/
public function setBarFontSizer($barFontSize)
{
return $this->setData(self::BAR_FONT_SIZE, $barFontSize);
}
/**
* Get bar layout position.
*
* @return string
*/
public function getBarLayoutPosition()
{
return $this->getData(self::BAR_LAYOUT_POSITION);
}
/**
* Set bar layout position.
*
* @param string $barLayoutPosition
* @return $this
*/
public function setBarLayoutPosition($barLayoutPosition)
{
return $this->setData(self::BAR_LAYOUT_POSITION, $barLayoutPosition);
}
}
<?php
namespace Sparsh\FreeShippingBar\Model\Entity\Source;
/**
* Class Status
* @package Sparsh\FreeShippingBar\Model\Entity\Source
*/
class Status implements \Magento\Framework\Data\OptionSourceInterface
{
const STATUS_ENABLED = 1;
const STATUS_DISABLED = 0;
/**
* @var \Sparsh\FreeShippingBar\Model\Entity
*/
protected $entity;
/**
* IsActive constructor.
*
* @param \Sparsh\FreeShippingBar\Model\Entity $entity
*/
public function __construct(
\Sparsh\FreeShippingBar\Model\Entity $entity
) {
$this->entity = $entity;
}
/**
* Return array of options as value-label pairs
*
* @return array
*/
public function toOptionArray()
{
$options = [];
foreach (self::getOptionArray() as $index => $value) {
$options[] = ['value' => $index, 'label' => $value];
}
return $options;
}
/**
* Retrieve option array
*
* @return array
*/
public function getOptionArray()
{
return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')];
}
}
<?php
namespace Sparsh\FreeShippingBar\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\EntityManager\EntityManager;
use Magento\Framework\Model\AbstractModel;
/**
* Class Entity
* @package Sparsh\FreeShippingBar\Model\ResourceModel
*/
class Entity extends AbstractDb
{
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* Store associated with bar entities information map
*
* @var array
*/
protected $_associatedEntitiesMap;
/**
* @param Context $context
* @param StoreManagerInterface $storeManager
* @param EntityManager $entityManager
* @param string $connectionName
*/
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
EntityManager $entityManager,
$connectionName = null
) {
parent::__construct($context, $connectionName);
$this->storeManager = $storeManager;
$this->entityManager = $entityManager;
$this->_associatedEntitiesMap = $this->getAssociatedEntitiesMap();
}
/**
* Define main table and primary-key.
*
* @return void
*/
protected function _construct()
{
$this->_init('sparsh_free_shipping_bar', 'entity_id');
}
/**
* Get store ids to which specified item is assigned
*
* @param int $barEntityId
* @return array
* @throws \Exception
*/
public function lookupStoreIds($barEntityId)
{
return $this->getAssociatedEntityIds($barEntityId, 'store');
}
/**
* Get customer group ids to which specified item is assigned
*
* @param int $barEntityId
* @return array
* @throws \Exception
*/
public function lookupCustomerGroupIds($barEntityId)
{
return $this->getAssociatedEntityIds($barEntityId, 'customer_group');
}
/**
* Retrieve single/multiple bar's associated entity Ids by entity type
*
* @param int $barEntityId
* @param string $entityType
* @return array
* @throws \Exception
*/
public function getAssociatedEntityIds($barEntityIds, $entityType, $collectionFlag = 0)
{
$connection = $this->getConnection();
$entityInfo = $this->_getAssociatedEntityInfo($entityType);
$select = $connection->select()
->from(
['sfe' => $this->getTable($entityInfo['associations_table'])],
$collectionFlag ? '*' : [$entityInfo['entity_id_field']]
)->join(
['sf' => $this->getMainTable()],
'sfe.'.$entityInfo['bar_entity_id_field'].' = sf.'.$entityInfo['bar_entity_id_field'],
[]
)->where(
'sf.'.$entityInfo['bar_entity_id_field'].' IN (?)',
$barEntityIds
);
return $collectionFlag ? $connection->fetchAll($select) : $connection->fetchCol($select);
}
/**
* Bind specified bar to entities
*
* @param int $barEntityId
* @param int[]|int|string $newEntityIds
* @param string $entityType
* @return $this
* @throws \Exception
*/
public function bindBarToEntity($barEntityId, $newEntityIds, $entityType)
{
$this->getConnection()->beginTransaction();
try {
$entityInfo = $this->_getAssociatedEntityInfo($entityType);
$oldEntityIds = $this->getAssociatedEntityIds($barEntityId, $entityType);
if (!is_array($newEntityIds)) {
$newEntityIds = [(int)$newEntityIds];
}
$table = $this->getTable($entityInfo['associations_table']);
$insert = array_diff($newEntityIds, $oldEntityIds);
if ($insert) {
$data = [];
foreach ($insert as $entityIds) {
$data[] = [
$entityInfo['bar_entity_id_field'] => (int)$barEntityId,
$entityInfo['entity_id_field'] => (int)$entityIds
];
}
$this->getConnection()->insertMultiple($table, $data);
}
$delete = array_diff($oldEntityIds, $newEntityIds);
if ($delete) {
$where = [
$entityInfo['bar_entity_id_field'].' = ?' => (int)$barEntityId,
$entityInfo['entity_id_field'].' IN (?)' => $delete
];
$this->getConnection()->delete($table, $where);
}
} catch (\Exception $e) {
$this->getConnection()->rollBack();
throw $e;
}
$this->getConnection()->commit();
return $this;
}
/**
* Map data for associated entities
*
* @param string $entityType
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _getAssociatedEntityInfo($entityType)
{
if (isset($this->_associatedEntitiesMap[$entityType])) {
return $this->_associatedEntitiesMap[$entityType];
}
throw new \Magento\Framework\Exception\LocalizedException(
__('There is no information about associated entity type "%1".', $entityType)
);
}
/**
* @return array
* @deprecated 100.1.0
*/
private function getAssociatedEntitiesMap()
{
if (!$this->_associatedEntitiesMap) {
$this->_associatedEntitiesMap = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Sparsh\FreeShippingBar\Model\ResourceModel\Entity\AssociatedEntityMap::class)
->getData();
}
return $this->_associatedEntitiesMap;
}
/**
* {@inheritDoc}
*/
public function load(AbstractModel $object, $value, $field = null)
{
return $this->entityManager->load($object, $value);
}
/**
* @param AbstractModel $object
* @return $this
* @throws \Exception
*/
public function save(AbstractModel $object)
{
$this->entityManager->save($object);
return $this;
}
/**
* @inheritDoc
*/
public function delete(AbstractModel $object)
{
$this->entityManager->delete($object);
return $this;
}
}
<?php
namespace Sparsh\FreeShippingBar\Model\ResourceModel\Entity;
use Sparsh\FreeShippingBar\Api\Data\EntityInterface;
/**
* Class Collection
* @package Sparsh\FreeShippingBar\Model\ResourceModel\Entity
*/
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
/**
* Primary field
*
* @var string
*/
protected $_idFieldName = 'entity_id';
/**
* @var \Magento\Framework\EntityManager\MetadataPool
*/
protected $metadataPool;
/**
* @var \Sparsh\FreeShippingBar\Model\ResourceModel\Entity
*/
private $resourceEntity;
/**
* Collection constructor.
* @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
* @param \Magento\Framework\Event\ManagerInterface $eventManager
* @param \Magento\Framework\EntityManager\MetadataPool $metadataPool
* @param \Sparsh\FreeShippingBar\Model\ResourceModel\Entity $resourceEntity
* @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection
* @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb|null $resource
*/
public function __construct(
\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Framework\EntityManager\MetadataPool $metadataPool,
\Sparsh\FreeShippingBar\Model\ResourceModel\Entity $resourceEntity,
\Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
) {
$this->metadataPool = $metadataPool;
$this->resourceEntity = $resourceEntity;
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
}
/**
* Define model and resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(
\Sparsh\FreeShippingBar\Model\Entity::class,
\Sparsh\FreeShippingBar\Model\ResourceModel\Entity::class
);
}
/**
* @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
* @throws \Exception
*/
protected function _afterLoad()
{
$entityMetadata = $this->metadataPool->getMetadata(EntityInterface::class);
$this->performAfterLoad($entityMetadata->getLinkField(), 'store');
$this->performAfterLoad($entityMetadata->getLinkField(), 'customer_group');
return parent::_afterLoad();
}
/**
* Perform operations after collection load
*
* @param string $tableName
* @param string|null $linkField
* @return Collection
* @throws \Exception
*/
protected function performAfterLoad($linkField, $entityType)
{
$linkedFieldIds = $this->getColumnValues($linkField);
if (count($linkedFieldIds)) {
$result = $this->resourceEntity->getAssociatedEntityIds($linkedFieldIds, $entityType, 1);
if ($result) {
$entityId = $entityType.'_id';
$storesData = [];
foreach ($result as $storeData) {
$storesData[$storeData[$linkField]][] = $storeData[$entityId];
}
foreach ($this as $item) {
$linkedFieldId = $item->getData($linkField);
if (!isset($storesData[$linkedFieldId])) {
continue;
}
$item->setData($entityId, $storesData[$linkedFieldId]);
}
}
}
return $this;
}
}
<?php
namespace Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation;
use Magento\Framework\EntityManager\MetadataPool;
use Magento\Framework\EntityManager\Operation\AttributeInterface;
use Sparsh\FreeShippingBar\Model\ResourceModel\Entity;
/**
* Class ReadHandler
* @package Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation
*/
class ReadHandler implements AttributeInterface
{
/**
* @var MetadataPool
*/
private $metadataPool;
/**
* @var Entity
*/
private $resourceEntity;
/**
* ReadHandler constructor.
*
* @param Entity $resourceEntity
*/
public function __construct(
MetadataPool $metadataPool,
Entity $resourceEntity
) {
$this->metadataPool = $metadataPool;
$this->resourceEntity = $resourceEntity;
}
/**
* Perform action on relation/extension attribute
*
* @param object $entity
* @param array $arguments
* @return array
* @throws \Exception
*/
public function execute($entityType, $entityData, $arguments = [])
{
$linkField = $this->metadataPool->getMetadata($entityType)->getLinkField();
$entityId = $entityData[$linkField];
$entityData['store_id'] = $this->resourceEntity->lookupStoreIds($entityId);
$entityData['customer_group_id'] = $this->resourceEntity->lookupCustomerGroupIds($entityId);
return $entityData;
}
}
<?php
namespace Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation;
use Magento\Framework\EntityManager\Operation\AttributeInterface;
use Magento\Framework\EntityManager\MetadataPool;
use Sparsh\FreeShippingBar\Model\ResourceModel\Entity;
/**
* Class SaveHandler
* @package Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation
*/
class SaveHandler implements AttributeInterface
{
/**
* @var MetadataPool
*/
private $metadataPool;
/**
* @var Entity
*/
private $resourceEntity;
/**
* ReadHandler constructor.
*
* @param Entity $resourceEntity
*/
public function __construct(
MetadataPool $metadataPool,
Entity $resourceEntity
) {
$this->metadataPool = $metadataPool;
$this->resourceEntity = $resourceEntity;
}
/**
* Perform action on relation/extension attribute
*
* @param object $entity
* @param array $arguments
* @return array
* @throws \Exception
*/
public function execute($entityType, $entityData, $arguments = [])
{
$linkField = $this->metadataPool->getMetadata($entityType)->getLinkField();
if (isset($entityData['store_id'])) {
$storeIds = $entityData['store_id'];
if (!is_array($storeIds)) {
$storeIds = explode(',', (string)$storeIds);
}
$this->resourceEntity->bindBarToEntity($entityData[$linkField], $storeIds, 'store');
}
if (isset($entityData['customer_group_id'])) {
$customerGroupIds = $entityData['customer_group_id'];
if (!is_array($customerGroupIds)) {
$customerGroupIds = explode(',', (string)$customerGroupIds);
}
$this->resourceEntity->bindBarToEntity($entityData[$linkField], $customerGroupIds, 'customer_group');
}
return $entityData;
}
}
<?php
namespace Sparsh\FreeShippingBar\Plugin\Model\Shipping;
/**
* Class InsertFreeShippingRates
* @package Sparsh\FreeShippingBar\Plugin\Model\Shipping
*/
class InsertFreeShippingRates
{
/**
* @var \Sparsh\FreeShippingBar\Helper\Data
*/
private $barDataHelper;
/**
* InsertFreeShippingRates constructor.
*
* @param \Magento\Checkout\Model\Cart $cart
* @param \Sparsh\FreeShippingBar\Helper\Data $barDataHelper
*/
public function __construct(
\Magento\Checkout\Model\Cart $cart,
\Sparsh\FreeShippingBar\Helper\Data $barDataHelper
) {
$this->cart = $cart;
$this->barDataHelper = $barDataHelper;
}
/**
* Collect and get rates
*
* @param \Magento\Shipping\Model\Carrier\AbstractCarrierInterface $subject
* @param $result
* @return \Magento\Framework\DataObject|bool|null
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function afterCollectRates(\Magento\Shipping\Model\Shipping $subject, $result)
{
$isModuleEnable = $this->barDataHelper->getConfig('sparsh_free_shipping_bar/general/enable');
if ($isModuleEnable) {
$subTotal = $this->cart->getQuote()->getSubtotal();
$freeShippingGoal = (float)$this->barDataHelper->getShippingGoal();
if ($freeShippingGoal) {
if ($subTotal >= $freeShippingGoal) {
$rates = $subject->getResult()->getAllRates();
foreach ($rates as $rate) {
if ($rate->hasData('price') && $rate->hasData('cost')) {
$rate->setData('price', 0);
$rate->setData('cost', 0);
}
}
}
}
}
return $result;
}
}
#Free Shipping Bar Module
This extension allows store owners to create and display free shipping bar, which encourage customers to buy more products to avail free shipping on their purchase.
##Support:
version - 2.3.x, 2.4.x
##How to install Extension
1. Download the archive file.
2. Unzip the file
3. Create a folder [Magento_Root]/app/code/Sparsh/FreeShippingBar
4. Drop/move the unzipped files to directory '[Magento_Root]/app/code/Sparsh/FreeShippingBar'
#Enable Extension:
- php bin/magento module:enable Sparsh_FreeShippingBar
- php bin/magento setup:upgrade
- php bin/magento setup:di:compile
- php bin/magento setup:static-content:deploy
- php bin/magento cache:flush
#Disable Extension:
- php bin/magento module:disable Sparsh_FreeShippingBar
- php bin/magento setup:upgrade
- php bin/magento setup:di:compile
- php bin/magento setup:static-content:deploy
- php bin/magento cache:flush
---
<?php
namespace Sparsh\FreeShippingBar\Ui\Component\Listing\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;
/**
* Class FreeShippingBarActions
* @package Sparsh\FreeShippingBar\Ui\Component\Listing\Column
*/
class FreeShippingBarActions extends Column
{
/**
* Edit action path.
*/
const SHIPPING_BAR_URL_PATH_EDIT = 'sparsh_free_shipping_bar/entity/edit';
/**
* Delete action path .
*/
const SHIPPING_BAR_URL_PATH_DELETE = 'sparsh_free_shipping_bar/entity/delete';
/**
* @var UrlInterface
*/
private $urlBuilder;
/**
* @var string
*/
private $editUrl;
/**
* FreeShippingBarActions constructor.
*
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param UrlInterface $urlBuilder
* @param array $components
* @param array $data
* @param string $editUrl
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
UrlInterface $urlBuilder,
array $components = [],
array $data = [],
$editUrl = self::SHIPPING_BAR_URL_PATH_EDIT
) {
$this->urlBuilder = $urlBuilder;
$this->editUrl = $editUrl;
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) {
$name = $this->getData('name');
if (isset($item['entity_id'])) {
$item[$name]['edit'] = [
'href' => $this->urlBuilder->getUrl($this->editUrl, ['entity_id' => $item['entity_id']]),
'label' => __('Edit')
];
$item[$name]['delete'] = [
'href' => $this->urlBuilder->getUrl(
self::SHIPPING_BAR_URL_PATH_DELETE,
['entity_id' => $item['entity_id']]
),
'label' => __('Delete'),
'confirm' => [
'title' => __('Delete Free Shipping Bar'),
'message' => __('Are you sure you want to delete a Free Shipping Bar record?')
]
];
}
}
}
return $dataSource;
}
}
{
"name": "sparsh/magento-2-free-shipping-bar-extension",
"description": "Sparsh Free Shipping Bar Extension for Magento 2",
"type": "magento2-module",
"version": "1.3.0",
"license": "OSL-3.0",
"require": {
"php": "~7.1.0|~7.2.0|~7.3.0|~7.4.0|^8.0"
},
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Sparsh\\FreeShippingBar\\": ""
}
}
}
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "d4f59f4528da51cd87afcd5ea3c7a856",
"packages": [],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": "~7.1.0|~7.2.0|~7.3.0|~7.4.0|^8.0"
},
"platform-dev": [],
"plugin-api-version": "2.3.0"
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<acl>
<resources>
<resource id="Magento_Backend::admin">
<resource id="Sparsh_FreeShippingBar::free_shipping_bar_management" title="Free Shipping Bar" translate="title" sortOrder="50" />
<resource id="Magento_Backend::stores">
<resource id="Magento_Backend::stores_settings">
<resource id="Magento_Config::config">
<resource id="Sparsh_FreeShippingBar::config_free_shipping_bar" title="Free Shipping Bar Settings" translate="title" sortOrder="10" />
</resource>
</resource>
</resource>
</resource>
</resources>
</acl>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
</menu>
</config>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="sparsh_free_shipping_bar" frontName="sparsh_free_shipping_bar">
<module name="Sparsh_FreeShippingBar" before="Magento_Backend" />
</route>
</router>
</config>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment