How to extend galley.phtml in Magento2? - magento

I want to add custom code in gallery.phtml in the PDP section on my custom module.
I tried this=>
called default the block in catalog_product_view.xml
<referenceBlock name="product.info.media.image">
<action method="setTemplate">
<argument name="template" xsi:type="string">Ajith_Mymodule::product/view/gallery.phtml</argument>
</action>
</referenceBlock>
loaded gallery.phtml with and without default code, nothing works well for me.
Am I'm trying the correct method or did anybody give me the idea to do this?

This method is working properly
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product media data template
*
* #var $block \Magento\Catalog\Block\Product\View\Gallery
*/
?>
<?php
$images = $block->getGalleryImages()->getItems();
$mainImage = current(array_filter($images, function ($img) use ($block) {
return $block->isMainImage($img);
}));
if (!empty($images) && empty($mainImage)) {
$mainImage = $block->getGalleryImages()->getFirstItem();
}
$helper = $block->getData('imageHelper');
$mainImageData = $mainImage ?
$mainImage->getData('medium_image_url') :
$helper->getDefaultPlaceholderUrl('image');
?>
<div class="gallery-placeholder _block-content-loading" data-gallery-role="gallery-placeholder">
<img
alt="main product photo"
class="gallery-placeholder__image"
src="<?= /* #noEscape */ $mainImageData ?>"
/>
</div>
<script type="text/x-magento-init">
{
"[data-gallery-role=gallery-placeholder]": {
"mage/gallery/gallery": {
"mixins":["magnifier/magnify"],
"magnifierOpts": <?= /* #noEscape */ $block->getMagnifier() ?>,
"data": <?= /* #noEscape */ $block->getGalleryImagesJson() ?>,
"options": <?= /* #noEscape */ $block->getGalleryOptions()->getOptionsJson() ?>,
"fullscreen": <?= /* #noEscape */ $block->getGalleryOptions()->getFSOptionsJson() ?>,
"breakpoints": <?= /* #noEscape */ $block->getBreakpoints() ?>
}
}
}
</script>
call this in our custom template

If we take a look:
vendor/magento/module-product-video/Observer/ChangeTemplateObserver.php
We can see that this template will be added via Observer event. So, we need to disable this observer event in our module. And then, try to add our custom template.
Vendor/Module/etc/events.xml
<event name=""catalog_product_gallery_prepare_layout"">
<observer name=""change_template"" disabled=""true""/>
<observer name=""custom_change_template"" instance=""Vendor\Module\Observer\ChangeTemplateObserver"" />
</event>
Vendor/Module/Observer/ChangeTemplateObserver.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class ChangeTemplateObserver implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$observer->getBlock()->setTemplate('Vendor_Module::helper/gallery.phtml');
}
}

Related

Having an Issue of loader on product page in magento2.4.1

I have an issue which is loader still loading in product detail page when i migrate magento 2.4.0 to magento 2.4.1
am expecting to load product detail page properly
issue is not coming display none or hide in loader div
<div class="gallery-placeholder _block-content-loading" data-gallery-role="gallery-placeholder">
<div data-role="loader" class="loading-mask">
<div class="loader">
<img src="<?php /* #escapeNotVerified */ echo $block->getViewFileUrl('images/loader-1.gif'); ?>"
alt="<?php /* #escapeNotVerified */ echo __('Loading...') ?>">
</div>
</div>
</div>
<!--Fix for jumping content. Loader must be the same size as gallery.-->
<script>
var config = {
"width": <?php /* #escapeNotVerified */ echo $width; ?>,
"thumbheight": <?php /* #escapeNotVerified */ echo $thumbHeight ?: $thumbWidth; ?>,
"navtype": "<?php /* #escapeNotVerified */ echo $block->getVar("gallery/navtype"); ?>",
"height": <?php /* #escapeNotVerified */ echo $height; ?>
},
thumbBarHeight = 0,
loader = document.querySelectorAll('[data-gallery-role="gallery-placeholder"] [data-role="loader"]')[0];
if (config.navtype === 'horizontal') {
thumbBarHeight = config.thumbheight;
}
loader.style.paddingBottom = ( config.height / config.width * 100) + "%";
</script>

October CMS datetime picker has a max date of 2020

I am trying to add an event using proevent in October CMS and the date-picker has a default range from 2010 to 2020 and I cannot change this option. When I inspect the HTML I see the below code:
<div id="Multidate-formMultidate-multidate" class="multidate" data-control="datepicker" data-show-time="false" data-min-date="2000-01-01" data-max-date="2020-12-31" data-disposable="">
Here is an image of the date-picker:
Below is the back-end builder which somehow is displaying that the widget is unknown by saying Unknown control type:multi-date:
When I edit that to see what will happen nothing changes. I also tried setting the maxDate and minDate dates by modifying the Datepicker class in the formwidgets to set the min and max dates but nothing is happening as well. Below is the datepicker class:
<?php namespace Backend\FormWidgets;
use Carbon\Carbon;
use Backend\Classes\FormField;
use Backend\Classes\FormWidgetBase;
use System\Helpers\DateTime as DateTimeHelper;
/**
* Date picker
* Renders a date picker field.
*
* #package october\backend
* #author Alexey Bobkov, Samuel Georges
*/
class DatePicker extends FormWidgetBase
{
//
// Configurable properties
//
/**
* #var bool Display mode: datetime, date, time.
*/
public $mode = 'datetime';
/**
* #var string Provide an explicit date display format.
*/
public $format = null;
/**
* #var string the minimum/earliest date that can be selected.
* eg: 2000-01-01
*/
public $minDate = null;
/**
* #var string the maximum/latest date that can be selected.
* eg: 2020-12-31
*/
public $maxDate = null;
/**
* #var string number of years either side or array of upper/lower range
* eg: 10 or [1900,1999]
*/
public $yearRange = 50;
/**
* #var int first day of the week
* eg: 0 (Sunday), 1 (Monday), 2 (Tuesday), etc.
*/
public $firstDay = 0;
/**
* #var bool show week numbers at head of row
*/
public $showWeekNumber = false;
/**
* #var bool change datetime exactly as is in database
*/
public $ignoreTimezone = false;
//
// Object properties
//
/**
* #inheritDoc
*/
protected $defaultAlias = 'datepicker';
/**
* #inheritDoc
*/
public function init()
{
$this->fillFromConfig([
'format',
'mode',
'minDate',
'maxDate',
'yearRange',
'firstDay',
'showWeekNumber',
'ignoreTimezone',
]);
$this->mode = strtolower($this->mode);
if ($this->minDate !== null) {
$this->minDate = is_integer($this->minDate)
? Carbon::createFromTimestamp($this->minDate)
: Carbon::parse($this->minDate);
}
if ($this->maxDate !== null) {
$this->maxDate = is_integer($this->maxDate)
? Carbon::createFromTimestamp($this->maxDate)
: Carbon::parse($this->maxDate);
}
}
/**
* #inheritDoc
*/
public function render()
{
$this->prepareVars();
return $this->makePartial('datepicker');
}
/**
* Prepares the list data
*/
public function prepareVars()
{
if ($value = $this->getLoadValue()) {
$value = DateTimeHelper::makeCarbon($value, false);
$value = $value instanceof Carbon ? $value->toDateTimeString() : $value;
}
$this->vars['name'] = $this->getFieldName();
$this->vars['value'] = $value ?: '';
$this->vars['field'] = $this->formField;
$this->vars['mode'] = $this->mode;
$this->vars['minDate'] = $this->minDate;
$this->vars['maxDate'] = $this->maxDate;
$this->vars['yearRange'] = $this->yearRange;
$this->vars['firstDay'] = $this->firstDay;
$this->vars['showWeekNumber'] = $this->showWeekNumber;
$this->vars['ignoreTimezone'] = $this->ignoreTimezone;
$this->vars['format'] = $this->format;
$this->vars['formatMoment'] = $this->getDateFormatMoment();
$this->vars['formatAlias'] = $this->getDateFormatAlias();
}
/**
* #inheritDoc
*/
public function getSaveValue($value)
{
if ($this->formField->disabled || $this->formField->hidden) {
return FormField::NO_SAVE_DATA;
}
if (!strlen($value)) {
return null;
}
return $value;
}
/**
* Convert PHP format to JS format
*/
protected function getDateFormatMoment()
{
if ($this->format) {
return DateTimeHelper::momentFormat($this->format);
}
}
/*
* Display alias, used by preview mode
*/
protected function getDateFormatAlias()
{
if ($this->format) {
return null;
}
if ($this->mode == 'time') {
return 'time';
}
elseif ($this->mode == 'date') {
return 'dateLong';
}
else {
return 'dateTimeLong';
}
}
}
Below is my datepicker html page:
<?php if ($this->previewMode): ?>
<div class="form-control"><?= Backend::dateTime($value, [
'format' => $format,
'formatAlias' => $formatAlias,
'defaultValue' => $value
]) ?></div>
<div
id="<?= $this->getId() ?>"
class="field-datepicker"
data-control="datepicker"
<?php if ($formatMoment): ?>data-format="<?= $formatMoment ?>"<?php endif ?>
<?php if ($minDate): ?>data-min-date="<?= $minDate ?>"<?php endif ?>
<?php if ($maxDate): ?>data-max-date="<?= $maxDate ?>"<?php endif ?>
<?php if ($yearRange): ?>data-year-range="<?= $yearRange ?>"<?php endif ?>
<?php if ($firstDay): ?>data-first-day="<?= $firstDay ?>"<?php endif ?>
data-show-week-number="<?= $showWeekNumber ?>"
<?php if ($ignoreTimezone): ?>data-ignore-timezone<?php endif ?>
>
<?php if ($mode == 'date'): ?>
<?= $this->makePartial('picker_date') ?>
<?php elseif ($mode == 'datetime'): ?>
<div class="row">
<div class="col-md-6">
<?= $this->makePartial('picker_date') ?>
</div>
<div class="col-md-6">
<?= $this->makePartial('picker_time') ?>
</div>
</div>
<?php elseif ($mode == 'time'): ?>
<?= $this->makePartial('picker_time') ?>
<?php endif ?>
<!-- Data locker -->
<input
type="hidden"
name="<?= $field->getName() ?>"
id="<?= $field->getId() ?>"
value="<?= e($value) ?>"
data-datetime-value
/>
</div>
Is there anything I am doing wrong or i can change to fix this issue? I have been handed this project and the previous developer did not document this well.
I directly edited the view by going inside the plugin itself and removed the maxdate php code and set it to blank. The directory was plugins/radiantweb/proevents/modules/backend/formwidgets/multidate/partils/_multidate.htm. That fixed the problem and now date has no Max and I can also set directly the Max and Min dates accordingly. The view looks like below:
<div
id="<?= $this->getId() ?>"
class="multidate"
data-control="datepicker"
data-show-time="<?= $showTime ? 'true' : 'false' ?>"
data-min-date="<?= $minDate ?>"
data-max-date=""
>
<input
type="text"
class="multidate-picker form-control align-left input-small"
autocomplete="off"
data-datepicker
/>
<input
type="hidden"
id="<?= $this->getId('input') ?>"
name="<?= $name ?>[date][]"
value="<?= $value['date'][0] ?>"
data-datetime-value
/>
<?php if ($this->mode != 'date'): ?>
<input
type="text"
id="<?= $this->getId('input') ?>-sttime"
name="<?= $name ?>[sttime][]"
value="<?= $value['sttime'][0] ?>"
class="form-control align-left timepicker"
/>
<input
type="text"
id="<?= $this->getId('input') ?>-entime"
name="<?= $name ?>[entime][]"
value="<?= $value['entime'][0] ?>"
class="form-control align-left timepicker"
/>
<?php endif ?>
<i class="icon-trash-o"></i>
</div>

How to render a mail with HTML variable?

I am trying to send email by html code.
I would like to include image and data on the blade template, but can't render the view.
current code:
MailTemplate.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MailTemplate extends Mailable
{
use Queueable, SerializesModels;
public $subject = null;
public $template;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($subject, $template, $data)
{
//
$this->subject = $subject;
$this->template = $template;
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->template = '<div><img src="{{ $message->embed(public_path('/assets/images/logo.png')) }}" ></div>';
return $this->subject( $this->subject)->view('emails.EmailTemplate');
}
}
EmailTemplate.blade.php
<html>
<body>
{!! $template !!}
</body>
</html>
result
current:
<html>
<body>
<div><img src="{{ $message->embed(public_path('/assets/images/logo.png')) }}" ></div>
</body>
</html>
//==============================================
**I want:**
<html>
<body>
<div><img src="embed swiftmailfile~~~~~~" ></div>
</body>
</html>
So, how can I return the view using HTML
so that it can be passed to the variable?
You can try this:
Just pass src to view
public function build()
{
$src = $message->embed(public_path('/assets/images/logo.png'));
return $this->subject( $this->subject)->view('emails.EmailTemplate', ['src' => $src]);
}
And then , render to view
<html>
<body>
<div><img src="{{ $src }}" ></div>
</body>
</html>
You are trying to render blade inside the mailable.
Instead, create the string using concatenation
$this->template = '<div><img src="' . $message->embed(public_path('/assets/images/logo.png')) . '" ></div>';

how to show my account link in header after successfully login in magento 2.0

Homepage
I would like to show My account after login.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
// display your link here
}
----------------------from controller-------------------
$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
// display your link here
}
We can do that easily Suppose We need to show only My-Account link after sign In
We have to override the authorization.phtml file in custom theme and we can put our logic based on our requirement.
app/design/frontend/Namespace/Customtheme/Magento_Customer/templates/account/link/ authorization.phtml
After overriding this file we can put our login -
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** #var \Magento\Customer\Block\Account\AuthorizationLink $block */
$objectManagerlogin = \Magento\Framework\App\ObjectManager::getInstance();
$baseurl = $objectManagerlogin->get('Magento\Store\Model\StoreManagerInterface')->getStore(0)->getBaseUrl();
$dataPostParam = '';
if ($block->isLoggedIn()) {
$dataPostParam = sprintf(" data-post='%s'", $block->getPostParams());
}
?>
<?php if($block->isLoggedIn() && $baseurl || $block->isLoggedIn() ) : ?>
<li class="authorization-link" >
Sign Out
</li>
<li class="authorization-link custom-top-link-myaccount-mobile" >
My Account
</li>
<?php else : ?>
<li class="authorization-link" data-label="<?= $block->escapeHtmlAttr(__('or')) ?>">
<a <?= /* #noEscape */ $block->getLinkAttributes() ?><?= /* #noEscape */ $dataPostParam ?>>
<?= $block->escapeHtml($block->getLabel()) ?>
</a>
</li>
<?php endif; ?>
I hope it will work let me know if you have any issue

How to get Recently View Product For Guest User In Magento

I am Facing one problem when i want to display recent products for guest user, is there any ways to show recently view product for guest user,
Magento support Recently View Product For Registered User But for Guest User How to show Recently view products by that particular Guest...
I am waiting for your kind response,
Hope i get some reply on this.
Thanks in advance.
here is phtml
<?php if ($_products = $this->getRecentlyViewedProducts()):
$ids = '';
foreach ($_products as $_item) {
$ids .= $_item->getId() . ';';
}
?>
<div class="lftHeading">
<span
style="text-transform:capitalize;background:url(<?php echo $this->getSkinUrl('css/images/clo_left_heading_bullet2.gif') ?>) top left no-repeat;"
>recently viewed</span>
</div>
<div class="innerRgtMenu recently_viewed_block">
<table id="recently-viewed-items">
<?php $i = 0; foreach ($_products as $_item): if ($i == 3) {
continue;
} ?>
<?php $product = $_item ?>
<tr>
<td><a style="border:1px solid #DDDDDD;float:left;margin:5px;padding:5px;"
href="<?php echo $this->getProductUrl($_item, array('_nosid' => true)) ?>" class="product-image"><img
src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail')->resize(50) ?>"
width="50" alt="<?php echo $this->escapeHtml($_item->getName()) ?>"/></a></td>
<td><a style="position:relative;top:3px;font-size:11px;"
href="<?php echo $this->getProductUrl($_item, array('_nosid' => true)) ?>"><?php echo $this->escapeHtml($_item->getName()) ?></a>
</td>
</tr>
<?php $i++;
endforeach; ?>
</table>
<div style="margin: 5px 0px 5px 2px; text-align: center; width: 140px;">
<input type="button" class="button recently_viewed_btn" value="<?php echo $this->__('Email These To Me') ?> "
onClick="email_recently('<?php echo $ids; ?>')"/>
</div>
<div style="margin:5px;">
<?php echo $this->__('See All Recently Viewed') ?>
</div>
<script type="text/javascript">decorateList('recently-viewed-items');</script>
and php file
class Mage_Reports_Block_Product_Viewed extends Mage_Reports_Block_Product_Abstract
{
const XML_PATH_RECENTLY_VIEWED_COUNT = 'catalog/recently_products/viewed_count';
/**
* Viewed Product Index model name
*
* #var string
*/
protected $_indexName = 'reports/product_index_viewed';
/**
* Retrieve page size (count)
*
* #return int
*/
public function getPageSize()
{
if ($this->hasData('page_size')) {
return $this->getData('page_size');
}
return Mage::getStoreConfig(self::XML_PATH_RECENTLY_VIEWED_COUNT);
}
/**
* Added predefined ids support
*/
public function getCount()
{
$ids = $this->getProductIds();
if (!empty($ids)) {
return count($ids);
}
return parent::getCount();
}
/**
* Prepare to html
* check has viewed products
*
* #return string
*/
protected function _toHtml()
{
if (!$this->getCount()) {
return '';
}
$this->setRecentlyViewedProducts($this->getItemsCollection());
return parent::_toHtml();
}
}
if it will not work for guests - try to change last function in php file to
protected function _toHtml()
{
/* if ($this->_hasViewedProductsBefore() === false) {
return '';
} */
$this->setDisplayMinimalPrice('1');
$collection = $this->_getRecentProductsCollection();
$hasProducts = (bool)count($collection);
// if (is_null($this->_hasViewedProductsBefore())) {
// Mage::getSingleton('reports/session')->setData('viewed_products', $hasProducts);
// }
if ($hasProducts) {
$this->setRecentlyViewedProducts($collection);
}
return parent::_toHtml();
}
Block Recently Viewed Products works fine without any code modification in magento 1.6-1.9.2.2
If block is not shown you need check:
Block is properly added to page in visible container (by default block added to right sidebar)
Log is Enabled. Check System->Configuration->System->Log Option "Enable Log" = Yes
Rebuild index "Category Product" (catalog_category_product)
as far as I know - it should work fine for guests. at least it works on my site
here is how I put that on a page:
<block type="reports/product_viewed" name="reports.product.recently.viewed" template="reports/recently_viewed.phtml" />

Resources