Commit b73b29ac by wd

添加顶部包邮广告链接自定义模块,添加自定义轮播图模块

parent a2862376
<?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 WhatToDisplay
* @package Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab
*/
class WhatToDisplay 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','enctype'=>'multipart/form-data']]
);
$form->setHtmlIdPrefix('sparsh_free_shipping_bar_entity_');
$model = $this->getCurrentBar();
$this->_addWhatToDisplayFieldset($form, $model);
$this->_addDesignTemplateFieldset($form, $model);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
/**
* @param \Magento\Framework\Data\Form $form
* @param $model
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _addWhatToDisplayFieldset(\Magento\Framework\Data\Form $form, $model)
{
$fieldset = $form->addFieldset('what_to_display_fieldset', ['legend' => __('What to Display')]);
$isElementDisabled = !$this->_isAllowedAction(Entity::ADMIN_RESOURCE);
if (!$model->getEntityId()) {
if (!$model->hasData('initial_goal_message')) {
$model->setInitialGoalMessage('Get free shipping on order over {{goal}}.');
}
if (!$model->hasData('achieve_goal_message')) {
$model->setAchieveGoalMessage('Congrats! you have got free shipping.');
}
}
$fieldset->addField(
'goal',
'text',
[
'label' => __('Free Shipping Goal'),
'title' => __('Free Shipping Goal'),
'name' => 'goal',
'required' => false,
'class' => 'validate-number',
'disabled' => $isElementDisabled,
'note' => __('Enter the free shipping threshold. Buyers whose orders reach this amount will get free shipping.')
]
);
$fieldset->addField(
'initial_goal_message',
'text',
[
'label' => __('Initial Goal Message'),
'title' => __('Initial Goal Message'),
'name' => 'initial_goal_message',
'required' => false,
'disabled' => $isElementDisabled,
'note' => __('Enter the initial message when buyer\'s cart sub-total haven\'t reach the goal.')
]
);
$fieldset->addField(
'achieve_goal_message',
'text',
[
'label' => __('Achieve Goal Message'),
'title' => __('Achieve Goal Message'),
'name' => 'achieve_goal_message',
'required' => false,
'disabled' => $isElementDisabled,
'note' => __('Enter the congratulation message when buyers\' cart sub-total reach the goal.')
]
);
$fieldset->addField(
'background_img',
'image',
[
'label' => __('Background image'),
'title' => __('Background image'),
'name' => 'background_img',
'required' => false,
'disabled' => $isElementDisabled,
'none' => __('Pictures displayed in the current position')
]
);
$fieldset->addField(
'is_clickable',
'select',
[
'label' => __('Clickable'),
'title' => __('Clickable'),
'name' => 'is_clickable',
'options' => ['1' => __('Yes'), '0' => __('No')],
'disabled' => $isElementDisabled,
'note' => __('If Yes, the bar can be clicked to link and redirect to specified url.')
]
);
$fieldset->addField(
'bar_link_url',
'text',
[
'label' => __('Link URL'),
'title' => __('Link URL'),
'name' => 'bar_link_url',
'required' => true,
'class' => 'validate-url',
'disabled' => $isElementDisabled,
'note' => __('Add link to redirect free shipping bar.')
]
);
$fieldset->addField(
'is_link_open_in_new_page',
'select',
[
'label' => __('Open in New Page'),
'title' => __('Open in New Page'),
'name' => 'is_link_open_in_new_page',
'options' => ['1' => __('Yes'), '0' => __('No')],
'disabled' => $isElementDisabled,
'note' => __('Select Yes to open the link in a new tab.')
]
);
$this->setChild(
'form_after',
$this->getLayout()->createBlock(\Magento\Backend\Block\Widget\Form\Element\Dependence::class)
->addFieldMap("sparsh_free_shipping_bar_entity_is_clickable", 'is_clickable')
->addFieldMap("sparsh_free_shipping_bar_entity_bar_link_url", 'bar_link_url')
->addFieldMap("sparsh_free_shipping_bar_entity_is_link_open_in_new_page", 'is_link_open_in_new_page')
->addFieldDependence('bar_link_url', 'is_clickable', 1)
->addFieldDependence('is_link_open_in_new_page', 'is_clickable', 1)
);
}
/**
* @param \Magento\Framework\Data\Form $form
* @param $model
*/
protected function _addDesignTemplateFieldset(\Magento\Framework\Data\Form $form, $model)
{
$fieldset = $form->addFieldset('design_template_fieldset', ['legend' => __('Design Template')]);
$isElementDisabled = !$this->_isAllowedAction(Entity::ADMIN_RESOURCE);
if (!$model->getEntityId()) {
if (!$model->hasData('bar_background_color')) {
$model->setBarBackgroundColor('#1979C3');
}
if (!$model->hasData('bar_text_color')) {
$model->setBarTextColor('#FFFFFF');
}
if (!$model->hasData('goal_text_color')) {
$model->setGoalTextColor('#FFFFFF');
}
if (!$model->hasData('bar_font_size')) {
$model->setBarFontSize(14);
}
}
$fieldset->addField(
'bar_background_color',
'text',
[
'label' => __('Bar Background Color'),
'title' => __('Bar Background Color'),
'name' => 'bar_background_color',
'required' => true,
'class' => 'jscolor {hash:true}',
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'bar_text_color',
'text',
[
'label' => __('Bar Text Color'),
'title' => __('Bar Text Color'),
'name' => 'bar_text_color',
'required' => true,
'class' => 'jscolor {hash:true}',
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'goal_text_color',
'text',
[
'label' => __('Goal Text Color'),
'title' => __('Goal Text Color'),
'name' => 'goal_text_color',
'required' => true,
'class' => 'jscolor {hash:true}',
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'bar_font_size',
'text',
[
'label' => __('Font Size'),
'title' => __('Font Size'),
'name' => 'bar_font_size',
'required' => true,
'class' => 'validate-number validate-greater-than-zero',
'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/preview-shipping-bar.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 array
*/
public function getGoalMessages()
{
$model = $this->getCurrentBar();
$goalMessages = [
'initial-message' => $model->getInitialGoalMessage(),
'achieve-message' =>$model->getAchieveGoalMessage()
];
return $goalMessages;
}
}
<?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;
}
if (isset($data['background_img']['delete']) && $data['background_img']['delete']==1){
$this->deleteImg($data['background_img']['value']);
$data['background_img'] = '';
}
if ($_FILES['background_img']['name']){
$this->saveImg('background_img');
$data['background_img'] = '/'.self::FILE_DIR.'/'.$_FILES['background_img']['name'];
}
if (is_array($data['background_img'])){
//no delete and no upload new img
unset($data['background_img']);
}
$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 ${ $.$data.name }'),
'message' => __('Are you sure you want to delete a ${ $.$data.name } 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
<?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="sparsh" translate="label" sortOrder="500">
<label>Sparsh Extensions</label>
</tab>
<section id="sparsh_free_shipping_bar" translate="label" sortOrder="10" showInStore="1" showInWebsite="1" showInDefault="1">
<class>separator-top</class>
<label>Free Shipping Bar</label>
<tab>sparsh</tab>
<resource>Sparsh_FreeShippingBar::config_free_shipping_bar</resource>
<group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>General Configuration</label>
<field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable Free Shipping Bar</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
</section>
</system>
</config>
<?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>
<sparsh_free_shipping_bar>
<general>
<enable>1</enable>
</general>
</sparsh_free_shipping_bar>
</default>
</config>
<?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="sparsh_free_shipping_bar" resource="default" engine="innodb" comment="Sparsh Free Shipping Bar">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Entity Id"/>
<column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/>
<column xsi:type="date" name="from_date" comment="From"/>
<column xsi:type="date" name="to_date" comment="To"/>
<column xsi:type="decimal" name="goal" nullable="false" scale="2" precision="10" comment="Free Shipping Goal"/>
<column xsi:type="varchar" name="initial_goal_message" nullable="false" length="255" comment="Initial Goal Message"/>
<column xsi:type="varchar" name="achieve_goal_message" nullable="false" length="255" comment="Achieve Goal Message"/>
<column xsi:type="tinyint" name="is_clickable" padding="2" unsigned="false" nullable="false" identity="false" default="0" comment="Is Clickable"/>
<column xsi:type="varchar" name="bar_link_url" nullable="true" length="255" comment="Bar Link URL"/>
<column xsi:type="tinyint" name="is_link_open_in_new_page" padding="2" unsigned="false" nullable="false" identity="false" default="0" comment="Is Link Open in New Page"/>
<column xsi:type="varchar" name="bar_background_color" nullable="false" length="255" comment="Bar Background Color"/>
<column xsi:type="varchar" name="bar_text_color" nullable="false" length="255" comment="Bar Text Color"/>
<column xsi:type="varchar" name="goal_text_color" nullable="false" length="255" comment="Goal Text Color"/>
<column xsi:type="varchar" name="bar_font_size" nullable="false" length="255" comment="Bar Font Size"/>
<column xsi:type="varchar" name="bar_layout_position" nullable="false" length="255" comment="Bar Layout Position"/>
<column xsi:type="tinyint" name="is_active" padding="2" unsigned="false" nullable="false" identity="false" default="1" comment="Is Active"/>
<column xsi:type="int" name="sort_order" padding="3" unsigned="true" nullable="false" identity="false" default="1" comment="Sort Order"/>
<column xsi:type="varchar" name="background_img" nullable="false" length="255" default="" comment="Bar Background Image" />
<column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="Creation Time"/>
<column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="Update Time"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="entity_id"/>
</constraint>
<index referenceId="SPARSH_FREE_SHIPPING_BAR_IS_ACTIVE" indexType="btree">
<column name="is_active"/>
</index>
<index referenceId="SPARSH_FREE_SHIPPING_BAR_SORT_ORDER" indexType="btree">
<column name="sort_order"/>
</index>
<index referenceId="SPARSH_FREE_SHIPPING_BAR_FROM_DATE" indexType="btree">
<column name="from_date"/>
</index>
<index referenceId="SPARSH_FREE_SHIPPING_BAR_TO_DATE" indexType="btree">
<column name="to_date"/>
</index>
</table>
<table name="sparsh_free_shipping_bar_store" resource="default" engine="innodb" comment="Sparsh Free Shipping Bar to Store View Relations">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="false" comment="Entity Id"/>
<column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" comment="Store Id"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="entity_id"/>
<column name="store_id"/>
</constraint>
<constraint xsi:type="foreign"
referenceId="SPARSH_FREE_SHIPPING_BAR_STORE_ENTITY_ID_SPARSH_FREE_SHIPPING_BAR_ENTITY_ID"
table="sparsh_free_shipping_bar_store"
column="entity_id"
referenceTable="sparsh_free_shipping_bar"
referenceColumn="entity_id"
onDelete="CASCADE"/>
<constraint xsi:type="foreign"
referenceId="SPARSH_FREE_SHIPPING_BAR_STORE_STORE_ID_STORE_STORE_ID"
table="sparsh_free_shipping_bar_store"
column="store_id"
referenceTable="store"
referenceColumn="store_id"
onDelete="CASCADE"/>
<index referenceId="SPARSH_FREE_SHIPPING_BAR_STORE_STORE_ID" indexType="btree">
<column name="store_id"/>
</index>
</table>
<table name="sparsh_free_shipping_bar_customer_group" resource="default" engine="innodb" comment="Sparsh Free Shipping Bar to Customer Groups Relations">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="false" comment="Entity Id"/>
<column xsi:type="int" name="customer_group_id" padding="10" unsigned="true" nullable="false" identity="false" comment="Customer Group Id"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="entity_id"/>
<column name="customer_group_id"/>
</constraint>
<constraint xsi:type="foreign" referenceId="SPARSH_FREE_SHIPPING_BAR_CUSTOMER_GROUP_ENTITY_ID_SPARSH_FREE_SHIPPING_BAR_ENTITY_ID" table="sparsh_free_shipping_bar_customer_group" column="entity_id" referenceTable="sparsh_free_shipping_bar" referenceColumn="entity_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="SPARSH_FREE_SHIPPING_BAR_CSTR_GROUP_CSTR_GROUP_ID_CSTR_GROUP_CSTR_GROUP_ID" table="sparsh_free_shipping_bar_customer_group" column="customer_group_id" referenceTable="customer_group" referenceColumn="customer_group_id" onDelete="CASCADE"/>
<index referenceId="SPARSH_FREE_SHIPPING_BAR_CUSTOMER_GROUP_CUSTOMER_GROUP_ID" indexType="btree">
<column name="customer_group_id"/>
</index>
</table>
</schema>
{
"sparsh_free_shipping_bar": {
"column": {
"entity_id": true,
"name": true,
"from_date": true,
"to_date": true,
"goal": true,
"initial_goal_message": true,
"achieve_goal_message": true,
"is_clickable": true,
"bar_link_url": true,
"is_link_open_in_new_page": true,
"bar_background_color": true,
"bar_text_color": true,
"goal_text_color": true,
"bar_font_size": true,
"bar_layout_position": true,
"is_active": true,
"sort_order": true,
"created_at": true,
"updated_at": true
},
"index": {
"SPARSH_FREE_SHIPPING_BAR_IS_ACTIVE": true,
"SPARSH_FREE_SHIPPING_BAR_SORT_ORDER": true,
"SPARSH_FREE_SHIPPING_BAR_FROM_DATE": true,
"SPARSH_FREE_SHIPPING_BAR_TO_DATE": true
},
"constraint": {
"PRIMARY": true
}
},
"sparsh_free_shipping_bar_store": {
"column": {
"entity_id": true,
"store_id": true
},
"index": {
"SPARSH_FREE_SHIPPING_BAR_STORE_STORE_ID": true
},
"constraint": {
"PRIMARY": true,
"SPARSH_FREE_SHIPPING_BAR_STORE_ENTITY_ID_SPARSH_FREE_SHIPPING_BAR_ENTITY_ID": true,
"SPARSH_FREE_SHIPPING_BAR_STORE_STORE_ID_STORE_STORE_ID": true
}
},
"sparsh_free_shipping_bar_customer_group": {
"column": {
"entity_id": true,
"customer_group_id": true
},
"index": {
"SPARSH_FREE_SHIPPING_BAR_CUSTOMER_GROUP_CUSTOMER_GROUP_ID": true
},
"constraint": {
"PRIMARY": true,
"SPARSH_FREE_SHIPPING_BAR_CUSTOMER_GROUP_ENTITY_ID_SPARSH_FREE_SHIPPING_BAR_ENTITY_ID": true,
"SPARSH_FREE_SHIPPING_BAR_CSTR_GROUP_CSTR_GROUP_ID_CSTR_GROUP_CSTR_GROUP_ID": true
}
}
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Sparsh\FreeShippingBar\Api\Data\EntityInterface" type="Sparsh\FreeShippingBar\Model\Entity"/>
<virtualType name="ShippingBarGridDataProvider" type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
<arguments>
<argument name="collection" xsi:type="object" shared="false">Sparsh\FreeShippingBar\Model\Resource\Entity\Collection</argument>
<argument name="filterPool" xsi:type="object" shared="false">ShippingBarGridFilterPool</argument>
</arguments>
</virtualType>
<virtualType name="ShippingBarGridFilterPool" type="Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool">
<arguments>
<argument name="appliers" xsi:type="array">
<item name="regular" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
</argument>
</arguments>
</virtualType>
<virtualType name="Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">sparsh_free_shipping_bar</argument>
<argument name="resourceModel" xsi:type="string">Sparsh\FreeShippingBar\Model\ResourceModel\Entity</argument>
</arguments>
</virtualType>
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="sparsh_free_shipping_bar_entity_listing_data_source" xsi:type="string">Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Grid\Collection</item>
</argument>
</arguments>
</type>
<virtualType name="Sparsh\FreeShippingBar\Model\ResourceModel\Entity\AssociatedEntityMap" type="Magento\Framework\DataObject">
<arguments>
<argument name="data" xsi:type="array">
<item name="store" xsi:type="array">
<item name="associations_table" xsi:type="string">sparsh_free_shipping_bar_store</item>
<item name="bar_entity_id_field" xsi:type="string">entity_id</item>
<item name="entity_id_field" xsi:type="string">store_id</item>
</item>
<item name="customer_group" xsi:type="array">
<item name="associations_table" xsi:type="string">sparsh_free_shipping_bar_customer_group</item>
<item name="bar_entity_id_field" xsi:type="string">entity_id</item>
<item name="entity_id_field" xsi:type="string">customer_group_id</item>
</item>
</argument>
</arguments>
</virtualType>
<type name="Magento\Framework\EntityManager\MetadataPool">
<arguments>
<argument name="metadata" xsi:type="array">
<item name="Sparsh\FreeShippingBar\Api\Data\EntityInterface" xsi:type="array">
<item name="entityTableName" xsi:type="string">sparsh_free_shipping_bar</item>
<item name="identifierField" xsi:type="string">entity_id</item>
</item>
</argument>
</arguments>
</type>
<type name="Magento\Framework\EntityManager\Operation\AttributePool">
<arguments>
<argument name="extensionActions" xsi:type="array">
<item name="freeShippingBar" xsi:type="array">
<item name="Sparsh\FreeShippingBar\Api\Data\EntityInterface" xsi:type="array">
<item name="read" xsi:type="string">Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation\ReadHandler</item>
<item name="create" xsi:type="string">Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation\SaveHandler</item>
<item name="update" xsi:type="string">Sparsh\FreeShippingBar\Model\ResourceModel\Entity\Relation\SaveHandler</item>
</item>
</item>
</argument>
</arguments>
</type>
<type name="Magento\Framework\EntityManager\HydratorPool">
<arguments>
<argument name="hydrators" xsi:type="array">
<item name="Sparsh\FreeShippingBar\Api\Data\EntityInterface" xsi:type="string">Magento\Framework\EntityManager\AbstractModelHydrator</item>
</argument>
</arguments>
</type>
<type name="Magento\Shipping\Model\Shipping">
<plugin name="sparsh-free-shipping-bar-insertFreeShippingRates" type="Sparsh\FreeShippingBar\Plugin\Model\Shipping\InsertFreeShippingRates" sortOrder="10" disabled="false" />
</type>
</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="Sparsh_FreeShippingBar" setup_version="1.3.0" />
</config>
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Sparsh_FreeShippingBar',
__DIR__
);
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="editor"/>
<body>
<referenceContainer name="content">
<block class="Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit" name="sparsh_free_shipping_bar_entity_edit_content"/>
</referenceContainer>
<referenceContainer name="left">
<block class="Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tabs" name="sparsh_free_shipping_bar_entity_edit_tabs" >
<block class="Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab\Main" name="sparsh_free_shipping_bar_entity_edit_tab_main" as="main" />
<block class="Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab\WhatToDisplay" name="sparsh_free_shipping_bar_entity_edit_tab_what_to_display" as="what_to_display" />
<block class="Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab\WhereToDisplay" name="sparsh_free_shipping_bar_entity_edit_tab_where_to_display" as="where_to_display" />
</block>
</referenceContainer>
</body>
</page>
<?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="sparsh_free_shipping_bar_entity_listing"/>
</referenceContainer>
</body>
</page>
\ No newline at end of file
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="sparsh_free_shipping_bar_entity_edit"/>
</page>
<?php
/** @var $block \Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab\WhatToDisplay */
$goalMessages = [];
$goalMessages = $block->getGoalMessages();
?>
<fieldset class="fieldset admin__fieldset" id="sparsh_free_shipping_bar_entity_preview_template_fieldset">
<legend class="admin__legend legend">
<span><?= $block->escapeHtml(__('Preview Template')) ?></span>
</legend><br/>
</fieldset>
<?php foreach ($goalMessages as $messageKey => $messageValue) { ?>
<div class="sparsh-free-shipping-bar">
<a>
<div>
<p class="<?= /* @noEscape */ $messageKey?>"><?= /* @noEscape */ $messageValue?></p>
</div>
</a>
</div>
<?php } ?>
<script type="text/x-magento-init">
{
"*": {
"Sparsh_FreeShippingBar/js/jscolor": {},
"Sparsh_FreeShippingBar/js/preview-shipping-bar": {}
}
}
</script>
<?php
/** @var $block \Sparsh\FreeShippingBar\Block\Adminhtml\Entity\Edit\Tab\WhereToDisplay */
$entityId = $block->getEntityId() ? $block->getEntityId() : null;
if ($entityId):
?>
<fieldset class="fieldset admin__fieldset" id="sparsh_free_shipping_bar_entity_snippet_code_fieldset">
<legend class="admin__legend legend">
<span><?= $block->escapeHtml(__('Snippet Code')) ?></span>
</legend><br/>
<div>
<div class="admin__field-control control">
<div class="sparsh-free-shipping-bar-control-value">
<p>Use the following code to show the shipping bar block in any place you want:</p>
<strong>CMS Page/Static Block</strong>
<pre class="sparsh-free-shipping-bar-snippet-code"><code>&#123;&#123;block class="Sparsh\FreeShippingBar\Block\Entity\FreeShippingBar" template="Sparsh_FreeShippingBar::free_shipping_bar.phtml" entity_id="<?= /* @noEscape */ $entityId ?>"&#125;&#125;</code></pre>
<strong>Template .phtml file</strong>
<pre class="sparsh-free-shipping-bar-snippet-code"><code>&lt;?= $block-&gt;getLayout()-&gt;createBlock("Sparsh\FreeShippingBar\Block\Entity\FreeShippingBar")-&gt;setTemplate("free_shipping_bar.phtml")-&gt;setEntityId("<?= /* @noEscape */ $entityId ?>")-&gt;toHtml();?&gt;</code></pre>
<strong>Layout File</strong>
<pre class="sparsh-free-shipping-bar-snippet-code"><code>&lt;block class="Sparsh\FreeShippingBar\Block\Entity\FreeShippingBar" name="sparsh.free-shipping.bar" template="Sparsh_FreeShippingBar::free_shipping_bar.phtml"&gt;<br/>&nbsp;&nbsp;&lt;arguments&gt; <br/>&nbsp;&nbsp;&nbsp;&nbsp;&lt;argument name="entity_id" xsi:type="string"><?= /* @noEscape */ $entityId ?>&lt;/argument&gt;<br/>&nbsp;&nbsp;&lt;/arguments&gt;<br/>&lt;/block&gt;</code></pre>
</div>
</div>
</div>
</fieldset>
<?php endif; ?>
.sparsh-free-shipping-bar{
text-align: center;
line-height: 3;
}
.sparsh-free-shipping-bar a{
text-decoration: none;
}
.sparsh-free-shipping-bar #goal {
font-weight: bold;
}
.sparsh-free-shipping-bar-snippet-code{
background-color: #f5f5dc;
}
.field-snippet_code_insert .sparsh-free-shipping-bar-control-value p{
font-size: 16px;
}
define([
'jquery'
], function ($) {
"use strict";
return function () {
$(document).ready(function(){
var initialGoalMessage = $('#sparsh_free_shipping_bar_entity_initial_goal_message');
var achieveGoalMessage = $('#sparsh_free_shipping_bar_entity_achieve_goal_message');
var clickAble = $('#sparsh_free_shipping_bar_entity_is_clickable');
var linkUrl = $('#sparsh_free_shipping_bar_entity_bar_link_url');
var openInNewPage = $('#sparsh_free_shipping_bar_entity_is_link_open_in_new_page');
var barBackgroundColor = $('#sparsh_free_shipping_bar_entity_bar_background_color');
var barTextColor = $('#sparsh_free_shipping_bar_entity_bar_text_color');
var goalTextColor = $('#sparsh_free_shipping_bar_entity_goal_text_color');
var fontSize = $('#sparsh_free_shipping_bar_entity_bar_font_size');
var barContainer = $('.sparsh-free-shipping-bar');
var barLink = $('.sparsh-free-shipping-bar a');
var initialGoalText = $('.sparsh-free-shipping-bar .initial-message');
var achieveGoalText = $('.sparsh-free-shipping-bar .achieve-message');
var goalTextValue = initialGoalText.text().replace("{{goal}}", "<span id='goal'>{{goal}}</span>");
barContainer.css({"background-color": barBackgroundColor.val(), "font-size": fontSize.val()+'px'});
barLink.css("color", barTextColor.val());
initialGoalText.html(goalTextValue);
initialGoalText.find('#goal').css("color", goalTextColor.val());
if (clickAble.val() === '1' && linkUrl.val()) {
barLink.attr("href", linkUrl.val());
}
initialGoalMessage.change(function() {
initialGoalText.html(initialGoalMessage.val().replace("{{goal}}", "<span id='goal'>{{goal}}</span>"));
initialGoalText.find('#goal').css("color", goalTextColor.css('backgroundColor'));
});
achieveGoalMessage.change(function() {
achieveGoalText.html(achieveGoalMessage.val());
});
clickAble.on("change", function () {
if (clickAble.val() === '1') {
if(linkUrl.val()){
barLink.attr("href", linkUrl.val());
}
if (openInNewPage.val() === '1') {
barLink.attr("target", '_blank');
} else {
barLink.attr("target", '_self');
}
}
else{
barLink.removeAttr("href");
barLink.removeAttr("target");
}
});
linkUrl.on("change", function () {
if (linkUrl.val()) {
barLink.attr("href", linkUrl.val());
}
});
openInNewPage.on("change", function () {
if (openInNewPage.val() === '1') {
barLink.attr("target", '_blank');
} else {
barLink.attr("target", '_self');
}
});
barBackgroundColor.change(function() {
barContainer.css("background-color", barBackgroundColor.css('backgroundColor'));
});
barTextColor.change(function() {
barLink.css("color", barTextColor.css('backgroundColor'));
});
goalTextColor.change(function() {
initialGoalText.find('#goal').css("color", goalTextColor.css('backgroundColor'));
});
fontSize.change(function() {
barContainer.css("font-size", fontSize.val()+'px');
});
});
}
});
\ 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="page.wrapper">
<block class="Sparsh\FreeShippingBar\Block\Entity\FreeShippingBar"
name="sparsh.free-shipping.bar.top"
template="Sparsh_FreeShippingBar::free_shipping_bar.phtml"
before="-">
<arguments>
<argument name="position" xsi:type="string">page_top</argument>
</arguments>
</block>
<block class="Sparsh\FreeShippingBar\Block\Entity\FreeShippingBar"
name="sparsh.free-shipping.bar.bottom"
template="Sparsh_FreeShippingBar::free_shipping_bar.phtml"
after="-">
<arguments>
<argument name="position" xsi:type="string">page_bottom</argument>
</arguments>
</block>
</referenceContainer>
</body>
</page>
<?php
/** @var $block \Sparsh\FreeShippingBar\Block\Entity\FreeShippingBar */
?>
<?php
$isModuleEnable = $block->getConfig('sparsh_free_shipping_bar/general/enable');
$isFreeShippingBarAvailable = null;
if ($isModuleEnable):
$layoutPosition = $block->getData('position') ? $block->getData('position') : null;
$entityId = $block->getData('entity_id') ? $block->getData('entity_id') : null;
if ($layoutPosition || $entityId):
if ($entityId):
$barData = $block->getFreeShippingBarByEntityId($entityId);
$layoutPosition = 'insert_snippet';
elseif ($layoutPosition):
$barData = $block->getFreeShippingBar();
endif;
if ($barData):
if ($barData['bar_layout_position'] === $layoutPosition):
$isFreeShippingBarAvailable = 1;
endif;
endif;
endif;
endif;
?>
<?php if ($isFreeShippingBarAvailable): ?>
<div class="sparsh-free-shipping-bar-goal-message"
style="background-image: url(<?= $block->getImgUrl($barData['background_img']) ?>); background-repeat: no-repeat;background-position: center center; height: 60px; line-height: initial; text-align: center; background-color: <?= /* @noEscape */ $barData['bar_background_color']?>; font-size: <?= /* @noEscape */ $barData['bar_font_size'].'px'?>">
<a <?= /* @noEscape */ $barData['is_clickable'] ? 'href='.$barData['bar_link_url'] : null ?>
<?= /* @noEscape */ $barData['is_clickable'] ? ($barData['is_link_open_in_new_page'] ? 'target=_blank' : 'target=_self') : null ?>
style="color: <?= /* @noEscape */ $barData['bar_text_color']?>">
<div data-bind="scope: 'free-shipping-scope'">
<p data-bind="html: goalMessage"></p>
</div>
</a>
</div>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"free-shipping-scope": {
"component": "Sparsh_FreeShippingBar/js/free_shipping_bar",
"goal": "<?= /* @noEscape */ $barData['goal'] ?>",
"currency": "<?= /* @noEscape */ $block->getCurrentCurrencySymbol() ?>",
"goalColor": "<?= /* @noEscape */ $barData['goal_text_color'] ?>",
"initialGoalMessage": "<?= /* @noEscape */ $barData['initial_goal_message'] ?>",
"achieveGoalMessage": "<?= /* @noEscape */ $barData['achieve_goal_message'] ?>"
}
}
}
}
}
</script>
<?php endif ?>
.sparsh-free-shipping-bar-goal-message{
text-align: center;
padding-top: 15px;
padding-bottom: 15px;
}
.sparsh-free-shipping-bar-goal-message a{
text-decoration: none;
}
.sparsh-free-shipping-bar-goal-message p{
margin: 0;
}
.sparsh-free-shipping-bar-goal-message #goal {
font-weight: bold;
}
\ No newline at end of file
define([
'jquery',
'ko',
'uiComponent',
'Magento_Customer/js/customer-data',
'mage/translate'
], function ($, ko, Component, customerData) {
'use strict';
return Component.extend({
initialize: function (config) {
this._super();
this.below_goal = ko.observable();
var cartData = customerData.get('cart');
this.below_goal(cartData().subtotalAmount);
config.goal = +config.goal;
cartData.subscribe(function (updatedCart) {
this.below_goal(updatedCart.subtotalAmount);
}, this);
this.goalMessage = ko.computed(function () {
if (typeof(this.below_goal()) === "undefined" || this.below_goal() === null || this.below_goal() < config.goal) {
return config.initialGoalMessage.replace("{{goal}}", "<span id='goal' style='text-align: center; color:" + config.goalColor + ";'>" + config.currency + config.goal.toFixed(2) + "</span>");
}
else if(this.below_goal() >= config.goal){
return config.achieveGoalMessage;
}
}, this);
},
});
});
\ No newline at end of file
<?php
namespace Test\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 Test\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 Test\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 Test\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 Test\Banner\Block;
use Test\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,
\Test\Banner\Model\ResourceModel\Bass\CollectionFactory $collectionFactory,
\Test\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 Test\Banner\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Test\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.
/*$bass = $this->_bassFactory->create();
$collection = $bass->getCollection();
foreach ($collection as $item){
echo "<pre>";
print_r($item->getData());
echo "</pre>";
}
exit();*/
return $this->_pageFactory->create();
}
}
\ No newline at end of file
<?php
namespace Test\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 Test\Banner\Controller\Adminhtml\Index;
use \Magento\Backend\App\Action;
class Delete extends Action
{
const ADMIN_RESOURCE = 'Test_Banner::index';
public function execute()
{
// TODO: Implement execute() method.
$id = $this->getRequest()->getParam('id');
if ($id > 0){
$model = $this->_objectManager->create('Test\Banner\Model\Bass');
$model->load($id);
try {
$model->delete();
$this->messageManager->addSuccessMessage(__('Deleted success.'));
}catch (\Exception $e){
$this->messageManager->addSuccess(__('Deleted error.'));
}
}
$this->_redirect('test_banner/index');
}
}
\ No newline at end of file
<?php
namespace Test\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 Test\Banner\Model\BassFactory;
class Edit extends Action
{
const ADMIN_RESOURCE = "Test_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(\Test\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 Test\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 = "Test_Banner::index";
const FILE_DIR = 'test/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 Test\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 = "Test_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('Test_Banner::index');
$resultPage->getConfig()->getTitle()->prepend((__('Banners')));
return $resultPage;
}
}
\ No newline at end of file
<?php
namespace Test\Banner\Controller\Adminhtml\Index;
use Magento\Backend\App\Action\Context;
use Test\Banner\Model\BassFactory;
class Save extends \Magento\Backend\App\Action
{
const ADMIN_RESOURCE = "Test_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('test_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 Test\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 Test\Banner\Model;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\DataObject\IdentityInterface;
class Bass extends AbstractModel implements IdentityInterface
{
const CACHE_TAG = 'test_banner_bass';
protected $_cacheTat = 'test_banner_bass';
protected $_eventPrefix = 'test_banner_bass';
protected function _construct()
{
$this->_init('Test\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 Test\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('test_banner_bass','id');
}
}
\ No newline at end of file
<?php
namespace Test\Banner\Model\ResourceModel\Bass;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected $_idFieldName = 'id';
protected $_eventPrefix = 'test_banner_bass_collection';
protected $_eventObject = 'bass_collection';
protected function _construct(){
$this->_init('Test\Banner\Model\Bass','Test\Banner\Model\ResourceModel\Bass');
//$this->_init( \Test\Banner\Model\Bass::class, \Test\Banner\Model\ResourceModel\Bass::class );
}
}
\ No newline at end of file
<?php
namespace Test\Banner\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
public function install(ModuleDataSetupInterface $setup,ModuleContextInterface $context)
{
$adapter = $setup->getConnection();
$setup->startSetup();
$adapter->insertMultiple('test_banner_bass',['name'=>'test3']);
$adapter->insertMultiple('test_banner_bass',[['name'=>'test4'],['name'=>'test5']]);
$setup->endSetup();
}
}
\ No newline at end of file
<?php
namespace Test\Banner\Setup;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface{
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context){
$installer = $setup;
$installer->startSetup();
if (!$installer->tableExists('test_banner_bass')) {
$table = $installer->getConnection()->newTable($installer->getTable('test_banner_bass'))
->addColumn(
'id',
Table::TYPE_INTEGER,
null,
[
'identity' => true,
'unsigned' => true,
'nullable' => false,
'primary' => true
],
'ID'
)->addColumn(
'name',
Table::TYPE_TEXT,
255,
[
'nullable' => false,
'default' => ''
],
'NAME'
)->setComment(
'Banner Table'
);
$installer->getConnection()->createTable($table);
}
$installer->endSetup();
}
}
\ No newline at end of file
<?php
namespace Test\Banner\Setup;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Psr\Log\LoggerInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
protected $logger;
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(),'1.0.1','<') && $setup->tableExists('test_banner_bass')){
$this->getLogger()->info(111);
$connection = $setup->getConnection();
$connection->addColumn(
$setup->getTable('test_banner_bass'),
'status',
[
'type' => Table::TYPE_SMALLINT,
'nullable' => false,
'default' => 1,
'after' => 'name',
'comment' =>'STATUS'
]
);
$connection->addColumn(
$setup->getTable('test_banner_bass'),
'created_at',
[
'type' => Table::TYPE_TIMESTAMP,
'nullable' => false,
'default' => Table::TIMESTAMP_INIT,
'after' => 'status',
'comment' => 'CREATED AT'
]
);
$connection->addColumn(
$setup->getTable('test_banner_bass'),
'updated_at',
[
'type' => Table::TYPE_TIMESTAMP,
'nullable' => false,
'default' => Table::TIMESTAMP_INIT_UPDATE,
'comment' => 'UPDATED AT'
]
);
}
if (version_compare($context->getVersion(),'1.0.2','<')){
$this->getLogger()->info(222);//只要大于当前版本这个会进入
}
if (version_compare($context->getVersion(),'1.0.3','<')){
$this->getLogger()->info(333);//这个也会进入
}
$setup->endSetup();
}
protected function getLogger()
{
if ($this->logger === null){
$this->logger = ObjectManager::getInstance()->get(LoggerInterface::class);
}
return $this->logger;
}
}
\ No newline at end of file
<?php
namespace Test\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 Test\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 Test\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='test_banner/index/edit';
const URL_DELETE = 'test_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 Test\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 Test\Banner\UiForm\Model;
use Magento\Ui\DataProvider\AbstractDataProvider;
use Magento\Framework\App\RequestInterface;
use Test\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::test" title="Test" sortOrder="40">
<resource id="Magento_Backend::test_banner" title="Banner" sortOrder="10">
<resource id="Test_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::test"
title="Joshine"
module="Magento_Backend"
sortOrder="99"
resource="Magento_Backend::test"
/>
<add
id="Magento_Backend::test_banner"
title="Test"
translate="title"
module="Magento_Backend"
sortOrder="10"
parent="Magento_Backend::test"
resource="Magento_Backend::test_banner"
/>
<add
id="Test_Banner::index"
title="Banner"
module="Test_Banner"
sortOrder="10"
parent="Magento_Backend::test_banner"
action="test_banner/index/index"
resource="Test_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::test_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="test_banner" frontName="test_banner">
<module name="Test_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="test" translate="label" sortOrder="100">
<label>Test</label>
</tab>
<section id="test_banner" translate="label" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<class>separator-top</class>
<label>Banner</label>
<tab>test</tab>
<resource>Test_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>
<test_banner>
<options>
<autoplay>1</autoplay>
<loop>1</loop>
</options>
</test_banner>
</default>
</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