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; ?>
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Ui/etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing_data_source</item>
<item name="deps" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing_data_source</item>
</item>
<item name="spinner" xsi:type="string">sparsh_free_shipping_bar_entity_columns</item>
<item name="buttons" xsi:type="array">
<item name="add" xsi:type="array">
<item name="name" xsi:type="string">add</item>
<item name="label" xsi:type="string" translate="true">Add New Shipping Bar</item>
<item name="class" xsi:type="string">primary</item>
<item name="url" xsi:type="string">sparsh_free_shipping_bar/entity/new</item>
</item>
</item>
</argument>
<dataSource name="sparsh_free_shipping_bar_entity_listing_data_source">
<argument name="dataProvider" xsi:type="configurableObject">
<argument name="class" xsi:type="string">ShippingBarGridDataProvider</argument>
<argument name="name" xsi:type="string">sparsh_free_shipping_bar_entity_listing_data_source</argument>
<argument name="primaryFieldName" xsi:type="string">entity_id</argument>
<argument name="requestFieldName" xsi:type="string">entity_id</argument>
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
<item name="update_url" xsi:type="url" path="mui/index/render"/>
<item name="storageConfig" xsi:type="array">
<item name="indexField" xsi:type="string">entity_id</item>
</item>
</item>
</argument>
</argument>
</dataSource>
<container name="listing_top">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="template" xsi:type="string">ui/grid/toolbar</item>
</item>
</argument>
<bookmark name="bookmarks">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/controls/bookmarks/bookmarks</item>
<item name="displayArea" xsi:type="string">dataGridActions</item>
<item name="storageConfig" xsi:type="array">
<item name="saveUrl" xsi:type="url" path="mui/bookmark/save"/>
<item name="deleteUrl" xsi:type="url" path="mui/bookmark/delete"/>
<item name="namespace" xsi:type="string">sparsh_free_shipping_bar_entity_listing</item>
</item>
</item>
</argument>
</bookmark>
<container name="columns_controls">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="columnsData" xsi:type="array">
<item name="provider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_columns</item>
</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/controls/columns</item>
<item name="displayArea" xsi:type="string">dataGridActions</item>
</item>
</argument>
</container>
<filters name="listing_filters" />
<massaction name="listing_massaction">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="selectProvider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_columns.ids</item>
<item name="indexField" xsi:type="string">entity_id</item>
</item>
</argument>
<action name="enable">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">enable</item>
<item name="label" xsi:type="string" translate="true">Enable</item>
<item name="url" xsi:type="url" path="*/*/massEnable"/>
</item>
</argument>
</action>
<action name="disable">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">disable</item>
<item name="label" xsi:type="string" translate="true">Disable</item>
<item name="url" xsi:type="url" path="*/*/massDisable"/>
</item>
</argument>
</action>
<action name="delete">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">delete</item>
<item name="label" xsi:type="string" translate="true">Delete</item>
<item name="url" xsi:type="url" path="*/*/massDelete"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Delete items</item>
<item name="message" xsi:type="string" translate="true">Are you sure you want to delete selected items?</item>
</item>
</item>
</argument>
</action>
</massaction>
<paging name="listing_paging">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="storageConfig" xsi:type="array">
<item name="provider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.listing_top.bookmarks</item>
<item name="namespace" xsi:type="string">current.paging</item>
</item>
<item name="selectProvider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_columns.ids</item>
<item name="displayArea" xsi:type="string">bottom</item>
</item>
</argument>
</paging>
</container>
<columns name="sparsh_free_shipping_bar_entity_columns">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="storageConfig" xsi:type="array">
<item name="provider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.listing_top.bookmarks</item>
<item name="namespace" xsi:type="string">current</item>
</item>
<item name="childDefaults" xsi:type="array">
<item name="fieldAction" xsi:type="array">
<item name="provider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_columns.actions</item>
<item name="target" xsi:type="string">applyAction</item>
<item name="params" xsi:type="array">
<item name="0" xsi:type="string">edit</item>
<item name="1" xsi:type="string">${ $.$data.rowIndex }</item>
</item>
</item>
<item name="controlVisibility" xsi:type="boolean">true</item>
<item name="storageConfig" xsi:type="array">
<item name="provider" xsi:type="string">sparsh_free_shipping_bar_entity_listing.sparsh_free_shipping_bar_entity_listing.listing_top.bookmarks</item>
<item name="root" xsi:type="string">columns.${ $.index }</item>
<item name="namespace" xsi:type="string">current.${ $.storageConfig.root}</item>
</item>
</item>
</item>
</argument>
<selectionsColumn name="ids">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="resizeEnabled" xsi:type="boolean">false</item>
<item name="resizeDefaultWidth" xsi:type="string">55</item>
<item name="indexField" xsi:type="string">entity_id</item>
</item>
</argument>
</selectionsColumn>
<column name="entity_id">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">textRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
<item name="dataType" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">ID</item>
</item>
</argument>
</column>
<column name="name">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
<item name="dataType" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Name</item>
</item>
</argument>
</column>
<column name="from_date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
<item name="dateFormat" xsi:type="string">MMM d, YYYY</item>
<item name="label" xsi:type="string" translate="true">From Date</item>
</item>
</argument>
</column>
<column name="to_date">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">dateRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
<item name="dataType" xsi:type="string">date</item>
<item name="dateFormat" xsi:type="string">MMM d, YYYY</item>
<item name="label" xsi:type="string" translate="true">To Date</item>
</item>
</argument>
</column>
<column name="is_active">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Sparsh\FreeShippingBar\Model\Entity\Source\Status</item>
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">select</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
<item name="editor" xsi:type="string">select</item>
<item name="dataType" xsi:type="string">select</item>
<item name="label" xsi:type="string" translate="true">Status</item>
</item>
</argument>
</column>
<column name="sort_order">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">textRange</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
<item name="dataType" xsi:type="string">select</item>
<item name="label" xsi:type="string" translate="true">Priority</item>
<item name="sorting" xsi:type="string">asc</item>
</item>
</argument>
</column>
<actionsColumn name="actions" class="Sparsh\FreeShippingBar\Ui\Component\Listing\Column\FreeShippingBarActions">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">entity_id</item>
<item name="sortOrder" xsi:type="number">200</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing>
.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;
}
/**
* jscolor - JavaScript Color Picker
*
* @link http://jscolor.com
* @license For open source use: GPLv3
* For commercial use: JSColor Commercial License
* @author Jan Odvarko
* @version 2.0.5
*
* See usage examples at http://jscolor.com/examples/
*/
"use strict";
if (!window.jscolor) { window.jscolor = (function () {
var jsc = {
register : function () {
jsc.attachDOMReadyEvent(jsc.init);
jsc.attachEvent(document, 'mousedown', jsc.onDocumentMouseDown);
jsc.attachEvent(document, 'touchstart', jsc.onDocumentTouchStart);
jsc.attachEvent(window, 'resize', jsc.onWindowResize);
},
init : function () {
if (jsc.jscolor.lookupClass) {
jsc.jscolor.installByClassName(jsc.jscolor.lookupClass);
}
},
tryInstallOnElements : function (elms, className) {
var matchClass = new RegExp('(^|\\s)(' + className + ')(\\s*(\\{[^}]*\\})|\\s|$)', 'i');
for (var i = 0; i < elms.length; i += 1) {
if (elms[i].type !== undefined && elms[i].type.toLowerCase() == 'color') {
if (jsc.isColorAttrSupported) {
// skip inputs of type 'color' if supported by the browser
continue;
}
}
var m;
if (!elms[i].jscolor && elms[i].className && (m = elms[i].className.match(matchClass))) {
var targetElm = elms[i];
var optsStr = null;
var dataOptions = jsc.getDataAttr(targetElm, 'jscolor');
if (dataOptions !== null) {
optsStr = dataOptions;
} else if (m[4]) {
optsStr = m[4];
}
var opts = {};
if (optsStr) {
try {
opts = (new Function ('return (' + optsStr + ')'))();
} catch(eParseError) {
jsc.warn('Error parsing jscolor options: ' + eParseError + ':\n' + optsStr);
}
}
targetElm.jscolor = new jsc.jscolor(targetElm, opts);
}
}
},
isColorAttrSupported : (function () {
var elm = document.createElement('input');
if (elm.setAttribute) {
elm.setAttribute('type', 'color');
if (elm.type.toLowerCase() == 'color') {
return true;
}
}
return false;
})(),
isCanvasSupported : (function () {
var elm = document.createElement('canvas');
return !!(elm.getContext && elm.getContext('2d'));
})(),
fetchElement : function (mixed) {
return typeof mixed === 'string' ? document.getElementById(mixed) : mixed;
},
isElementType : function (elm, type) {
return elm.nodeName.toLowerCase() === type.toLowerCase();
},
getDataAttr : function (el, name) {
var attrName = 'data-' + name;
var attrValue = el.getAttribute(attrName);
if (attrValue !== null) {
return attrValue;
}
return null;
},
attachEvent : function (el, evnt, func) {
if (el.addEventListener) {
el.addEventListener(evnt, func, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evnt, func);
}
},
detachEvent : function (el, evnt, func) {
if (el.removeEventListener) {
el.removeEventListener(evnt, func, false);
} else if (el.detachEvent) {
el.detachEvent('on' + evnt, func);
}
},
_attachedGroupEvents : {},
attachGroupEvent : function (groupName, el, evnt, func) {
if (!jsc._attachedGroupEvents.hasOwnProperty(groupName)) {
jsc._attachedGroupEvents[groupName] = [];
}
jsc._attachedGroupEvents[groupName].push([el, evnt, func]);
jsc.attachEvent(el, evnt, func);
},
detachGroupEvents : function (groupName) {
if (jsc._attachedGroupEvents.hasOwnProperty(groupName)) {
for (var i = 0; i < jsc._attachedGroupEvents[groupName].length; i += 1) {
var evt = jsc._attachedGroupEvents[groupName][i];
jsc.detachEvent(evt[0], evt[1], evt[2]);
}
delete jsc._attachedGroupEvents[groupName];
}
},
attachDOMReadyEvent : function (func) {
var fired = false;
var fireOnce = function () {
if (!fired) {
fired = true;
func();
}
};
if (document.readyState === 'complete') {
setTimeout(fireOnce, 1); // async
return;
}
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fireOnce, false);
// Fallback
window.addEventListener('load', fireOnce, false);
} else if (document.attachEvent) {
// IE
document.attachEvent('onreadystatechange', function () {
if (document.readyState === 'complete') {
document.detachEvent('onreadystatechange', arguments.callee);
fireOnce();
}
})
// Fallback
window.attachEvent('onload', fireOnce);
// IE7/8
if (document.documentElement.doScroll && window == window.top) {
var tryScroll = function () {
if (!document.body) { return; }
try {
document.documentElement.doScroll('left');
fireOnce();
} catch (e) {
setTimeout(tryScroll, 1);
}
};
tryScroll();
}
}
},
warn : function (msg) {
if (window.console && window.console.warn) {
window.console.warn(msg);
}
},
preventDefault : function (e) {
if (e.preventDefault) { e.preventDefault(); }
e.returnValue = false;
},
captureTarget : function (target) {
// IE
if (target.setCapture) {
jsc._capturedTarget = target;
jsc._capturedTarget.setCapture();
}
},
releaseTarget : function () {
// IE
if (jsc._capturedTarget) {
jsc._capturedTarget.releaseCapture();
jsc._capturedTarget = null;
}
},
fireEvent : function (el, evnt) {
if (!el) {
return;
}
if (document.createEvent) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent(evnt, true, true);
el.dispatchEvent(ev);
} else if (document.createEventObject) {
var ev = document.createEventObject();
el.fireEvent('on' + evnt, ev);
} else if (el['on' + evnt]) { // alternatively use the traditional event model
el['on' + evnt]();
}
},
classNameToList : function (className) {
return className.replace(/^\s+|\s+$/g, '').split(/\s+/);
},
// The className parameter (str) can only contain a single class name
hasClass : function (elm, className) {
if (!className) {
return false;
}
return -1 != (' ' + elm.className.replace(/\s+/g, ' ') + ' ').indexOf(' ' + className + ' ');
},
// The className parameter (str) can contain multiple class names separated by whitespace
setClass : function (elm, className) {
var classList = jsc.classNameToList(className);
for (var i = 0; i < classList.length; i += 1) {
if (!jsc.hasClass(elm, classList[i])) {
elm.className += (elm.className ? ' ' : '') + classList[i];
}
}
},
// The className parameter (str) can contain multiple class names separated by whitespace
unsetClass : function (elm, className) {
var classList = jsc.classNameToList(className);
for (var i = 0; i < classList.length; i += 1) {
var repl = new RegExp(
'^\\s*' + classList[i] + '\\s*|' +
'\\s*' + classList[i] + '\\s*$|' +
'\\s+' + classList[i] + '(\\s+)',
'g'
);
elm.className = elm.className.replace(repl, '$1');
}
},
getStyle : function (elm) {
return window.getComputedStyle ? window.getComputedStyle(elm) : elm.currentStyle;
},
setStyle : (function () {
var helper = document.createElement('div');
var getSupportedProp = function (names) {
for (var i = 0; i < names.length; i += 1) {
if (names[i] in helper.style) {
return names[i];
}
}
};
var props = {
borderRadius: getSupportedProp(['borderRadius', 'MozBorderRadius', 'webkitBorderRadius']),
boxShadow: getSupportedProp(['boxShadow', 'MozBoxShadow', 'webkitBoxShadow'])
};
return function (elm, prop, value) {
switch (prop.toLowerCase()) {
case 'opacity':
var alphaOpacity = Math.round(parseFloat(value) * 100);
elm.style.opacity = value;
elm.style.filter = 'alpha(opacity=' + alphaOpacity + ')';
break;
default:
elm.style[props[prop]] = value;
break;
}
};
})(),
setBorderRadius : function (elm, value) {
jsc.setStyle(elm, 'borderRadius', value || '0');
},
setBoxShadow : function (elm, value) {
jsc.setStyle(elm, 'boxShadow', value || 'none');
},
getElementPos : function (e, relativeToViewport) {
var x=0, y=0;
var rect = e.getBoundingClientRect();
x = rect.left;
y = rect.top;
if (!relativeToViewport) {
var viewPos = jsc.getViewPos();
x += viewPos[0];
y += viewPos[1];
}
return [x, y];
},
getElementSize : function (e) {
return [e.offsetWidth, e.offsetHeight];
},
// get pointer's X/Y coordinates relative to viewport
getAbsPointerPos : function (e) {
if (!e) { e = window.event; }
var x = 0, y = 0;
if (typeof e.changedTouches !== 'undefined' && e.changedTouches.length) {
// touch devices
x = e.changedTouches[0].clientX;
y = e.changedTouches[0].clientY;
} else if (typeof e.clientX === 'number') {
x = e.clientX;
y = e.clientY;
}
return { x: x, y: y };
},
// get pointer's X/Y coordinates relative to target element
getRelPointerPos : function (e) {
if (!e) { e = window.event; }
var target = e.target || e.srcElement;
var targetRect = target.getBoundingClientRect();
var x = 0, y = 0;
var clientX = 0, clientY = 0;
if (typeof e.changedTouches !== 'undefined' && e.changedTouches.length) {
// touch devices
clientX = e.changedTouches[0].clientX;
clientY = e.changedTouches[0].clientY;
} else if (typeof e.clientX === 'number') {
clientX = e.clientX;
clientY = e.clientY;
}
x = clientX - targetRect.left;
y = clientY - targetRect.top;
return { x: x, y: y };
},
getViewPos : function () {
var doc = document.documentElement;
return [
(window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
(window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
];
},
getViewSize : function () {
var doc = document.documentElement;
return [
(window.innerWidth || doc.clientWidth),
(window.innerHeight || doc.clientHeight),
];
},
redrawPosition : function () {
if (jsc.picker && jsc.picker.owner) {
var thisObj = jsc.picker.owner;
var tp, vp;
if (thisObj.fixed) {
// Fixed elements are positioned relative to viewport,
// therefore we can ignore the scroll offset
tp = jsc.getElementPos(thisObj.targetElement, true); // target pos
vp = [0, 0]; // view pos
} else {
tp = jsc.getElementPos(thisObj.targetElement); // target pos
vp = jsc.getViewPos(); // view pos
}
var ts = jsc.getElementSize(thisObj.targetElement); // target size
var vs = jsc.getViewSize(); // view size
var ps = jsc.getPickerOuterDims(thisObj); // picker size
var a, b, c;
switch (thisObj.position.toLowerCase()) {
case 'left': a=1; b=0; c=-1; break;
case 'right':a=1; b=0; c=1; break;
case 'top': a=0; b=1; c=-1; break;
default: a=0; b=1; c=1; break;
}
var l = (ts[b]+ps[b])/2;
// compute picker position
if (!thisObj.smartPosition) {
var pp = [
tp[a],
tp[b]+ts[b]-l+l*c
];
} else {
var pp = [
-vp[a]+tp[a]+ps[a] > vs[a] ?
(-vp[a]+tp[a]+ts[a]/2 > vs[a]/2 && tp[a]+ts[a]-ps[a] >= 0 ? tp[a]+ts[a]-ps[a] : tp[a]) :
tp[a],
-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c > vs[b] ?
(-vp[b]+tp[b]+ts[b]/2 > vs[b]/2 && tp[b]+ts[b]-l-l*c >= 0 ? tp[b]+ts[b]-l-l*c : tp[b]+ts[b]-l+l*c) :
(tp[b]+ts[b]-l+l*c >= 0 ? tp[b]+ts[b]-l+l*c : tp[b]+ts[b]-l-l*c)
];
}
var x = pp[a];
var y = pp[b];
var positionValue = thisObj.fixed ? 'fixed' : 'absolute';
var contractShadow =
(pp[0] + ps[0] > tp[0] || pp[0] < tp[0] + ts[0]) &&
(pp[1] + ps[1] < tp[1] + ts[1]);
jsc._drawPosition(thisObj, x, y, positionValue, contractShadow);
}
},
_drawPosition : function (thisObj, x, y, positionValue, contractShadow) {
var vShadow = contractShadow ? 0 : thisObj.shadowBlur; // px
jsc.picker.wrap.style.position = positionValue;
jsc.picker.wrap.style.left = x + 'px';
jsc.picker.wrap.style.top = y + 'px';
jsc.setBoxShadow(
jsc.picker.boxS,
thisObj.shadow ?
new jsc.BoxShadow(0, vShadow, thisObj.shadowBlur, 0, thisObj.shadowColor) :
null);
},
getPickerDims : function (thisObj) {
var displaySlider = !!jsc.getSliderComponent(thisObj);
var dims = [
2 * thisObj.insetWidth + 2 * thisObj.padding + thisObj.width +
(displaySlider ? 2 * thisObj.insetWidth + jsc.getPadToSliderPadding(thisObj) + thisObj.sliderSize : 0),
2 * thisObj.insetWidth + 2 * thisObj.padding + thisObj.height +
(thisObj.closable ? 2 * thisObj.insetWidth + thisObj.padding + thisObj.buttonHeight : 0)
];
return dims;
},
getPickerOuterDims : function (thisObj) {
var dims = jsc.getPickerDims(thisObj);
return [
dims[0] + 2 * thisObj.borderWidth,
dims[1] + 2 * thisObj.borderWidth
];
},
getPadToSliderPadding : function (thisObj) {
return Math.max(thisObj.padding, 1.5 * (2 * thisObj.pointerBorderWidth + thisObj.pointerThickness));
},
getPadYComponent : function (thisObj) {
switch (thisObj.mode.charAt(1).toLowerCase()) {
case 'v': return 'v'; break;
}
return 's';
},
getSliderComponent : function (thisObj) {
if (thisObj.mode.length > 2) {
switch (thisObj.mode.charAt(2).toLowerCase()) {
case 's': return 's'; break;
case 'v': return 'v'; break;
}
}
return null;
},
onDocumentMouseDown : function (e) {
if (!e) { e = window.event; }
var target = e.target || e.srcElement;
if (target._jscLinkedInstance) {
if (target._jscLinkedInstance.showOnClick) {
target._jscLinkedInstance.show();
}
} else if (target._jscControlName) {
jsc.onControlPointerStart(e, target, target._jscControlName, 'mouse');
} else {
// Mouse is outside the picker controls -> hide the color picker!
if (jsc.picker && jsc.picker.owner) {
jsc.picker.owner.hide();
}
}
},
onDocumentTouchStart : function (e) {
if (!e) { e = window.event; }
var target = e.target || e.srcElement;
if (target._jscLinkedInstance) {
if (target._jscLinkedInstance.showOnClick) {
target._jscLinkedInstance.show();
}
} else if (target._jscControlName) {
jsc.onControlPointerStart(e, target, target._jscControlName, 'touch');
} else {
if (jsc.picker && jsc.picker.owner) {
jsc.picker.owner.hide();
}
}
},
onWindowResize : function (e) {
jsc.redrawPosition();
},
onParentScroll : function (e) {
// hide the picker when one of the parent elements is scrolled
if (jsc.picker && jsc.picker.owner) {
jsc.picker.owner.hide();
}
},
_pointerMoveEvent : {
mouse: 'mousemove',
touch: 'touchmove'
},
_pointerEndEvent : {
mouse: 'mouseup',
touch: 'touchend'
},
_pointerOrigin : null,
_capturedTarget : null,
onControlPointerStart : function (e, target, controlName, pointerType) {
var thisObj = target._jscInstance;
jsc.preventDefault(e);
jsc.captureTarget(target);
var registerDragEvents = function (doc, offset) {
jsc.attachGroupEvent('drag', doc, jsc._pointerMoveEvent[pointerType],
jsc.onDocumentPointerMove(e, target, controlName, pointerType, offset));
jsc.attachGroupEvent('drag', doc, jsc._pointerEndEvent[pointerType],
jsc.onDocumentPointerEnd(e, target, controlName, pointerType));
};
registerDragEvents(document, [0, 0]);
if (window.parent && window.frameElement) {
var rect = window.frameElement.getBoundingClientRect();
var ofs = [-rect.left, -rect.top];
registerDragEvents(window.parent.window.document, ofs);
}
var abs = jsc.getAbsPointerPos(e);
var rel = jsc.getRelPointerPos(e);
jsc._pointerOrigin = {
x: abs.x - rel.x,
y: abs.y - rel.y
};
switch (controlName) {
case 'pad':
// if the slider is at the bottom, move it up
switch (jsc.getSliderComponent(thisObj)) {
case 's': if (thisObj.hsv[1] === 0) { thisObj.fromHSV(null, 100, null); }; break;
case 'v': if (thisObj.hsv[2] === 0) { thisObj.fromHSV(null, null, 100); }; break;
}
jsc.setPad(thisObj, e, 0, 0);
break;
case 'sld':
jsc.setSld(thisObj, e, 0);
break;
}
jsc.dispatchFineChange(thisObj);
},
onDocumentPointerMove : function (e, target, controlName, pointerType, offset) {
return function (e) {
var thisObj = target._jscInstance;
switch (controlName) {
case 'pad':
if (!e) { e = window.event; }
jsc.setPad(thisObj, e, offset[0], offset[1]);
jsc.dispatchFineChange(thisObj);
break;
case 'sld':
if (!e) { e = window.event; }
jsc.setSld(thisObj, e, offset[1]);
jsc.dispatchFineChange(thisObj);
break;
}
}
},
onDocumentPointerEnd : function (e, target, controlName, pointerType) {
return function (e) {
var thisObj = target._jscInstance;
jsc.detachGroupEvents('drag');
jsc.releaseTarget();
// Always dispatch changes after detaching outstanding mouse handlers,
// in case some user interaction will occur in user's onchange callback
// that would intrude with current mouse events
jsc.dispatchChange(thisObj);
};
},
dispatchChange : function (thisObj) {
if (thisObj.valueElement) {
if (jsc.isElementType(thisObj.valueElement, 'input')) {
jsc.fireEvent(thisObj.valueElement, 'change');
}
}
},
dispatchFineChange : function (thisObj) {
if (thisObj.onFineChange) {
var callback;
if (typeof thisObj.onFineChange === 'string') {
callback = new Function (thisObj.onFineChange);
} else {
callback = thisObj.onFineChange;
}
callback.call(thisObj);
}
},
setPad : function (thisObj, e, ofsX, ofsY) {
var pointerAbs = jsc.getAbsPointerPos(e);
var x = ofsX + pointerAbs.x - jsc._pointerOrigin.x - thisObj.padding - thisObj.insetWidth;
var y = ofsY + pointerAbs.y - jsc._pointerOrigin.y - thisObj.padding - thisObj.insetWidth;
var xVal = x * (360 / (thisObj.width - 1));
var yVal = 100 - (y * (100 / (thisObj.height - 1)));
switch (jsc.getPadYComponent(thisObj)) {
case 's': thisObj.fromHSV(xVal, yVal, null, jsc.leaveSld); break;
case 'v': thisObj.fromHSV(xVal, null, yVal, jsc.leaveSld); break;
}
},
setSld : function (thisObj, e, ofsY) {
var pointerAbs = jsc.getAbsPointerPos(e);
var y = ofsY + pointerAbs.y - jsc._pointerOrigin.y - thisObj.padding - thisObj.insetWidth;
var yVal = 100 - (y * (100 / (thisObj.height - 1)));
switch (jsc.getSliderComponent(thisObj)) {
case 's': thisObj.fromHSV(null, yVal, null, jsc.leavePad); break;
case 'v': thisObj.fromHSV(null, null, yVal, jsc.leavePad); break;
}
},
_vmlNS : 'jsc_vml_',
_vmlCSS : 'jsc_vml_css_',
_vmlReady : false,
initVML : function () {
if (!jsc._vmlReady) {
// init VML namespace
var doc = document;
if (!doc.namespaces[jsc._vmlNS]) {
doc.namespaces.add(jsc._vmlNS, 'urn:schemas-microsoft-com:vml');
}
if (!doc.styleSheets[jsc._vmlCSS]) {
var tags = ['shape', 'shapetype', 'group', 'background', 'path', 'formulas', 'handles', 'fill', 'stroke', 'shadow', 'textbox', 'textpath', 'imagedata', 'line', 'polyline', 'curve', 'rect', 'roundrect', 'oval', 'arc', 'image'];
var ss = doc.createStyleSheet();
ss.owningElement.id = jsc._vmlCSS;
for (var i = 0; i < tags.length; i += 1) {
ss.addRule(jsc._vmlNS + '\\:' + tags[i], 'behavior:url(#default#VML);');
}
}
jsc._vmlReady = true;
}
},
createPalette : function () {
var paletteObj = {
elm: null,
draw: null
};
if (jsc.isCanvasSupported) {
// Canvas implementation for modern browsers
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var drawFunc = function (width, height, type) {
canvas.width = width;
canvas.height = height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var hGrad = ctx.createLinearGradient(0, 0, canvas.width, 0);
hGrad.addColorStop(0 / 6, '#F00');
hGrad.addColorStop(1 / 6, '#FF0');
hGrad.addColorStop(2 / 6, '#0F0');
hGrad.addColorStop(3 / 6, '#0FF');
hGrad.addColorStop(4 / 6, '#00F');
hGrad.addColorStop(5 / 6, '#F0F');
hGrad.addColorStop(6 / 6, '#F00');
ctx.fillStyle = hGrad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
var vGrad = ctx.createLinearGradient(0, 0, 0, canvas.height);
switch (type.toLowerCase()) {
case 's':
vGrad.addColorStop(0, 'rgba(255,255,255,0)');
vGrad.addColorStop(1, 'rgba(255,255,255,1)');
break;
case 'v':
vGrad.addColorStop(0, 'rgba(0,0,0,0)');
vGrad.addColorStop(1, 'rgba(0,0,0,1)');
break;
}
ctx.fillStyle = vGrad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
paletteObj.elm = canvas;
paletteObj.draw = drawFunc;
} else {
// VML fallback for IE 7 and 8
jsc.initVML();
var vmlContainer = document.createElement('div');
vmlContainer.style.position = 'relative';
vmlContainer.style.overflow = 'hidden';
var hGrad = document.createElement(jsc._vmlNS + ':fill');
hGrad.type = 'gradient';
hGrad.method = 'linear';
hGrad.angle = '90';
hGrad.colors = '16.67% #F0F, 33.33% #00F, 50% #0FF, 66.67% #0F0, 83.33% #FF0'
var hRect = document.createElement(jsc._vmlNS + ':rect');
hRect.style.position = 'absolute';
hRect.style.left = -1 + 'px';
hRect.style.top = -1 + 'px';
hRect.stroked = false;
hRect.appendChild(hGrad);
vmlContainer.appendChild(hRect);
var vGrad = document.createElement(jsc._vmlNS + ':fill');
vGrad.type = 'gradient';
vGrad.method = 'linear';
vGrad.angle = '180';
vGrad.opacity = '0';
var vRect = document.createElement(jsc._vmlNS + ':rect');
vRect.style.position = 'absolute';
vRect.style.left = -1 + 'px';
vRect.style.top = -1 + 'px';
vRect.stroked = false;
vRect.appendChild(vGrad);
vmlContainer.appendChild(vRect);
var drawFunc = function (width, height, type) {
vmlContainer.style.width = width + 'px';
vmlContainer.style.height = height + 'px';
hRect.style.width =
vRect.style.width =
(width + 1) + 'px';
hRect.style.height =
vRect.style.height =
(height + 1) + 'px';
// Colors must be specified during every redraw, otherwise IE won't display
// a full gradient during a subsequential redraw
hGrad.color = '#F00';
hGrad.color2 = '#F00';
switch (type.toLowerCase()) {
case 's':
vGrad.color = vGrad.color2 = '#FFF';
break;
case 'v':
vGrad.color = vGrad.color2 = '#000';
break;
}
};
paletteObj.elm = vmlContainer;
paletteObj.draw = drawFunc;
}
return paletteObj;
},
createSliderGradient : function () {
var sliderObj = {
elm: null,
draw: null
};
if (jsc.isCanvasSupported) {
// Canvas implementation for modern browsers
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var drawFunc = function (width, height, color1, color2) {
canvas.width = width;
canvas.height = height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var grad = ctx.createLinearGradient(0, 0, 0, canvas.height);
grad.addColorStop(0, color1);
grad.addColorStop(1, color2);
ctx.fillStyle = grad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
sliderObj.elm = canvas;
sliderObj.draw = drawFunc;
} else {
// VML fallback for IE 7 and 8
jsc.initVML();
var vmlContainer = document.createElement('div');
vmlContainer.style.position = 'relative';
vmlContainer.style.overflow = 'hidden';
var grad = document.createElement(jsc._vmlNS + ':fill');
grad.type = 'gradient';
grad.method = 'linear';
grad.angle = '180';
var rect = document.createElement(jsc._vmlNS + ':rect');
rect.style.position = 'absolute';
rect.style.left = -1 + 'px';
rect.style.top = -1 + 'px';
rect.stroked = false;
rect.appendChild(grad);
vmlContainer.appendChild(rect);
var drawFunc = function (width, height, color1, color2) {
vmlContainer.style.width = width + 'px';
vmlContainer.style.height = height + 'px';
rect.style.width = (width + 1) + 'px';
rect.style.height = (height + 1) + 'px';
grad.color = color1;
grad.color2 = color2;
};
sliderObj.elm = vmlContainer;
sliderObj.draw = drawFunc;
}
return sliderObj;
},
leaveValue : 1<<0,
leaveStyle : 1<<1,
leavePad : 1<<2,
leaveSld : 1<<3,
BoxShadow : (function () {
var BoxShadow = function (hShadow, vShadow, blur, spread, color, inset) {
this.hShadow = hShadow;
this.vShadow = vShadow;
this.blur = blur;
this.spread = spread;
this.color = color;
this.inset = !!inset;
};
BoxShadow.prototype.toString = function () {
var vals = [
Math.round(this.hShadow) + 'px',
Math.round(this.vShadow) + 'px',
Math.round(this.blur) + 'px',
Math.round(this.spread) + 'px',
this.color
];
if (this.inset) {
vals.push('inset');
}
return vals.join(' ');
};
return BoxShadow;
})(),
//
// Usage:
// var myColor = new jscolor(<targetElement> [, <options>])
//
jscolor : function (targetElement, options) {
// General options
//
this.value = null; // initial HEX color. To change it later, use methods fromString(), fromHSV() and fromRGB()
this.valueElement = targetElement; // element that will be used to display and input the color code
this.styleElement = targetElement; // element that will preview the picked color using CSS backgroundColor
this.required = true; // whether the associated text <input> can be left empty
this.refine = true; // whether to refine the entered color code (e.g. uppercase it and remove whitespace)
this.hash = false; // whether to prefix the HEX color code with # symbol
this.uppercase = true; // whether to show the color code in upper case
this.onFineChange = null; // called instantly every time the color changes (value can be either a function or a string with javascript code)
this.activeClass = 'jscolor-active'; // class to be set to the target element when a picker window is open on it
this.overwriteImportant = false; // whether to overwrite colors of styleElement using !important
this.minS = 0; // min allowed saturation (0 - 100)
this.maxS = 100; // max allowed saturation (0 - 100)
this.minV = 0; // min allowed value (brightness) (0 - 100)
this.maxV = 100; // max allowed value (brightness) (0 - 100)
// Accessing the picked color
//
this.hsv = [0, 0, 100]; // read-only [0-360, 0-100, 0-100]
this.rgb = [255, 255, 255]; // read-only [0-255, 0-255, 0-255]
// Color Picker options
//
this.width = 181; // width of color palette (in px)
this.height = 101; // height of color palette (in px)
this.showOnClick = true; // whether to display the color picker when user clicks on its target element
this.mode = 'HSV'; // HSV | HVS | HS | HV - layout of the color picker controls
this.position = 'bottom'; // left | right | top | bottom - position relative to the target element
this.smartPosition = true; // automatically change picker position when there is not enough space for it
this.sliderSize = 16; // px
this.crossSize = 8; // px
this.closable = false; // whether to display the Close button
this.closeText = 'Close';
this.buttonColor = '#000000'; // CSS color
this.buttonHeight = 18; // px
this.padding = 12; // px
this.backgroundColor = '#FFFFFF'; // CSS color
this.borderWidth = 1; // px
this.borderColor = '#BBBBBB'; // CSS color
this.borderRadius = 8; // px
this.insetWidth = 1; // px
this.insetColor = '#BBBBBB'; // CSS color
this.shadow = true; // whether to display shadow
this.shadowBlur = 15; // px
this.shadowColor = 'rgba(0,0,0,0.2)'; // CSS color
this.pointerColor = '#4C4C4C'; // px
this.pointerBorderColor = '#FFFFFF'; // px
this.pointerBorderWidth = 1; // px
this.pointerThickness = 2; // px
this.zIndex = 1000;
this.container = null; // where to append the color picker (BODY element by default)
for (var opt in options) {
if (options.hasOwnProperty(opt)) {
this[opt] = options[opt];
}
}
this.hide = function () {
if (isPickerOwner()) {
detachPicker();
}
};
this.show = function () {
drawPicker();
};
this.redraw = function () {
if (isPickerOwner()) {
drawPicker();
}
};
this.importColor = function () {
if (!this.valueElement) {
this.exportColor();
} else {
if (jsc.isElementType(this.valueElement, 'input')) {
if (!this.refine) {
if (!this.fromString(this.valueElement.value, jsc.leaveValue)) {
if (this.styleElement) {
this.styleElement.style.backgroundImage = this.styleElement._jscOrigStyle.backgroundImage;
this.styleElement.style.backgroundColor = this.styleElement._jscOrigStyle.backgroundColor;
this.styleElement.style.color = this.styleElement._jscOrigStyle.color;
}
this.exportColor(jsc.leaveValue | jsc.leaveStyle);
}
} else if (!this.required && /^\s*$/.test(this.valueElement.value)) {
this.valueElement.value = '';
if (this.styleElement) {
this.styleElement.style.backgroundImage = this.styleElement._jscOrigStyle.backgroundImage;
this.styleElement.style.backgroundColor = this.styleElement._jscOrigStyle.backgroundColor;
this.styleElement.style.color = this.styleElement._jscOrigStyle.color;
}
this.exportColor(jsc.leaveValue | jsc.leaveStyle);
} else if (this.fromString(this.valueElement.value)) {
// managed to import color successfully from the value -> OK, don't do anything
} else {
this.exportColor();
}
} else {
// not an input element -> doesn't have any value
this.exportColor();
}
}
};
this.exportColor = function (flags) {
if (!(flags & jsc.leaveValue) && this.valueElement) {
var value = this.toString();
if (this.uppercase) { value = value.toUpperCase(); }
if (this.hash) { value = '#' + value; }
if (jsc.isElementType(this.valueElement, 'input')) {
this.valueElement.value = value;
} else {
this.valueElement.innerHTML = value;
}
}
if (!(flags & jsc.leaveStyle)) {
if (this.styleElement) {
var bgColor = '#' + this.toString();
var fgColor = this.isLight() ? '#000' : '#FFF';
this.styleElement.style.backgroundImage = 'none';
this.styleElement.style.backgroundColor = bgColor;
this.styleElement.style.color = fgColor;
if (this.overwriteImportant) {
this.styleElement.setAttribute('style',
'background: ' + bgColor + ' !important; ' +
'color: ' + fgColor + ' !important;'
);
}
}
}
if (!(flags & jsc.leavePad) && isPickerOwner()) {
redrawPad();
}
if (!(flags & jsc.leaveSld) && isPickerOwner()) {
redrawSld();
}
};
// h: 0-360
// s: 0-100
// v: 0-100
//
this.fromHSV = function (h, s, v, flags) { // null = don't change
if (h !== null) {
if (isNaN(h)) { return false; }
h = Math.max(0, Math.min(360, h));
}
if (s !== null) {
if (isNaN(s)) { return false; }
s = Math.max(0, Math.min(100, this.maxS, s), this.minS);
}
if (v !== null) {
if (isNaN(v)) { return false; }
v = Math.max(0, Math.min(100, this.maxV, v), this.minV);
}
this.rgb = HSV_RGB(
h===null ? this.hsv[0] : (this.hsv[0]=h),
s===null ? this.hsv[1] : (this.hsv[1]=s),
v===null ? this.hsv[2] : (this.hsv[2]=v)
);
this.exportColor(flags);
};
// r: 0-255
// g: 0-255
// b: 0-255
//
this.fromRGB = function (r, g, b, flags) { // null = don't change
if (r !== null) {
if (isNaN(r)) { return false; }
r = Math.max(0, Math.min(255, r));
}
if (g !== null) {
if (isNaN(g)) { return false; }
g = Math.max(0, Math.min(255, g));
}
if (b !== null) {
if (isNaN(b)) { return false; }
b = Math.max(0, Math.min(255, b));
}
var hsv = RGB_HSV(
r===null ? this.rgb[0] : r,
g===null ? this.rgb[1] : g,
b===null ? this.rgb[2] : b
);
if (hsv[0] !== null) {
this.hsv[0] = Math.max(0, Math.min(360, hsv[0]));
}
if (hsv[2] !== 0) {
this.hsv[1] = hsv[1]===null ? null : Math.max(0, this.minS, Math.min(100, this.maxS, hsv[1]));
}
this.hsv[2] = hsv[2]===null ? null : Math.max(0, this.minV, Math.min(100, this.maxV, hsv[2]));
// update RGB according to final HSV, as some values might be trimmed
var rgb = HSV_RGB(this.hsv[0], this.hsv[1], this.hsv[2]);
this.rgb[0] = rgb[0];
this.rgb[1] = rgb[1];
this.rgb[2] = rgb[2];
this.exportColor(flags);
};
this.fromString = function (str, flags) {
var m;
if (m = str.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i)) {
// HEX notation
//
if (m[1].length === 6) {
// 6-char notation
this.fromRGB(
parseInt(m[1].substr(0,2),16),
parseInt(m[1].substr(2,2),16),
parseInt(m[1].substr(4,2),16),
flags
);
} else {
// 3-char notation
this.fromRGB(
parseInt(m[1].charAt(0) + m[1].charAt(0),16),
parseInt(m[1].charAt(1) + m[1].charAt(1),16),
parseInt(m[1].charAt(2) + m[1].charAt(2),16),
flags
);
}
return true;
} else if (m = str.match(/^\W*rgba?\(([^)]*)\)\W*$/i)) {
var params = m[1].split(',');
var re = /^\s*(\d*)(\.\d+)?\s*$/;
var mR, mG, mB;
if (
params.length >= 3 &&
(mR = params[0].match(re)) &&
(mG = params[1].match(re)) &&
(mB = params[2].match(re))
) {
var r = parseFloat((mR[1] || '0') + (mR[2] || ''));
var g = parseFloat((mG[1] || '0') + (mG[2] || ''));
var b = parseFloat((mB[1] || '0') + (mB[2] || ''));
this.fromRGB(r, g, b, flags);
return true;
}
}
return false;
};
this.toString = function () {
return (
(0x100 | Math.round(this.rgb[0])).toString(16).substr(1) +
(0x100 | Math.round(this.rgb[1])).toString(16).substr(1) +
(0x100 | Math.round(this.rgb[2])).toString(16).substr(1)
);
};
this.toHEXString = function () {
return '#' + this.toString().toUpperCase();
};
this.toRGBString = function () {
return ('rgb(' +
Math.round(this.rgb[0]) + ',' +
Math.round(this.rgb[1]) + ',' +
Math.round(this.rgb[2]) + ')'
);
};
this.isLight = function () {
return (
0.213 * this.rgb[0] +
0.715 * this.rgb[1] +
0.072 * this.rgb[2] >
255 / 2
);
};
this._processParentElementsInDOM = function () {
if (this._linkedElementsProcessed) { return; }
this._linkedElementsProcessed = true;
var elm = this.targetElement;
do {
// If the target element or one of its parent nodes has fixed position,
// then use fixed positioning instead
//
// Note: In Firefox, getComputedStyle returns null in a hidden iframe,
// that's why we need to check if the returned style object is non-empty
var currStyle = jsc.getStyle(elm);
if (currStyle && currStyle.position.toLowerCase() === 'fixed') {
this.fixed = true;
}
if (elm !== this.targetElement) {
// Ensure to attach onParentScroll only once to each parent element
// (multiple targetElements can share the same parent nodes)
//
// Note: It's not just offsetParents that can be scrollable,
// that's why we loop through all parent nodes
if (!elm._jscEventsAttached) {
jsc.attachEvent(elm, 'scroll', jsc.onParentScroll);
elm._jscEventsAttached = true;
}
}
} while ((elm = elm.parentNode) && !jsc.isElementType(elm, 'body'));
};
// r: 0-255
// g: 0-255
// b: 0-255
//
// returns: [ 0-360, 0-100, 0-100 ]
//
function RGB_HSV (r, g, b) {
r /= 255;
g /= 255;
b /= 255;
var n = Math.min(Math.min(r,g),b);
var v = Math.max(Math.max(r,g),b);
var m = v - n;
if (m === 0) { return [ null, 0, 100 * v ]; }
var h = r===n ? 3+(b-g)/m : (g===n ? 5+(r-b)/m : 1+(g-r)/m);
return [
60 * (h===6?0:h),
100 * (m/v),
100 * v
];
}
// h: 0-360
// s: 0-100
// v: 0-100
//
// returns: [ 0-255, 0-255, 0-255 ]
//
function HSV_RGB (h, s, v) {
var u = 255 * (v / 100);
if (h === null) {
return [ u, u, u ];
}
h /= 60;
s /= 100;
var i = Math.floor(h);
var f = i%2 ? h-i : 1-(h-i);
var m = u * (1 - s);
var n = u * (1 - s * f);
switch (i) {
case 6:
case 0: return [u,n,m];
case 1: return [n,u,m];
case 2: return [m,u,n];
case 3: return [m,n,u];
case 4: return [n,m,u];
case 5: return [u,m,n];
}
}
function detachPicker () {
jsc.unsetClass(THIS.targetElement, THIS.activeClass);
jsc.picker.wrap.parentNode.removeChild(jsc.picker.wrap);
delete jsc.picker.owner;
}
function drawPicker () {
// At this point, when drawing the picker, we know what the parent elements are
// and we can do all related DOM operations, such as registering events on them
// or checking their positioning
THIS._processParentElementsInDOM();
if (!jsc.picker) {
jsc.picker = {
owner: null,
wrap : document.createElement('div'),
box : document.createElement('div'),
boxS : document.createElement('div'), // shadow area
boxB : document.createElement('div'), // border
pad : document.createElement('div'),
padB : document.createElement('div'), // border
padM : document.createElement('div'), // mouse/touch area
padPal : jsc.createPalette(),
cross : document.createElement('div'),
crossBY : document.createElement('div'), // border Y
crossBX : document.createElement('div'), // border X
crossLY : document.createElement('div'), // line Y
crossLX : document.createElement('div'), // line X
sld : document.createElement('div'),
sldB : document.createElement('div'), // border
sldM : document.createElement('div'), // mouse/touch area
sldGrad : jsc.createSliderGradient(),
sldPtrS : document.createElement('div'), // slider pointer spacer
sldPtrIB : document.createElement('div'), // slider pointer inner border
sldPtrMB : document.createElement('div'), // slider pointer middle border
sldPtrOB : document.createElement('div'), // slider pointer outer border
btn : document.createElement('div'),
btnT : document.createElement('span') // text
};
jsc.picker.pad.appendChild(jsc.picker.padPal.elm);
jsc.picker.padB.appendChild(jsc.picker.pad);
jsc.picker.cross.appendChild(jsc.picker.crossBY);
jsc.picker.cross.appendChild(jsc.picker.crossBX);
jsc.picker.cross.appendChild(jsc.picker.crossLY);
jsc.picker.cross.appendChild(jsc.picker.crossLX);
jsc.picker.padB.appendChild(jsc.picker.cross);
jsc.picker.box.appendChild(jsc.picker.padB);
jsc.picker.box.appendChild(jsc.picker.padM);
jsc.picker.sld.appendChild(jsc.picker.sldGrad.elm);
jsc.picker.sldB.appendChild(jsc.picker.sld);
jsc.picker.sldB.appendChild(jsc.picker.sldPtrOB);
jsc.picker.sldPtrOB.appendChild(jsc.picker.sldPtrMB);
jsc.picker.sldPtrMB.appendChild(jsc.picker.sldPtrIB);
jsc.picker.sldPtrIB.appendChild(jsc.picker.sldPtrS);
jsc.picker.box.appendChild(jsc.picker.sldB);
jsc.picker.box.appendChild(jsc.picker.sldM);
jsc.picker.btn.appendChild(jsc.picker.btnT);
jsc.picker.box.appendChild(jsc.picker.btn);
jsc.picker.boxB.appendChild(jsc.picker.box);
jsc.picker.wrap.appendChild(jsc.picker.boxS);
jsc.picker.wrap.appendChild(jsc.picker.boxB);
}
var p = jsc.picker;
var displaySlider = !!jsc.getSliderComponent(THIS);
var dims = jsc.getPickerDims(THIS);
var crossOuterSize = (2 * THIS.pointerBorderWidth + THIS.pointerThickness + 2 * THIS.crossSize);
var padToSliderPadding = jsc.getPadToSliderPadding(THIS);
var borderRadius = Math.min(
THIS.borderRadius,
Math.round(THIS.padding * Math.PI)); // px
var padCursor = 'crosshair';
// wrap
p.wrap.style.clear = 'both';
p.wrap.style.width = (dims[0] + 2 * THIS.borderWidth) + 'px';
p.wrap.style.height = (dims[1] + 2 * THIS.borderWidth) + 'px';
p.wrap.style.zIndex = THIS.zIndex;
// picker
p.box.style.width = dims[0] + 'px';
p.box.style.height = dims[1] + 'px';
p.boxS.style.position = 'absolute';
p.boxS.style.left = '0';
p.boxS.style.top = '0';
p.boxS.style.width = '100%';
p.boxS.style.height = '100%';
jsc.setBorderRadius(p.boxS, borderRadius + 'px');
// picker border
p.boxB.style.position = 'relative';
p.boxB.style.border = THIS.borderWidth + 'px solid';
p.boxB.style.borderColor = THIS.borderColor;
p.boxB.style.background = THIS.backgroundColor;
jsc.setBorderRadius(p.boxB, borderRadius + 'px');
// IE hack:
// If the element is transparent, IE will trigger the event on the elements under it,
// e.g. on Canvas or on elements with border
p.padM.style.background =
p.sldM.style.background =
'#FFF';
jsc.setStyle(p.padM, 'opacity', '0');
jsc.setStyle(p.sldM, 'opacity', '0');
// pad
p.pad.style.position = 'relative';
p.pad.style.width = THIS.width + 'px';
p.pad.style.height = THIS.height + 'px';
// pad palettes (HSV and HVS)
p.padPal.draw(THIS.width, THIS.height, jsc.getPadYComponent(THIS));
// pad border
p.padB.style.position = 'absolute';
p.padB.style.left = THIS.padding + 'px';
p.padB.style.top = THIS.padding + 'px';
p.padB.style.border = THIS.insetWidth + 'px solid';
p.padB.style.borderColor = THIS.insetColor;
// pad mouse area
p.padM._jscInstance = THIS;
p.padM._jscControlName = 'pad';
p.padM.style.position = 'absolute';
p.padM.style.left = '0';
p.padM.style.top = '0';
p.padM.style.width = (THIS.padding + 2 * THIS.insetWidth + THIS.width + padToSliderPadding / 2) + 'px';
p.padM.style.height = dims[1] + 'px';
p.padM.style.cursor = padCursor;
// pad cross
p.cross.style.position = 'absolute';
p.cross.style.left =
p.cross.style.top =
'0';
p.cross.style.width =
p.cross.style.height =
crossOuterSize + 'px';
// pad cross border Y and X
p.crossBY.style.position =
p.crossBX.style.position =
'absolute';
p.crossBY.style.background =
p.crossBX.style.background =
THIS.pointerBorderColor;
p.crossBY.style.width =
p.crossBX.style.height =
(2 * THIS.pointerBorderWidth + THIS.pointerThickness) + 'px';
p.crossBY.style.height =
p.crossBX.style.width =
crossOuterSize + 'px';
p.crossBY.style.left =
p.crossBX.style.top =
(Math.floor(crossOuterSize / 2) - Math.floor(THIS.pointerThickness / 2) - THIS.pointerBorderWidth) + 'px';
p.crossBY.style.top =
p.crossBX.style.left =
'0';
// pad cross line Y and X
p.crossLY.style.position =
p.crossLX.style.position =
'absolute';
p.crossLY.style.background =
p.crossLX.style.background =
THIS.pointerColor;
p.crossLY.style.height =
p.crossLX.style.width =
(crossOuterSize - 2 * THIS.pointerBorderWidth) + 'px';
p.crossLY.style.width =
p.crossLX.style.height =
THIS.pointerThickness + 'px';
p.crossLY.style.left =
p.crossLX.style.top =
(Math.floor(crossOuterSize / 2) - Math.floor(THIS.pointerThickness / 2)) + 'px';
p.crossLY.style.top =
p.crossLX.style.left =
THIS.pointerBorderWidth + 'px';
// slider
p.sld.style.overflow = 'hidden';
p.sld.style.width = THIS.sliderSize + 'px';
p.sld.style.height = THIS.height + 'px';
// slider gradient
p.sldGrad.draw(THIS.sliderSize, THIS.height, '#000', '#000');
// slider border
p.sldB.style.display = displaySlider ? 'block' : 'none';
p.sldB.style.position = 'absolute';
p.sldB.style.right = THIS.padding + 'px';
p.sldB.style.top = THIS.padding + 'px';
p.sldB.style.border = THIS.insetWidth + 'px solid';
p.sldB.style.borderColor = THIS.insetColor;
// slider mouse area
p.sldM._jscInstance = THIS;
p.sldM._jscControlName = 'sld';
p.sldM.style.display = displaySlider ? 'block' : 'none';
p.sldM.style.position = 'absolute';
p.sldM.style.right = '0';
p.sldM.style.top = '0';
p.sldM.style.width = (THIS.sliderSize + padToSliderPadding / 2 + THIS.padding + 2 * THIS.insetWidth) + 'px';
p.sldM.style.height = dims[1] + 'px';
p.sldM.style.cursor = 'default';
// slider pointer inner and outer border
p.sldPtrIB.style.border =
p.sldPtrOB.style.border =
THIS.pointerBorderWidth + 'px solid ' + THIS.pointerBorderColor;
// slider pointer outer border
p.sldPtrOB.style.position = 'absolute';
p.sldPtrOB.style.left = -(2 * THIS.pointerBorderWidth + THIS.pointerThickness) + 'px';
p.sldPtrOB.style.top = '0';
// slider pointer middle border
p.sldPtrMB.style.border = THIS.pointerThickness + 'px solid ' + THIS.pointerColor;
// slider pointer spacer
p.sldPtrS.style.width = THIS.sliderSize + 'px';
p.sldPtrS.style.height = sliderPtrSpace + 'px';
// the Close button
function setBtnBorder () {
var insetColors = THIS.insetColor.split(/\s+/);
var outsetColor = insetColors.length < 2 ? insetColors[0] : insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0] + ' ' + insetColors[1];
p.btn.style.borderColor = outsetColor;
}
p.btn.style.display = THIS.closable ? 'block' : 'none';
p.btn.style.position = 'absolute';
p.btn.style.left = THIS.padding + 'px';
p.btn.style.bottom = THIS.padding + 'px';
p.btn.style.padding = '0 15px';
p.btn.style.height = THIS.buttonHeight + 'px';
p.btn.style.border = THIS.insetWidth + 'px solid';
setBtnBorder();
p.btn.style.color = THIS.buttonColor;
p.btn.style.font = '12px sans-serif';
p.btn.style.textAlign = 'center';
try {
p.btn.style.cursor = 'pointer';
} catch(eOldIE) {
p.btn.style.cursor = 'hand';
}
p.btn.onmousedown = function () {
THIS.hide();
};
p.btnT.style.lineHeight = THIS.buttonHeight + 'px';
p.btnT.innerHTML = '';
p.btnT.appendChild(document.createTextNode(THIS.closeText));
// place pointers
redrawPad();
redrawSld();
// If we are changing the owner without first closing the picker,
// make sure to first deal with the old owner
if (jsc.picker.owner && jsc.picker.owner !== THIS) {
jsc.unsetClass(jsc.picker.owner.targetElement, THIS.activeClass);
}
// Set the new picker owner
jsc.picker.owner = THIS;
// The redrawPosition() method needs picker.owner to be set, that's why we call it here,
// after setting the owner
if (jsc.isElementType(container, 'body')) {
jsc.redrawPosition();
} else {
jsc._drawPosition(THIS, 0, 0, 'relative', false);
}
if (p.wrap.parentNode != container) {
container.appendChild(p.wrap);
}
jsc.setClass(THIS.targetElement, THIS.activeClass);
}
function redrawPad () {
// redraw the pad pointer
switch (jsc.getPadYComponent(THIS)) {
case 's': var yComponent = 1; break;
case 'v': var yComponent = 2; break;
}
var x = Math.round((THIS.hsv[0] / 360) * (THIS.width - 1));
var y = Math.round((1 - THIS.hsv[yComponent] / 100) * (THIS.height - 1));
var crossOuterSize = (2 * THIS.pointerBorderWidth + THIS.pointerThickness + 2 * THIS.crossSize);
var ofs = -Math.floor(crossOuterSize / 2);
jsc.picker.cross.style.left = (x + ofs) + 'px';
jsc.picker.cross.style.top = (y + ofs) + 'px';
// redraw the slider
switch (jsc.getSliderComponent(THIS)) {
case 's':
var rgb1 = HSV_RGB(THIS.hsv[0], 100, THIS.hsv[2]);
var rgb2 = HSV_RGB(THIS.hsv[0], 0, THIS.hsv[2]);
var color1 = 'rgb(' +
Math.round(rgb1[0]) + ',' +
Math.round(rgb1[1]) + ',' +
Math.round(rgb1[2]) + ')';
var color2 = 'rgb(' +
Math.round(rgb2[0]) + ',' +
Math.round(rgb2[1]) + ',' +
Math.round(rgb2[2]) + ')';
jsc.picker.sldGrad.draw(THIS.sliderSize, THIS.height, color1, color2);
break;
case 'v':
var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 100);
var color1 = 'rgb(' +
Math.round(rgb[0]) + ',' +
Math.round(rgb[1]) + ',' +
Math.round(rgb[2]) + ')';
var color2 = '#000';
jsc.picker.sldGrad.draw(THIS.sliderSize, THIS.height, color1, color2);
break;
}
}
function redrawSld () {
var sldComponent = jsc.getSliderComponent(THIS);
if (sldComponent) {
// redraw the slider pointer
switch (sldComponent) {
case 's': var yComponent = 1; break;
case 'v': var yComponent = 2; break;
}
var y = Math.round((1 - THIS.hsv[yComponent] / 100) * (THIS.height - 1));
jsc.picker.sldPtrOB.style.top = (y - (2 * THIS.pointerBorderWidth + THIS.pointerThickness) - Math.floor(sliderPtrSpace / 2)) + 'px';
}
}
function isPickerOwner () {
return jsc.picker && jsc.picker.owner === THIS;
}
function blurValue () {
THIS.importColor();
}
// Find the target element
if (typeof targetElement === 'string') {
var id = targetElement;
var elm = document.getElementById(id);
if (elm) {
this.targetElement = elm;
} else {
jsc.warn('Could not find target element with ID \'' + id + '\'');
}
} else if (targetElement) {
this.targetElement = targetElement;
} else {
jsc.warn('Invalid target element: \'' + targetElement + '\'');
}
if (this.targetElement._jscLinkedInstance) {
jsc.warn('Cannot link jscolor twice to the same element. Skipping.');
return;
}
this.targetElement._jscLinkedInstance = this;
// Find the value element
this.valueElement = jsc.fetchElement(this.valueElement);
// Find the style element
this.styleElement = jsc.fetchElement(this.styleElement);
var THIS = this;
var container =
this.container ?
jsc.fetchElement(this.container) :
document.getElementsByTagName('body')[0];
var sliderPtrSpace = 3; // px
// For BUTTON elements it's important to stop them from sending the form when clicked
// (e.g. in Safari)
if (jsc.isElementType(this.targetElement, 'button')) {
if (this.targetElement.onclick) {
var origCallback = this.targetElement.onclick;
this.targetElement.onclick = function (evt) {
origCallback.call(this, evt);
return false;
};
} else {
this.targetElement.onclick = function () { return false; };
}
}
/*
var elm = this.targetElement;
do {
// If the target element or one of its offsetParents has fixed position,
// then use fixed positioning instead
//
// Note: In Firefox, getComputedStyle returns null in a hidden iframe,
// that's why we need to check if the returned style object is non-empty
var currStyle = jsc.getStyle(elm);
if (currStyle && currStyle.position.toLowerCase() === 'fixed') {
this.fixed = true;
}
if (elm !== this.targetElement) {
// attach onParentScroll so that we can recompute the picker position
// when one of the offsetParents is scrolled
if (!elm._jscEventsAttached) {
jsc.attachEvent(elm, 'scroll', jsc.onParentScroll);
elm._jscEventsAttached = true;
}
}
} while ((elm = elm.offsetParent) && !jsc.isElementType(elm, 'body'));
*/
// valueElement
if (this.valueElement) {
if (jsc.isElementType(this.valueElement, 'input')) {
var updateField = function () {
THIS.fromString(THIS.valueElement.value, jsc.leaveValue);
jsc.dispatchFineChange(THIS);
};
jsc.attachEvent(this.valueElement, 'keyup', updateField);
jsc.attachEvent(this.valueElement, 'input', updateField);
jsc.attachEvent(this.valueElement, 'blur', blurValue);
this.valueElement.setAttribute('autocomplete', 'off');
}
}
// styleElement
if (this.styleElement) {
this.styleElement._jscOrigStyle = {
backgroundImage : this.styleElement.style.backgroundImage,
backgroundColor : this.styleElement.style.backgroundColor,
color : this.styleElement.style.color
};
}
if (this.value) {
// Try to set the color from the .value option and if unsuccessful,
// export the current color
this.fromString(this.value) || this.exportColor();
} else {
this.importColor();
}
}
};
//================================
// Public properties and methods
//================================
// By default, search for all elements with class="jscolor" and install a color picker on them.
//
// You can change what class name will be looked for by setting the property jscolor.lookupClass
// anywhere in your HTML document. To completely disable the automatic lookup, set it to null.
//
jsc.jscolor.lookupClass = 'jscolor';
jsc.jscolor.installByClassName = function (className) {
var inputElms = document.getElementsByTagName('input');
var buttonElms = document.getElementsByTagName('button');
jsc.tryInstallOnElements(inputElms, className);
jsc.tryInstallOnElements(buttonElms, className);
};
jsc.register();
return jsc.jscolor;
})(); }
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
<?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="test_banner_bass">
<column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" comment="ID" identity="true" />
<column xsi:type="varchar" name="title" default="" nullable="false" length="255" comment="TITLE" />
<column xsi:type="smallint" name="status" default="1" nullable="false" padding="2" comment="STATUS 1=ENABLE 0=DISABLE"/>
<column xsi:type="varchar" name="desc" default="" nullable="false" length="255" comment="DESC" />
<column xsi:type="varchar" name="url" default="" nullable="false" length="255" comment="URL" />
<column xsi:type="smallint" name="sort" default="0" nullable="false" padding="2" comment="SORT" />
<column xsi:type="varchar" name="img_patch" default="" nullable="false" length="255" comment="IMG PATCH" />
<column xsi:type="varchar" name="phone_img_patch" default="" nullable="false" length="255" comment="IMG PATCH" />
<column xsi:type="timestamp" name="created_at" default="CURRENT_TIMESTAMP" on_update="false" comment="CREATED AT" />
<column xsi:type="timestamp" name="updated_at" default="CURRENT_TIMESTAMP" on_update="true" comment="UPDATED AT" />
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="id" />
</constraint>
</table>
</schema>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
<item name="test_banner_index_listing_data_source" xsi:type="string">Test\Banner\Model\ResourceModel\Bass\Grid\Collection</item>
</argument>
</arguments>
</type>
<virtualType name="Test\Banner\Model\ResourceModel\Bass\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">test_banner_bass</argument>
<argument name="resourceModel" xsi:type="string">Test\Banner\Model\ResourceModel\Bass</argument>
</arguments>
</virtualType>
</config>
\ No newline at end of file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd" >
<router id="standard">
<route frontName="banner" id="banner">
<module name="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:framework:Module/etc/module.xsd">
<module name="Test_Banner" setup_version="1.0.0" />
</config>
\ No newline at end of file
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Test_Banner',
__DIR__
);
\ No newline at end of file
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<uiComponent name="test_banner_index_form"/>
</referenceContainer>
</body>
</page>
\ No newline at end of file
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<uiComponent name="test_banner_index_listing"/>
</referenceContainer>
</body>
</page>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">test_banner_index_form.test_banner_index_form_data_source</item>
</item>
<item name="label" xsi:type="string" translate="true">Banner</item>
<item name="template" xsi:type="string">templates/form/collapsible</item>
</argument>
<settings>
<buttons>
<button name="save" class="Test\Banner\Block\Adminhtml\Edit\SaveButton"></button>
<button name="delete" class="Test\Banner\Block\Adminhtml\Edit\DeleteButton"></button>
<button name="back" class="Test\Banner\Block\Adminhtml\Edit\BackButton"></button>
</buttons>
<namespace>test_banner_index_form</namespace>
<dataScope>data</dataScope>
<deps>
<dep>test_banner_index_form.test_banner_index_form_data_source</dep>
</deps>
</settings>
<dataSource name="test_banner_index_from_data_source">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
</item>
</argument>
<settings>
<submitUrl path="test_banner/index/save"/>
</settings>
<dataProvider class="Test\Banner\UiForm\Model\DataProvider" name="test_banner_index_form_data_source">
<settings>
<requestFieldName>id</requestFieldName>
<primaryFieldName>id</primaryFieldName>
</settings>
</dataProvider>
</dataSource>
<fieldset name="general">
<settings>
<label></label>
</settings>
<!--select选择框-->
<field name="active" sortOrder="0" formElement="select">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>number</dataType>
<label translate="true">Active</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="title" sortOrder="10" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Title</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="desc" sortOrder="20" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Description</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="url" sortOrder="30" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Url</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
<field name="pcImage" sortOrder="40" formElement="imageUploader">
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">PC Image</label>
<visible>true</visible>
<required>true</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="test_banner/index_fileUploader/save"/>
</uploaderConfig>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
<field name="phoneImage" sortOrder="50" formElement="imageUploader">
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">Phone Image</label>
<visible>true</visible>
<required>true</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="test_banner/index_fileUploader/save"/>
</uploaderConfig>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
<field name="sort" sortOrder="60" formElement="input">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">general</item>
</item>
</argument>
<settings>
<dataType>text</dataType>
<label translate="true">Sort</label>
<visible>true</visible>
<required>true</required>
</settings>
</field>
</fieldset>
</form>
\ No newline at end of file
<?xml version="1.0" ?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<!--配置声明旧的组件结构 settings节点进行替换和配置 name=data必须 可嵌套-->
<argument name="data" xsi:type="array">
<!--所有其他子节点都声明为项。<item name="config"> ...</item>包含描述当前 UI 组件配置的子节点。请注意,尽管所有组件的配置都不同,但不同组件的基本属性基本相同。例如,我们可以使用<item name="component">...</item>定义哪个 JS 文件将用作上述示例中的 Fieldset UI 组件的模型。对该 JS 文件的引用可以是该文件的完整路径,也可以是require.js配置中定义的别名。在这个例子中,我们只展示了可能配置的一小部分。
包含该项添加和声明了组件
-->
<item name="js_config" xsi:type="array">
<item name="provider" xsi:type="string">test_banner_index_listing.test_banner_index_listing_data_source</item>
<item name="deps" xsi:type="string">test_banner_index_listing.test_banner_index_listing_data_source</item>
</item>
<!--组件的名称 [ComponentName].[ComponentName]_data_source -->
<item name="spinner" xsi:type="string">test_banner_items_columns</item>
<item name="buttons" xsi:type="array">
<item name="add" xsi:type="array">
<item name="name" xsi:type="string">add</item>
<item name="label" xsi:type="string" translate="true">Add Banner</item>
<item name="class" xsi:type="string">primary</item>
<item name="url" xsi:type="string">*/*/add</item>
</item>
</item>
</argument>
<!--数据源 component属性注册的magento组件名称-->
<dataSource name="test_banner_index_listing_data_source" component="Magento_Ui/js/grid/provider">
<!--声明新的结构-->
<settings>
<updateUrl path="mui/index/render" />
</settings>
<!--<aclResource>Test::Banner<aclResource/> 数据提供者 名称-->
<dataProvider class="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider" name="test_banner_index_listing_data_source">
<settings>
<!--请求字段名一般为主键-->
<requestFieldName>id</requestFieldName>
<!--主键-->
<primaryFieldName>id</primaryFieldName>
</settings>
</dataProvider>
</dataSource>
<!-- 工具条 -->
<container name="listing_top">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="template" xsi:type="string">ui/grid/toolbar</item>
</item>
</argument>
<!--过滤器-->
<filters name="listing_filters"/>
<!--书签-->
<bookmark name="bookmark"/>
<!--控制显示字段-->
<columnsControls name="columns_controls"/>
<!--导出-->
<exportButton name="export_button"/>
<!--分页-->
<paging name="listing_paging"/>
</container>
<!-- 显示字段 columns name一定要改不然会出现load图片和遮罩层一直存在的bug -->
<columns name="test_banner_items_columns">
<column name="id">
<argument name="data" xsi:type="array">
<item name="js_config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
</item>
<item name="config" xsi:type="array">
<item name="indexField" xsi:type="string">id</item>
<item name="filter" xsi:type="string">text</item>
<item name="sorting" xsi:type="string">desc</item>
<item name="label" xsi:type="string" translate="true">ID</item>
</item>
</argument>
</column>
<column name="title">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Title</item>
</item>
</argument>
</column>
<column name="desc">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Description</item>
<item name="resizeEnabled" xsi:type="boolean">true</item>
<item name="resizeDefaultWidth" xsi:type="string">60</item>
</item>
</argument>
</column>
<column name="url">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Url</item>
<item name="resizeEnabled" xsi:type="boolean">true</item>
<item name="resizeDefaultWidth" xsi:type="string">60</item>
</item>
</argument>
</column>
<column name="sort">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Sort</item>
</item>
</argument>
</column>
<column name="status" class="Test\Banner\Ui\Component\Listing\Column\Status">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Status</item>
</item>
</argument>
</column>
<column name="img_patch" class="Test\Banner\Ui\Component\Listing\Column\ImgPatch">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Pc Image patch</item>
</item>
</argument>
</column>
<column name="phone_img_patch" class="Test\Banner\Ui\Component\Listing\Column\PhoneImagePatch">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Phone Image patch</item>
</item>
</argument>
</column>
<actionsColumn name="actions" class="Test\Banner\Ui\Component\Listing\Column\PostActions">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="resizeEnabled" xsi:type="boolean">false</item>
<item name="resizeDefaultWidth" xsi:type="string">10</item>
<item name="indexField" xsi:type="string">id</item>
</item>
</argument>
</actionsColumn>
</columns>
</listing>
\ No newline at end of file
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="Test\Banner\Block\Index" name="banner_index_index" template="Test_Banner::index.phtml" />
</referenceContainer>
</page>
\ No newline at end of file
var config = {
paths: {
'banner': 'Test_Banner/js/banner',
'owlcarousel': "Test_Banner/js/owl.carousel"
},
shim: {
'banner': ['jquery'],
'owlcarousel': ['jquery']
}
}
\ No newline at end of file
<?php
/** @var $block \Test\Banner\Block\Index */
$collection = $block->getCollection();
?>
<div class="banner1" style="background-color: #f0f0f0;"></div>
<?php foreach ($collection->getItems() as $item):?>
<?php echo $item->getData('name');?>
<?php endforeach;?>
<link rel="stylesheet" type="text/css" href="<?php echo $block->getViewFileUrl('Test_Banner::css/banner.css'); ?>">
<script type="text/javascript">
require(['jquery','banner'],function ($){
var img_arr =
[
<?php foreach ($collection->getItems() as $item):?>
[
<?php echo "'/media/" . $item->getData('img_patch') . "',";?>
<?php echo "'/media/" . $item->getData('phone_img_patch') . "',";?>
],
<?php endforeach;?>
];
var href = [
<?php foreach ($collection->getItems() as $item):?>
<?php echo "'" . $item->getData('url') . "',";?>
<?php endforeach;?>
];
jQuery('.banner1').banner({
img: img_arr,
href:href,
btn: true,
list: true,
autoPlay: true,
delayTime: 5000,
moveTime: 500,
index: 0
});
var h_max = 0;
$('.top_banner').each(function (i,v){
var h = $(this).height();
h_max = h > h_max ? h : h_max;
});
$('.banner1').height(h_max);
$('.banner1').css('line-height',h_max+'px');
var buttonTop = h_max/2;
$('#left').css({'top':buttonTop,'line-height': 0});
$('#right').css({'top':buttonTop,'line-height': 0});
console.log(h_max);
});
</script>
\ No newline at end of file
.top_banner{
width: 100%;
}
input#left,input#right {
padding-top: 2px;
}
@media (max-width: 768px) {
input#left, input#right {
padding: 1px;
}
}
@media (max-width: 1024px) {
.rating-result::before, .rating-result>span::before {
-webkit-mask-size: 1rem 1rem;
}
.rating-result{
width: 5rem;
height: 1rem;
}
p.flashsale-title{
font-size: 18px;
}
}
\ No newline at end of file
.banner1,.banner1 >.imgbox, .banner1 >.imgbox > a, .banner1 >.imgbox > a >img{
height: 634px !important;
}
.top_banner{
width: 100%;
}
input#left,input#right {
top: 300px !important;
padding-top: 2px;
}
@media (max-width: 768px) {
.banner1, .banner1 > .imgbox, .banner1 > .imgbox > a, .banner1 > .imgbox > a > img,.top_banner {
height: 577px !important;
}
input#left, input#right {
top: 280px !important;
padding: 1px;
}
}
@media (max-width: 1024px) {
.rating-result::before, .rating-result>span::before {
-webkit-mask-size: 1rem 1rem;
}
.rating-result{
width: 5rem;
height: 1rem;
}
p.flashsale-title{
font-size: 18px;
}
}
\ No newline at end of file
define(['jquery'],function ($){
$.fn.banner = function(options){
var that = this;
options = options || {};
this._obj = {
btn:options.btn===false ? false : true,
list:options.list===false ? false : true,
autoPlay:options.autoPlay===false ? false : true,
delayTime:options.delayTime || 2000,
moveTime:options.moveTime || 200,
index:options.index || 0,
iPrev:options.img.length-1,
img:options.img || [],
href:options.href || [],
};
this._obj.init = function(){
var str = ``;
for(var i=0;i<this.img.length;i++){
str += `<a href="${this.href[i]}"><picture>
<source media="(max-width: 768px)" srcset="${this.img[i][1]}" />
<source media="(min-width: 769px)" srcset="${this.img[i][0]}" />
<img src="${this.img[i][0]}" loading="lazy" class="top_banner" /></picture></a>`
}
that.html(`<div class="imgbox">${str}</div>`).css({
"width":"100%",
"height":"auto",
position:"relative",
overflow:"hidden"
}).children(".imgbox").css({
"width":"100%",
}).children("a").css({
position: "absolute",
left:1920,
top:0,
"width":"100%",
}).eq(0).css({
left:0
}).end().children("img").css({
"width":"100%",
});
}
this._obj.init();
this._obj.leftClick=function () {
if (that._obj.index ==0){
that._obj.index = that._obj.img.length-1;
that._obj.iPrev=0;
}else{
that._obj.index--;
that._obj.iPrev=that._obj.index+1;
}
that._obj.btnMove(1);
}
this._obj.rightClick=function(){
if (that._obj.index ==that._obj.img.length-1){
that._obj.index = 0;
that._obj.iPrev=that._obj.img.length-1;
}else{
that._obj.index++;
that._obj.iPrev=that._obj.index-1;
}
that._obj.btnMove(-1);
}
if (this._obj.btn){
$("<input type='button' id='left' value='<'>").css({
left:0,
}).appendTo(this).
after($("<input type='button' id='right' value='>'>").css({
right:0,
})).parent()
.children("input").css({
position:"absolute",
top:130,
width:30,
height:30,
border:"none",
background:"rgba(200,200,200,0.5)",
borderRadius:"50%",
color:"#ffffff"
})
this.on("click","#left",that._obj.leftClick)
this.on("click","#right",that._obj.rightClick)
this._obj.btnMove=function (type) {
let imgs=that.children(".imgbox").children("a");
imgs.eq(this.iPrev).css({
left:0
}).stop().animate({
left:imgs.eq(0).width()*type
},this.moveTime).end().eq(this.index).css({
left:-imgs.eq(0).width()*type
}).stop().animate({
left:0
},this.moveTime)
if(!this.list) return;
$(".list").children("li").css("background","rgba(200,200,200,0.6)")
.eq(this.index).css("background","#005caf")
}
}
if (this._obj.list){
let str="";
for (var i=0;i<this._obj.img.length;i++){
str+=`<li></li>`;
}
$("<ul class='list'>").html(str).appendTo(this).css({
margin:0,
padding:0,
listStyle:"none",
width:"100%",
height:40,
bottom:0,
position:"absolute",
display:"flex",
justifyContent:"center",
lineHeight:"40px",
textAlign:"center"
}).children("li").css({
width:40,
height:6,
background:"rgba(200,200,200,0.6)",
margin:"0 5px",
textAlign: "center",
cursor:"pointer"
}).eq(0).css({
background:"#005caf"
}).end().click(function () {
if ($(this).index()>that._obj.index){
that._obj.listMove($(this).index(),-1)
}
if ($(this).index()<that._obj.index){
that._obj.listMove($(this).index(),1)
}
that._obj.index = $(this).index();
})
this._obj.listMove=function (iNow,type) {
let imgs=that.children(".imgbox").children("a");
imgs.eq(this.index).css({
left:0
}).stop().animate({
left:imgs.eq(0).width()*type
},this.moveTime).end().eq(iNow).css({
left:-imgs.eq(0).width()*type
}).stop().animate({
left:0
},this.moveTime)
$(".list").children("li").css("background","rgba(200,200,200,0.6)")
.eq(iNow).css("background","#005caf")
}
}
if (this._obj.autoPlay){
this._obj.t=setInterval(()=>{
this._obj.rightClick();
},this._obj.delayTime);
this.hover(function () {
clearInterval(that._obj.t)
},function () {
that._obj.t=setInterval(()=>{
that._obj.rightClick();
},that._obj.delayTime);
})
}
}
});
\ No newline at end of file
...@@ -4,224 +4,8 @@ ...@@ -4,224 +4,8 @@
* See COPYING.txt for license details. * See COPYING.txt for license details.
*/ */
?> ?>
<style>
.banner1,.banner1 >.imgbox, .banner1 >.imgbox > a, .banner1 >.imgbox > a >img{
height: 634px !important;
}
.top_banner{
width: 100%;
}
input#left,input#right {
top: 300px !important;
padding-top: 2px;
}
@media (max-width: 768px) {
.banner1, .banner1 > .imgbox, .banner1 > .imgbox > a, .banner1 > .imgbox > a > img,.top_banner {
height: 577px !important;
}
input#left, input#right {
top: 280px !important;
padding: 1px;
}
}
@media (max-width: 1024px) {
.rating-result::before, .rating-result>span::before {
-webkit-mask-size: 1rem 1rem;
}
.rating-result{
width: 5rem;
height: 1rem;
}
p.flashsale-title{
font-size: 18px;
}
}
</style>
<div class="banner1" style="background-color: #f0f0f0;"></div>
<script>
require([
'jquery'
], function ($) {
$.fn.banner = function(options){
var that = this;
options = options || {};
this._obj = {
btn:options.btn===false ? false : true,
list:options.list===false ? false : true,
autoPlay:options.autoPlay===false ? false : true,
delayTime:options.delayTime || 2000,
moveTime:options.moveTime || 200,
index:options.index || 0,
iPrev:options.img.length-1,
img:options.img || [],
href:options.href || [],
};
this._obj.init = function(){
var str = ``;
for(var i=0;i<this.img.length;i++){
str += `<a href="${this.href[i]}"><picture>
<source media="(max-width: 768px)" srcset="${this.img[i][1]}" />
<source media="(min-width: 769px)" srcset="${this.img[i][0]}" />
<img src="${this.img[i][0]}" loading="lazy" class="top_banner" /></picture></a>`
}
that.html(`<div class="imgbox">${str}</div>`).css({
"width":"100%",
"height":"auto",
position:"relative",
overflow:"hidden"
}).children(".imgbox").css({
"width":"100%",
}).children("a").css({ <?php echo $block->getLayout()->createBlock('Test\Banner\Block\Index')->setTemplate('Test_Banner::index.phtml')->toHtml(); ?>
position: "absolute",
left:1920,
top:0,
"width":"100%",
}).eq(0).css({
left:0
}).end().children("img").css({
"width":"100%",
});
}
this._obj.init();
this._obj.leftClick=function () {
if (that._obj.index ==0){
that._obj.index = that._obj.img.length-1;
that._obj.iPrev=0;
}else{
that._obj.index--;
that._obj.iPrev=that._obj.index+1;
}
that._obj.btnMove(1);
}
this._obj.rightClick=function(){
if (that._obj.index ==that._obj.img.length-1){
that._obj.index = 0;
that._obj.iPrev=that._obj.img.length-1;
}else{
that._obj.index++;
that._obj.iPrev=that._obj.index-1;
}
that._obj.btnMove(-1);
}
if (this._obj.btn){
$("<input type='button' id='left' value='<'>").css({
left:0,
}).appendTo(this).
after($("<input type='button' id='right' value='>'>").css({
right:0,
})).parent()
.children("input").css({
position:"absolute",
top:130,
width:30,
height:30,
border:"none",
background:"rgba(200,200,200,0.5)",
borderRadius:"50%",
color:"#ffffff"
})
this.on("click","#left",that._obj.leftClick)
this.on("click","#right",that._obj.rightClick)
this._obj.btnMove=function (type) {
let imgs=that.children(".imgbox").children("a");
imgs.eq(this.iPrev).css({
left:0
}).stop().animate({
left:imgs.eq(0).width()*type
},this.moveTime).end().eq(this.index).css({
left:-imgs.eq(0).width()*type
}).stop().animate({
left:0
},this.moveTime)
if(!this.list) return;
$(".list").children("li").css("background","rgba(200,200,200,0.6)")
.eq(this.index).css("background","#005caf")
}
}
if (this._obj.list){
let str="";
for (var i=0;i<this._obj.img.length;i++){
str+=`<li></li>`;
}
$("<ul class='list'>").html(str).appendTo(this).css({
margin:0,
padding:0,
listStyle:"none",
width:"100%",
height:40,
bottom:0,
position:"absolute",
display:"flex",
justifyContent:"center",
lineHeight:"40px",
textAlign:"center"
}).children("li").css({
width:40,
height:6,
background:"rgba(200,200,200,0.6)",
margin:"0 5px",
textAlign: "center",
cursor:"pointer"
}).eq(0).css({
background:"#005caf"
}).end().click(function () {
if ($(this).index()>that._obj.index){
that._obj.listMove($(this).index(),-1)
}
if ($(this).index()<that._obj.index){
that._obj.listMove($(this).index(),1)
}
that._obj.index = $(this).index();
})
this._obj.listMove=function (iNow,type) {
let imgs=that.children(".imgbox").children("a");
imgs.eq(this.index).css({
left:0
}).stop().animate({
left:imgs.eq(0).width()*type
},this.moveTime).end().eq(iNow).css({
left:-imgs.eq(0).width()*type
}).stop().animate({
left:0
},this.moveTime)
$(".list").children("li").css("background","rgba(200,200,200,0.6)")
.eq(iNow).css("background","#005caf")
}
}
if (this._obj.autoPlay){
this._obj.t=setInterval(()=>{
this._obj.rightClick();
},this._obj.delayTime);
this.hover(function () {
clearInterval(that._obj.t)
},function () {
that._obj.t=setInterval(()=>{
that._obj.rightClick();
},that._obj.delayTime);
})
}
}
var img_arr = [["/media/carousel/pc/1.jpg","/media/carousel/mobile/1.jpg"],
["/media/carousel/pc/2.jpg","/media/carousel/mobile/2.jpg"] ];
$(".banner1").banner({
img: img_arr,
href: ["/collections/shapewear", "/collections/shapewear"],
btn: true,
list: true,
autoPlay: true,
delayTime: 5000,
moveTime: 500,
index: 0
});
});
</script>
<?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('home_top_category_thumnail')->toHtml();?> <?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('home_top_category_thumnail')->toHtml();?>
<?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('home_new_arrivals')->toHtml();?> <?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('home_new_arrivals')->toHtml();?>
<?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('flashsaleproduct')->toHtml();?> <?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('flashsaleproduct')->toHtml();?>
......
...@@ -47,5 +47,4 @@ ...@@ -47,5 +47,4 @@
<p><?= $block->escapeHtml(__('This is a demo store. No orders will be fulfilled.')) ?></p> <p><?= $block->escapeHtml(__('This is a demo store. No orders will be fulfilled.')) ?></p>
</div> </div>
</div> </div>
<?php endif; ?> <?php endif; ?>
<?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('header_text')->toHtml();?> \ No newline at end of file
\ 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