2

I've migrated Magento 1 to Magento 2, In the Magento 1 site on product listing page I've truncated the length of the short description.

e.g- echo Mage::helper('core/string')->truncate($short_description, '120');

I require the same thing in Magento 2 way, how can I achieve it?

Note:- I don't want to use simple core PHP to restrict length.

1
  • Check my below solution and let me know if working or not. Commented Jul 19, 2018 at 11:37

2 Answers 2

1

You can truncate string in Magento-2 by below code

Inject below parameters to your class __construct

protected $filter;

public function __construct(
        \Magento\Framework\Filter\FilterManager $filter
    ) {
        $this->filter = $filter;
   }

You can truncate string by below code

$this->filter->truncate($short_description, ['length' => 120]));
6
  • Sorry! I was engaged on some other urgent works so looked on this late.thanks for the reply.i tried but it didn't work in the class "Magento\Catalog\Block\Product\ListProduct". Commented Jul 24, 2018 at 12:27
  • any error or not working? Commented Jul 24, 2018 at 12:29
  • Getting errors, so i tried helper way & it works. Commented Jul 24, 2018 at 12:42
  • I've used cache:clean. when we need to delete generated? i used the same using helper but it works without deleting generated why? Commented Jul 24, 2018 at 12:48
  • keep in mind if you add any constructor argument, It required delete generated folder. if you clean just cache it will be not working and throw error. Commented Jul 24, 2018 at 12:49
0

After spending two hours approx I've done this by using a helper.

Helper Path:-

Magento\Catalog\Helper\Product\ProductList.php(I'll be overriding later so you can also).

Added Following code:-

    // Extends class \Magento\Framework\App\Helper\AbstractHelper

class ProductList extends \Magento\Framework\App\Helper\AbstractHelper
     public function __construct(
            \Magento\Framework\Filter\FilterManager $filter
          ) {
              $this->filter = $filter;
            }
                // My custom method
         public function truncateString($value, $length = 80)
            {
                return $this->filter->truncate($value, ['length' => $length]) ;
            }

// In the template file, just called custom method:-

 $this->helper('Magento\Catalog\Helper\Product\ProductList')->truncateString($short_description,120); 

Note:- I tried to do it using block but due to the time restriction i'm not able will try later. if anyone do the same via block then please share here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.