zend currency negative sign - zend-framework

Hello i am using Zend_currency
class Currency extends Zend_View_Helper_Abstract
{
public function currency($number, $locale = 'it_IT') {
$currency = new Zend_Currency($locale);
$number = $number + 0.00;//convert to float
return $currency->toCurrency((float) $number);
}
}
in a some view .phtml file
echo $this->currency($gimme_my_money);
and this is what i get
€ 19.373,25
-€ 116,07
how can i get it to print negative numbers like
€ -116,07

Just overwrite the format option like this:
$cur = new Zend_Currency(array('format' => '¤ #,##0.00;¤ -#,##0.00'));
The trick is in the second part of the string (after the comma), I've checked it for Italian locale and the format string provided there is ¤ #,##0.00.
This is tested with ZF 1.11.7

I don't think this formatting option is built into Zend_Currency.
What you can do, is move the currency symbol to the right side:
$this->view->total = new Zend_Currency(array('value' => $total, 'position' => Zend_Currency::RIGHT));
And then your currencies will be displayed with the currency symbol on the right:
-19.373,25 €
If you want a custom formatting, with the negative sign after the symbol, (€ -116,07), you will have to write your own currency formatter or built on top of Zend_Currency

try this:
class My_View_Helper_Currency extends Zend_View_Helper_Abstract
{
/**
* Format a numeric currency value and return it as a string
*
* #param int|float $value any value that return true with is_numeric
* #param array $options additional options to pass to the currency
* constructor
* #param string $locale locale value
*
* #throws InvalidParameterException if the $value parameter is not numeric
* #return string the formatted value
*/
public function currency($value, $options = array(), $locale = null)
{
if (!is_numeric($value)) {
throw new InvalidArgumentException(
'Numeric argument expected ' . gettype($value) . ' given'
);
}
$options = array_merge($options, array('value' => $value));
$currency = new Zend_Currency($options, $locale);
return $currency->toString();
}
}

Related

Magento2 Custom Quote PDF Incorect Currency Symbol Need to add Quote currency code?

I have Created a save quote extension for one of my clients every thing is working fine
But when a customer print a pdf Quote its show the POUND symbol instead of showing the quote currency code EURO My code is given below I have tried many ways to add currency code but it is not working
public function __construct(
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\Stdlib\StringUtils $string,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Filesystem $filesystem,
Config $pdfConfig,
\Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
\Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
\Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
AddressQuoteRenderer $addressQuoteRenderer,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Framework\Pricing\Helper\Data $helper,
OrderFactory $orderFactory,
array $data = []
) {
$this->orderFactory = $orderFactory;
$this->addressQuoteRenderer = $addressQuoteRenderer;
$this->helper = $helper;
$this->_appEmulation = $appEmulation;
parent::__construct(
$paymentData,
$string,
$scopeConfig,
$filesystem,
$pdfConfig,
$pdfTotalFactory,
$pdfItemsFactory,
$localeDate,
$inlineTranslation,
$addressRenderer,
$storeManager,
$appEmulation,
$data
);
}
/**
* Return PDF document
*
* #param Collection $quotes
*
* #return \Zend_Pdf
* #throws \Magento\Framework\Exception\LocalizedException
* #throws \Zend_Pdf_Exception
*/
public function getPdf($quotes = [])
{
$this->_beforeGetPdf();
$this->_initRenderer('order');
$pdf = new \Zend_Pdf();
$this->_setPdf($pdf);
$order = $this->orderFactory->create();
foreach ($quotes as $quote) {
if ($quote->getStoreId()) {
$this->_appEmulation->startEnvironmentEmulation($quote->getStoreId());
$this->_storeManager->setCurrentStore($quote->getStoreId());
}
$page = $this->newPage();
$this->_setFontBold($page, 10);
$quote->setQuote($quote);
/* Add image */
$this->insertLogo($page, $quote->getStore());
/* Add address */
$this->insertAddress($page, $quote->getStore());
/* Add head */
$this->insertOrder($page, $quote, false);
/* Add table */
$this->_drawHeader($page);
$this->_initRenderer('default');
/* Add body */
$taxTotal = 0;
foreach ($quote->getAllItems() as $item) {
if ($item->getParentItem()) {
continue;
}
/* Keep it compatible with the invoice */
$item->setQty($item->getQty());
$item->setProductType($item->getProduct()->getTypeId());
$this->_initRenderer($item->getProduct()->getTypeId());
$item->setOrderItem($item);
$taxTotal += $item->getTaxAmount();
/* Draw item */
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
/* Add totals */
$order->setStoreId($quote->getStoreId());
$order->setSubtotal($quote->getSubtotal());
$order->setGrandTotal($quote->getSubtotal() + $taxTotal);
$order->setShippingAmount($quote->getShippingAddress()->getShippingAmount());
$order->setTaxAmount($taxTotal);
$order->setOrder($order);
$this->insertTotals($page, $order);
if ($quote->getStoreId()) {
$this->_appEmulation->stopEnvironmentEmulation();
}
Please Help and suggest to me where I am wrong I am stuck in this problem
Thanks for your help in advance

How to extend date picker viewhelper of EXT:powermail?

I need to add a custom validator to the datepicker field. By default, this field comes without any validators.
I've already made the validator settings visible in the TCA of tx_powermail_domain_model_field and added my custom validator as usual.
Now I need the attributes data-parsley-customXXX and data-parsley-error-message added to the HTML input field which is usually done via the the viewhelper in ValidationDataAttributeViewHelper.php:
https://github.com/einpraegsam/powermail/blob/develop/Classes/ViewHelpers/Validation/ValidationDataAttributeViewHelper.php#L342
https://github.com/einpraegsam/powermail/blob/develop/Classes/ViewHelpers/Validation/ValidationDataAttributeViewHelper.php#L348
This is the code I need to extend:
https://github.com/einpraegsam/powermail/blob/develop/Classes/ViewHelpers/Validation/DatepickerDataAttributeViewHelper.php#L32
I found a solution for my problem. As suggested in the comment it's possible to extend the Viewhelper:
ext_localconf.php:
$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\In2code\Powermail\ViewHelpers\Validation\DatepickerDataAttributeViewHelper::class] = [
'className' => \Vendor\MyExt\Powermail\ViewHelpers\Validation\DatepickerDataAttributeViewHelper::class
];
myext/Classes/Powermail/ViewHelpers/Validation/DatepickerDataAttributeViewHelper.php
<?php
declare(strict_types=1);
namespace Vendor\MyExt\Powermail\ViewHelpers\Validation;
use In2code\Powermail\Domain\Model\Field;
use In2code\Powermail\Utility\LocalizationUtility;
class DatepickerDataAttributeViewHelper extends \In2code\Powermail\ViewHelpers\Validation\DatepickerDataAttributeViewHelper
{
/**
* Returns Data Attribute Array Datepicker settings (FE + BE)
*
* #return array for data attributes
*/
public function render(): array
{
/** #var Field $field */
$field = $this->arguments['field'];
$additionalAttributes = $this->arguments['additionalAttributes'];
$value = $this->arguments['value'];
$additionalAttributes['data-datepicker-force'] =
$this->settings['misc']['datepicker']['forceJavaScriptDatePicker'];
$additionalAttributes['data-datepicker-settings'] = $this->getDatepickerSettings($field);
$additionalAttributes['data-datepicker-months'] = $this->getMonthNames();
$additionalAttributes['data-datepicker-days'] = $this->getDayNames();
$additionalAttributes['data-datepicker-format'] = $this->getFormat($field);
if ($value) {
$additionalAttributes['data-date-value'] = $value;
}
if ($field->getValidation() && $this->isClientValidationEnabled()) {
$value = 1;
if ($field->getValidationConfiguration()) {
$value = $field->getValidationConfiguration();
}
$additionalAttributes['data-parsley-custom' . $field->getValidation()] = $value;
$additionalAttributes['data-parsley-error-message'] =
LocalizationUtility::translate('validationerror_validation.' . $field->getValidation());
}
$this->addMandatoryAttributes($additionalAttributes, $field);
return $additionalAttributes;
}
}

TYPO3: Extend ctype textmedia with subheader

I want to add the subheader to the ctype 'textmedia' (TYPO3 9.5 & 10.4).
I followed this stackoverflow answer:
TYPO3 8 show layout selection in backend preview for textmedia
to register my Hook
typo3conf/ext/my-extension/Classes/Hooks/PageLayoutView/TextMediaCustomPreviewRenderer.php
Then I added the subheader
<?php
namespace aaa\bbb\Hooks\PageLayoutView;
use \TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface;
use \TYPO3\CMS\Backend\View\PageLayoutView;
/**
* Contains a preview rendering for the page module of CType="textmedia"
*/
class TextMediaCustomPreviewRenderer implements PageLayoutViewDrawItemHookInterface
{
/**
* Preprocesses the preview rendering of a content element of type "textmedia"
*
* #param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling parent object
* #param bool $drawItem Whether to draw the item using the default functionality
* #param string $headerContent Header content
* #param string $subheaderContent Subheader content
* #param string $itemContent Item content
* #param array $row Record row of tt_content
*/
public function preProcess(
PageLayoutView &$parentObject,
&$drawItem,
&$headerContent,
&$subheaderContent,
&$itemContent,
array &$row
) {
if ($row['CType'] === 'textmedia') {
if ($row['bodytext']) {
$itemContent .= $parentObject->linkEditContent($parentObject->renderText($row['bodytext']), $row) . '<br />';
}
if ($row['assets']) {
$itemContent .= $parentObject->linkEditContent($parentObject->getThumbCodeUnlinked($row, 'tt_content', 'assets'), $row) . '<br />';
$fileReferences = BackendUtility::resolveFileReferences('tt_content', 'assets', $row);
if (!empty($fileReferences)) {
$linkedContent = '';
foreach ($fileReferences as $fileReference) {
$description = $fileReference->getDescription();
if ($description !== null && $description !== '') {
$linkedContent .= htmlspecialchars($description) . '<br />';
}
}
$itemContent .= $parentObject->linkEditContent($linkedContent, $row);
unset($linkedContent);
}
}
$drawItem = false;
}
}
}
I get the errror:
Fatal error: Declaration of aaaa\bbb\Hooks\PageLayoutView\TextMediaCustomPreviewRenderer::preProcess(TYPO3\CMS\Backend\View\PageLayoutView &$parentObject, &$drawItem, &$headerContent, &$subheaderContent, &$itemContent, array &$row) must be compatible with TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface::preProcess(TYPO3\CMS\Backend\View\PageLayoutView &$parentObject, &$drawItem, &$headerContent, &$itemContent, array &$row) in /kunden/1111/rp-hosting/2222/333/typo3cms/projekt1/typo3conf/ext/my-sitepackage/Classes/Hooks/PageLayoutView/TextMediaCustomPreviewRenderer.php on line 23
What do I have to do to make it compatible with
TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface::preProcess(TYPO3\CMS\Backend\View\PageLayoutView &$parentObject, &$drawItem, &$headerContent, &$itemContent, array &$row)
You got it a bit wrong. You do not add the subheader in your process() arguments. In general, the arguments must be the same as the class that they extend. You can add the subheader inside the if ($row['CType'] === 'textmedia') {} by adding the value in the itemContent
$itemContent .= $row['subheader'];
Personally i would avoid to do it this way. My preferred choice is to call the StandAlone View and assign a template for preview. Is easier to maintain and program it.

"Could not analyse class: maybe not loaded or no autoloader?"

I created (my first) extension with one viewhelper.
Oops, an error occurred!
Could not analyse class:My\Mlv\ViewHelpers\Format\ReplacenewlinesViewHelper maybe not loaded or no autoloader?
In use (with news):
{namespace m=My\Mlv\ViewHelpers}
{newsItem.bodytext -> m:format.replacenewlines()}
Directory tree of extension:
typo3conf/ext/mlv
ext_emconf.php (copied from another ext)
/Classes
/ViewHelpers
/Format
ReplaceNewLinesViewHelper.php
ReplaceNewLinesViewHelper.php:
<?php
namespace My\Mlv\ViewHelpers\Format;
/**
* Replaces newlines in plain text with <br> tags.
*
* #author johndoe33
* #package Mlv
* #subpackage ViewHelpers\Format
*/
class ReplaceNewLinesViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* Replaces newlines in plain text with <br> tags.
*
* #param string $content
* #return string
*/
public function render($content = NULL) {
if (NULL === $content) {
$content = $this->renderChildren();
}
$content = str_replace( "\n", '<br>', $content );
return $content;
}
}
You need to use camel case in the view helper invocation:
{newsItem.bodytext -> m:format.replaceNewLines()}
Furthermore you may need to define an autoload definition in your ext_emconf.php if you're using TYPO3 >=7.6 (reinstall the extension after doing so):
'autoload' => array(
'psr-4' => array('My\\Mlv\\' => 'Classes')
)
For more information see: http://insight.helhum.io/post/130876393595/how-to-configure-class-loading-for-extensions-in

ZF2 - Show just one error on forms

I can't seem to get ZF2 to show just one error message for failed form validation messages.
For example, an EmailAddress validator can pass back up to 7 messages and typically shows the following if the user has made a typo:
oli.meffff' is not a valid hostname for the email address
The input appears to be a DNS hostname but cannot match TLD against known list
The input appears to be a local network name but local network names are not allowed
How can I override the error to show something a little more friendly, such as "Please enter a valid email address" instead of specifics like the above?
OK, managed to come up with a solution for this. Instead of using the same string as the error for all validator failures as Sam suggested above, I have overridden the error messages in the InputFilter for the elements and then used a custom form error view helper to show only the first message.
Here is the helper:
<?php
namespace Application\Form\View\Helper;
use Traversable;
use \Zend\Form\ElementInterface;
use \Zend\Form\Exception;
class FormElementSingleErrors extends \Zend\Form\View\Helper\FormElementErrors
{
/**
* Render validation errors for the provided $element
*
* #param ElementInterface $element
* #param array $attributes
* #throws Exception\DomainException
* #return string
*/
public function render(ElementInterface $element, array $attributes = array())
{
$messages = $element->getMessages();
if (empty($messages)) {
return '';
}
if (!is_array($messages) && !$messages instanceof Traversable) {
throw new Exception\DomainException(sprintf(
'%s expects that $element->getMessages() will return an array or Traversable; received "%s"',
__METHOD__,
(is_object($messages) ? get_class($messages) : gettype($messages))
));
}
// We only want a single message
$messages = array(current($messages));
// Prepare attributes for opening tag
$attributes = array_merge($this->attributes, $attributes);
$attributes = $this->createAttributesString($attributes);
if (!empty($attributes)) {
$attributes = ' ' . $attributes;
}
// Flatten message array
$escapeHtml = $this->getEscapeHtmlHelper();
$messagesToPrint = array();
array_walk_recursive($messages, function ($item) use (&$messagesToPrint, $escapeHtml) {
$messagesToPrint[] = $escapeHtml($item);
});
if (empty($messagesToPrint)) {
return '';
}
// Generate markup
$markup = sprintf($this->getMessageOpenFormat(), $attributes);
$markup .= implode($this->getMessageSeparatorString(), $messagesToPrint);
$markup .= $this->getMessageCloseString();
return $markup;
}
}
It's just an extension of FormElementErrors with the render function overridden to include this:
// We only want a single message
$messages = array(current($messages));
I then insert the helper into my application using the solution I posted to my issue here.