Symfony3 - MISD Phone Number Bundle format - php

Is it possible to set the format returned by the entity containing a phone number property when using MISD Phone-Number-Bundle? For example I have a property $phoneNumber
When I call $this->getPhoneNumber() it returns the string formatted:
Country Code: 1 National Number: ########## Country Code Source:
but I want it in the format (or similar):
1 (###) ###-####
The reason I want to change this is because in that entity I am implementing the __toString() method and want the string returned to be a combination of 2 properties one being the "nickName" and other being the phone number in this type of format or similar NickName - 1 (###) ###-#### The purpose of this is to display them in a drop down form element setup in a form type I created.

Phone number is instance of libphonenumber\PhoneNumber. This class has __toString method, which returns not formated debug information about object's properties
https://github.com/giggsey/libphonenumber-for-php/blob/master/src/PhoneNumber.php
I have formated phone number with temlate option with SonataAdminBundle:
$listMapper
->add('phoneNumber', PhoneNumberType::class, [
'template' => ':CRUD:phoneNumber_list_field.html.twig'
]);
Template :CRUD:phoneNumber_list_field.html.twig contents:
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
{% if object.phoneNumber is null %}
-
{% else %}
{{ object.phoneNumber|phone_number_format(2) }}
{% endif %}
{% endblock %}
Here argument 2 for twig filter is \libphonenumber\PhoneNumberFormat::NATIONAL
https://github.com/giggsey/libphonenumber-for-php/blob/master/src/PhoneNumberFormat.php

I think I solved my own problem... My __toString() method looks like this and seems to do what I want.
use libphonenumber\PhoneNumberUtil;
//...
public function __toString()
{
$phoneNumberUtil = PhoneNumberUtil::getInstance();
$number = $phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::NATIONAL);
return $this->nickName . " - " . $number;
}
Anyone see any issues or better ways to do this?

Related

EasyAdmin: Display integer cent-amount as Euro/Dollar (like MoneyType with `divisor`) in list view

When storing a currency value as integer (i.e. Cent), is there a way to display it in list view as Euro/Dollar?
Example: € 900 are stored in the database as 90000. EasyAdmin displays this as 90,000. What I'd like to have is 900 (or 900,00 or 900.00).
In EasyAdmin's form view, you can configure this via:
form:
fields:
- { property: 'centAmount', type: 'money', type_options: { divisor: 100, currency: 'EUR' } }
MoneyType is not supported in list view, see https://github.com/EasyCorp/EasyAdminBundle/issues/1995
Here's the workaround outlined at https://github.com/EasyCorp/EasyAdminBundle/issues/1995#issuecomment-356717049 :
Create a file /templates/easy_admin/money.html.twig with:
{% if value is null %}
{{ include(entity_config.templates.label_null) }} {# otherwise `null` will be displayed as `0,00 €` #}
{% else %}
{{ (value/100)|number_format(2, ',', '.') }} € {# you can omit the `number_format()` filter if you don’t want the cents to be shown #}
{% endif %}
See /vendor/easycorp/easyadmin-bundle/src/Resources/views/default/field_integer.html.twig for the template that EasyAdmin uses by default.
Activate your new template in easy_admin.yaml:
list:
fields:
- {property: 'centAmount', template: 'easy_admin/money.html.twig' }
Result: 900,00 €
Reference: https://symfony.com/doc/current/bundles/EasyAdminBundle/book/list-search-show-configuration.html#rendering-entity-properties-with-custom-templates
I had the same issue with the MoneyField (Easy Admin 3).
This is how I fixed it:
MoneyField::new('price','Prix')
->setCurrency('EUR')
->setCustomOption('storedAsCents', false);

Twig - Use variable key for object

I am using Twig and I have a problem.
I have a problem when I want to use a variable index for an object.
Here is my code:
{% for label, field in params.fields %}
{{ dump(data.field) }}
{% endfor %}
data is an object containing {'email': 'test#test.fr', 'name': 'John'}.
Field is an array of string containing ['email', 'name']
I can't show the value my object dynamically.
{{ dump(data.email) }} works.
How can I use dynamic indexes?
In Twig syntax, data.field is equal to $data['field'] in PHP. In other words, Twig use field as the array key name instead of taking the value of the field variable and use it as a key name.
If you want something similar to $data[$field], you can use the attribute() function:
The attribute function can be used to access a "dynamic" attribute of a variable:
Example:
{{ dump(attribute(data, field)) }}
{# or simply #}
{{ attribute(data, field) }}

Display split results in Symfony2 twig

I have a function in my Symfony controller which returns the following:
test+testString1+test2
TestController.php
public function getResultAction($fileName) {
$string1="test";
$string2="testString1";
$string3="test2";
$response = $string1."+".$string2."+".$string3;
return new Response($response);
}
In my twig I've rendered the function in my controller:
test.html.twig
{% set test %}
{{ render(controller('TestBundle:Test:getResult')) }}|split('+', 4)
{% endset %}
{{ test[0] }}
I'm using twig split filter so that I can display test, testString1 and test2 individually. But then whenever I attempt to display test[0], I receive the following error:
Impossible to access a key "0" on an object of class "Twig_Markup" that does not implement ArrayAccess interface in TestBundle:Test:test.html.twig
What's wrong with what I'm doing? I hope you could help me with this. Thanks
You miss the split filter inside the double brace as follow:
{% set test %}
{{ render(controller('TestBundle:Test:getResult')) |split('+', 4) }}
{% endset %}
Hovenever seems same problem with the set tag. From the doc:
The set tag can also be used to 'capture' chunks of text
Try with:
{%
set test=render(controller('TestBundle:Test:getResult'))|split('+', 4)
%}
Hope this help

Symfony2 translation yaml array and twig loop

I am trying to have twig convert an array from the translation file
// messages.en.yml
termsAndConditions:
title: Terms and Conditions
paragraph:
- Paragraph text...blah blah...1
- Paragraph text...blah blah...2
- Paragraph text...blah blah...3
- Paragraph text...blah blah...n
// termsandconditions.html.twig
// tried...
{% for i in range(1,termsAndConditions.paragraph|length) -%}
<p>{% trans %}termsAndConditions.paragraph. {{ i }}{% endtrans %}</p>
{%- endfor %}
// and tried...
{% for i in range(1,termsAndConditions.paragraph|length) -%}
<p>{{ 'termsAndConditions.paragraph.' ~ i ~ |trans }}</p>
{%- endfor %}
You need to use pairs of keys: values to get things to work:
// messages.en.yml
termsAndConditions:
title: Terms and Conditions
paragraph:
1: Paragraph text...blah blah...1
2: Paragraph text...blah blah...2
3: Paragraph text...blah blah...3
4: Paragraph text...blah blah...n
Also and due to the fact that you want to use a variable for your translation, access to the translation this way {{('termsAndConditions.paragraph.'~i)|trans }}.
I've hardcoded 4 instead of termsAndConditions.paragraph|length. Not really sure if you can access that from a twig template...
// termsandconditions.html.twig
{% for i in range(1,4) -%}
<p>{{('termsAndConditions.paragraph.'~i)|trans}}</p>
{%- endfor %}
It should work. Hope it helps.
UPDATE
termsAndConditions.paragraph|length makes no sense unless you've defined in the template the variable or you've injected the variable through the controller.
Solutions
Solution 1. In your controller, access the yaml and get the number of translations, then pass it to the template and that's it.
Solution 2. Create a service and inject the translator service to it. In the controller create a method that calculates the number of elements of a particular key. Injecting the translator service is better than reading the yaml directly as it caches the catalogue when it reads it.
Solution 3. Same as 2 but creating a twig filter. I'm going to go for this one as it seems kind of fun.
Solution 3
Let's start by creating the Extension:
namespace Acme\DemoBundle\Twig\Extension;
class TransLengthExtension extends \Twig_Extension
{
private $translator;
public function __construct($translator) {
$this->translator = $translator;
}
public function getFilters()
{
return array(
new \Twig_SimpleFilter('translength', array($this, 'translengthFilter')),
);
}
public function translengthFilter($id, $domain = null)
{
if (null === $domain) {
$domain = 'messages';
}
$i = 0;
$g = $this->translator->getMessages();
foreach($g["messages"] as $key => $message) {
if(substr( $key, 0, strlen($id) ) === $id ) {
$i++;
}
}
return $i;
}
public function getName()
{
return 'acme_extension';
}
}
As you can see above, it calculates the number of $id occurrences in the translation catalogue. Translator takes care of locale, loading the appropiate catalogue and so on. It also caches results which is really good in terms of performance.
Register the service injecting the translator and registering as a twig extension:
services:
acme.twig.acme_extension:
class: Acme\DemoBundle\Twig\Extension\TransLengthExtension
arguments:
- "#translator"
tags:
- { name: twig.extension }
Now, in your template:
{% set end = 'termsAndConditions.paragraph'|translength %}
{% for i in range(1,end) -%}
<p>{{('termsAndConditions.paragraph.'~i)|trans}}</p>
{%- endfor %}
Hope it helps.
There's a twig filter for this - keys
{% for keyname in yml_tree_nodes|keys %}

Symfony2 Array to string conversion, set empty value

I`am rendering a twig template in symfony2 and its possible to get a variable with value of array type but i am trying to preview the variable and this error pops:
Array to string conversion ...
So my qustion is not how to print out the array, but is it possible in twig to disable this error, so when an array comes and it cannot be outputed, to set an empty value.
In config.yml, under twig i have set
strict_variables: false
But this dose not include printing arrays.
EDIT:
In controller I pass this array to twig, for example:
'data' => array(
'description' => array(
'desc1',
'desc2'
)
);
In twig I am trying to print {{ data['description'] }} and I got the following error:
Array to string conversion ...
This is the normal error that must pop, but I need if I try to print this a no error to pop but instead I need to print nothing(empty value), same way like trying to print an non existing variable with twig set with
strict_variables: false
ANSWER:
Make a custom function:
public function getFunctions()
{
return array(
'to_string' => new \Twig_Function_Method($this, 'toString')
);
}
public function toString($data) {
if(is_array($data)) {
return '';
}
return $data;
}
And in twig template:
{{ to_string(data['description']) }}
You have two desc: desc1 and desc2, what do you want to print? If both you have to use this notation (for instance)
{{ data['description'][desc1] }} - {{ data['description'][desc2] }}
More in general:
{% for desc in data['description'] %}
{{ desc }}
{% endfor %}
EDIT
Ok, now I got it (from your comment):
{% if data['description'] is iterable %}
//echo here an empty string
{% else %}
{{ data['description'] }}
{% endif %}

Categories