Giter Club home page Giter Club logo

phone-number-bundle's Introduction

PhoneNumberBundle

This package has been abandoned in favour of odolbeau/phone-number-bundle.

Build Status Total Downloads Downloads per month Latest stable version License

This bundle integrates Google's libphonenumber into your Symfony2-Symfony4 application through the giggsey/libphonenumber-for-php port.

Installation

  1. Use Composer to download the PhoneNumberBundle:
        $ composer require misd/phone-number-bundle
  1. Register the bundle in your application:
        // app/AppKernel.php

        public function registerBundles()
        {
            $bundles = array(
                // ...
                new Misd\PhoneNumberBundle\MisdPhoneNumberBundle()
            );
        }

Usage

Services

The following services are available:

Service ID libphonenumber version
libphonenumber\PhoneNumberUtil libphonenumber.phone_number_util
libphonenumber\geocoding\PhoneNumberOfflineGeocoder libphonenumber.phone_number_offline_geocoder >=5.8.8
libphonenumber\ShortNumberInfo libphonenumber.short_number_info >=5.8
libphonenumber\PhoneNumberToCarrierMapper libphonenumber.phone_number_to_carrier_mapper >=5.8.8
libphonenumber\PhoneNumberToTimeZonesMapper libphonenumber.phone_number_to_time_zones_mapper >=5.8.8

So to parse a string into a libphonenumber\PhoneNumber object:

    $phoneNumber = $container->get('libphonenumber.phone_number_util')->parse($string, PhoneNumberUtil::UNKNOWN_REGION);

Doctrine mapping

Requires doctrine/doctrine-bundle.

To persist libphonenumber\PhoneNumber objects, add the Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType mapping to your application's config:

    // app/config.yml

    doctrine:
        dbal:
            types:
                phone_number: Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType

You can then use the phone_number mapping:

    /**
     * @ORM\Column(type="phone_number")
     */
    private $phoneNumber;

This creates a varchar(35) column with a Doctrine mapping comment.

Note that if you're putting the phone_number type on an already-existing schema the current values must be converted to the libphonenumber\PhoneNumberFormat::E164 format.

Templating

Twig

phone_number_format

The phone_number_format filter can be used to format a phone number object. A libphonenumber\PhoneNumberFormat constant can be passed as argument to specify in which format the number should be printed.

For example, to format an object called myPhoneNumber in the libphonenumber\PhoneNumberFormat::NATIONAL format:

    {{ myPhoneNumber|phone_number_format('NATIONAL') }}

By default phone numbers are formatted in the libphonenumber\PhoneNumberFormat::INTERNATIONAL format.

phone_number_of_type

The phone_number_of_type test can be used to check a phone number against a type: A libphonenumber\PhoneNumberType constant name must be passed to specify to which type a number has to match.

For example, to check if an object called myPhoneNumber is a libphonenumber\PhoneNumberType::MOBILE type:

    {% if myPhoneNumber is phone_number_of_type('MOBILE') }} %} ... {% endif %}

PHP template

format()

The format() method in the phone_number_helper takes two arguments: a libphonenumber\PhoneNumber object and an optional libphonenumber\PhoneNumberFormat constant name or value.

For example, to format $myPhoneNumber in the libphonenumber\PhoneNumberFormat::NATIONAL format, either use:

    <?php echo $view['phone_number_helper']->format($myPhoneNumber, 'NATIONAL') ?>

or:

    <?php echo $view['phone_number_helper']->format($myPhoneNumber, \libphonenumber\PhoneNumberFormat::NATIONAL) ?>

By default phone numbers are formatted in the libphonenumber\PhoneNumberFormat::INTERNATIONAL format.

isType()

The isType() method in the phone_number_helper takes two arguments: a libphonenumber\PhoneNumber object and an optional libphonenumber\PhoneNumberType constant name or value.

For example, to check if $myPhoneNumberis alibphonenumber\PhoneNumberType::MOBILE` type:

    <?php if $view['phone_number_helper']->isType($myPhoneNumber, 'MOBILE'): ?>
    ...
    <?php endif; ?>

or:

    <?php if $view['phone_number_helper']->isType($myPhoneNumber, \libphonenumber\PhoneNumberType::MOBILE): ?>
    ...
    <?php endif; ?>

Serializing libphonenumber\PhoneNumber objects

Requires jms/serializer-bundle.

Instances of libphonenumber\PhoneNumber are automatically serialized in the E.164 format.

Phone numbers can be deserialized from an international format by setting the type to libphonenumber\PhoneNumber. For example:

    use JMS\Serializer\Annotation\Type;

    /**
     * @Type("libphonenumber\PhoneNumber")
     */
    private $phoneNumber;

Using libphonenumber\PhoneNumber objects in forms

You can use the PhoneNumberType (phone_number for Symfony 2.7) form type to create phone number fields. There are two widgets available.

Single text field

A single text field allows the user to type in the complete phone number. When an international prefix is not entered, the number is assumed to be part of the set default_region. For example:

    use libphonenumber\PhoneNumberFormat;
    use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
    use Symfony\Component\Form\FormBuilderInterface;

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('phone_number', PhoneNumberType::class, array('default_region' => 'GB', 'format' => PhoneNumberFormat::NATIONAL));
    }

By default the default_region and format options are PhoneNumberUtil::UNKNOWN_REGION and PhoneNumberFormat::INTERNATIONAL respectively.

Country choice fields

The phone number can be split into a country choice and phone number text fields. This allows the user to choose the relevant country (from a customisable list) and type in the phone number without international dialling.

    use libphonenumber\PhoneNumberFormat;
    use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
    use Symfony\Component\Form\FormBuilderInterface;

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('phone_number', PhoneNumberType::class, array('widget' => PhoneNumberType::WIDGET_COUNTRY_CHOICE, 'country_choices' => array('GB', 'JE', 'FR', 'US'), 'preferred_country_choices' => array('GB', 'JE')));
    }

This produces the preferred choices of 'Jersey' and 'United Kingdom', and regular choices of 'France' and 'United States'.

By default the country_choices is empty, which means all countries are included, as is preferred_country_choices. The option country_placeholder can be specified to create a placeholder option on above the whole list.

Validating phone numbers

You can use the Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber constraint to make sure that either a libphonenumber\PhoneNumber object or a plain string is a valid phone number. For example:

    use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber as AssertPhoneNumber;

    /**
     * @AssertPhoneNumber
     */
    private $phoneNumber;

You can set the default region through the defaultRegion property:

    use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber as AssertPhoneNumber;

    /**
     * @AssertPhoneNumber(defaultRegion="GB")
     */
    private $phoneNumber;

By default any valid phone number will be accepted. You can restrict the type through the type property, recognised values:

  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::ANY (default)
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::FIXED_LINE
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::MOBILE
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::PAGER
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::PERSONAL_NUMBER
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::PREMIUM_RATE
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::SHARED_COST
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::TOLL_FREE
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::UAN
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::VOIP
  • Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber::VOICEMAIL

(Note that libphonenumber cannot always distinguish between mobile and fixed-line numbers (eg in the USA), in which case it will be accepted.)

    /**
     * @AssertPhoneNumber(type="mobile")
     */
    private $mobilePhoneNumber;

Translations

The bundle contains translations for the form field and validation constraints.

In cases where a language uses multiple terms for mobile phones, the generic language locale will use the term 'mobile', while country-specific locales will use the relevant term. So in English, for example, en uses 'mobile', en_US uses 'cell' and en_SG uses 'handphone'.

If your language doesn't yet have translations, feel free to open a pull request to add them in!

phone-number-bundle's People

Contributors

boekkooi avatar c0ntax avatar fdelapena avatar garak avatar giggsey avatar giovkanata avatar ickbinhier avatar jasperstafleu avatar jean-beru avatar jongotlin avatar justeleblanc avatar kosdfol avatar niketpathak avatar ossinkine avatar pculka avatar pdawczak avatar peshi avatar polc avatar pulzarraider avatar rh389 avatar robhogan avatar rvanlaak avatar seriy avatar shakaran avatar ste93cry avatar thewilkybarkid avatar toooni avatar winzou avatar xabbuh avatar zhil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phone-number-bundle's Issues

how to set defaultRegion in an Entity

I defined a Doctrine entity called Phone like so:

<?php
namespace ACC\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber as AssertPhoneNumber;
use libphonenumber\PhoneNumber as PNum;

/**
 * Phone
 *
 * @ORM\Table(name="phone")
 * @ORM\Entity
 */
class Phone
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
    * @var integer
    *
    * @ORM\Column(name="phonenumber", type="phone_number")
    * @AssertPhoneNumber(defaultRegion="CA")
    */
    private $phonenumber;    

    /**
    * @var string
    *
    * @ORM\Column(name="locale", type="string", length=2)
    */
    private $locale = 'CA';

      //the usual getters and setters
}

The SQL Create table:

CREATE TABLE `phone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `phonenumber` varchar(35) COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:phone_number)',
  `locale` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci$$

(an aside, but note that the phonenumber field is varchar(35) and not varchar(20) as stated in the docs)

In the controller I do this:

    $em = $this->getDoctrine()->getRepository('ACC\MainBundle\Entity\Phone');
    $phone = $em->find(1);

which throws a NumberParseException: Missing or invalid default region.

How can I identify to Doctrine that it should use my locale property as the region?

Making Phone Number field Optional

I am trying to get the fields to be optional instead of mandatory (most people won't fill both Landline and Mobile). However, even if I set the field to be optional, the form isValid() fails because of this field.

Kindly assist in figuring out how to make it optional. I don't have any of my own validator configured. So it is basically what Symfony validators are working with.

My class field variable below. As you can see, nullable=true so database can accept null value.

 * @var \libphonenumber\PhoneNumber
 *
 * @Type("libphonenumber\PhoneNumber")
 *
 * @ORM\Column(name="landline_no", type="phone_number", nullable=true)
 */
private $landlineNo; 

My Type for the field. I have set required => false.

->add('landlineNo', PhoneNumberType::class, array( 'widget' => PhoneNumberType::WIDGET_COUNTRY_CHOICE, 'preferred_country_choices' => array("GB", "US", "AU"), 'label' => "Landline No", 'required' => false, ) )

But when I submit the form, it is returning back as invalid because of the missing value.

Would appreciate the guidance to get this done right.

Add country restriction to constraint

Related to #13, it might be useful to add an option to the validation constraint to restrict number to one or more countries (eg if you have a UK-specific application, you probably don't want non-UK numbers).

It might be difficult to have a useful translatable message however (see #9).

Phone to String is not available?

So I would like to know if there's a way to transform PhoneNumber to string with prefix, for example

+34600000000 for Spain, because when using a PhoneNumber inside query it's not returning anything because MySQL has +34600000000 and PhoneNumber doesn't add the +34 prefix in any way (not even getNationalNumber) so it is useless...

I know that you can instance the utils, parse/transform etc but man, there should be just a one liner way to do it inside the class itself.

Something like this inside PhoneNumber class

public function getStringNumber() { return sprintf("+%d%d", $this->getCountryCode(), $this->getNationalNumber()); }

So easy...

placeholder on phone number

I'm displaying form without labels, but using placeholder has labels.

I have been trying to search and use different method to put placeholder for phone, but it puts it on div element and not the input. How can I put placeholder on input field of phone number?

use buildViolation

Hello,
currently you are using addViolation in your https://github.com/misd-service-development/phone-number-bundle/blob/master/Validator/Constraints/PhoneNumberValidator.php#L98
So there is no option to set an atPath where to display the message! you not even use addViolationAt

However, addViolation and addViolationAt are deprecated from symfony 2.5 and will be removed at 3.0. You should use buildViolation() instead.
http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#creating-the-validator-itself

You can do something like this:
in Validator/Constraints/PhoneNumber.php

class PhoneNumber extends Constraint
{
    public $message = 'This value is not a valid {{ type }} number.';
    public $type = 'phone';
    public $defaultRegion = PhoneNumberUtil::UNKNOWN_REGION;
    public $atPath = 'anyProperty';
}

in Validator/Constraints/PhoneNumberValidator.php
instead of

private function addViolation($value, Constraint $constraint)
    {
        $this->context->addViolation(
            $constraint->message,
            array('{{ type }}' => $constraint->type, '{{ value }}' => $value)
        );
    }

you can use the new function

private function addViolation($value, Constraint $constraint)
    {
        $this->context->buildViolation($constraint->message)
            ->atPath($constraint->atPath)
            ->setParameter('{{ type }}', $constraint->type)
            ->addViolation();
    }

or instead of directly accessing the $constraint properties (e.g. $constraint->atPath) use
a function (saw now that you already did it with getter functions)

public function getAtPath()

With this changes you are save for the future (symfony 3.0+) and you give an option to set the atPath property, so the user can determine where the violation message should appear.

Include PhoneNumberFormat static allowing to format as INTERNATIONAL, yet display without prefix

That would make many lives tons easier for sites which use different CSS styling of prefix element which, dependently on certain site's target audience, is pretty much static.

For example, a simple Twitter Bootstrap form prefix/prepend usage for Nigerian market:

            <div class="field col-xs-12 col-sm-12 col-md-4">
                <div class="form-group{% if form.phone.vars.errors|length %} has-error{% endif %}">
                    {{ form_label(form.phone) }}
                    <div class="input-group">
                        <span class="input-group-addon">&#43;234</span>
                        {{ form_widget(form.phone) }}
                    </div>
                    {{ form_errors(form.phone) }}
                </div>
            </div>

This will give +234 +234 %phone-number% unless uber hacking is applied (which then destroys the data format)...

Improve (de)serialization

Currently the PhoneNumberHandler only handles E.164 format numbers; the format and default region could be added as options similar to DateTime<'format', 'zone'> (so the annotation would look something like @Type("libphonenumber\PhoneNumber<'NATIONAL', 'GB'>")) for flexibility (especially when consuming external feeds).

Unable to transform value for property path phone_number

Entity entries:
/**
* @Orm\Column(type="phone_number", nullable=true)
* @AssertPhoneNumber(defaultRegion="US", message="Please specify a valid phone number")
*/
private $phoneNumber;

DBAL Mapping:
doctrine:
dbal:
types:
phone_number: Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType

Form:
->add('phoneNumber', PhoneNumberType::class, array('default_region' => 'US', 'format' => PhoneNumberFormat::NATIONAL, 'required' => false))

But still I get the below error, Can someone let me know how to resolve this? I wrote few lines of code to convert the string to PhoneNumber obj then the form loads fine but my question is do we need to explicitly convert this? Is this not to be handled automatically?
if($user->getphoneNumber()!="") {
$util = $this->container->get('libphonenumber.phone_number_util');
$phoneNUmber = $util->parse($user->getphoneNumber(), "US"); $user->setphoneNumber($phoneNUmber);
} else {
$phoneNUmber = new \libphonenumber\PhoneNumber;
$user->setphoneNumber($phoneNUmber);
}

Uncaught PHP Exception Symfony\Component\Form\Exception\TransformationFailedException: "Unable to transform value for property path "phone_number": Expected a \libphonenumber\PhoneNumber." at /var/www/example/webapp/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php line 1149 {"exception":"[object] (Symfony\Component\Form\Exception\TransformationFailedException(code: 0): Unable to transform value for property path "phone_number": Expected a \libphonenumber\PhoneNumber. at /var/www/example/webapp/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php:1149, Symfony\Component\Form\Exception\TransformationFailedException(code: 0): Expected a \libphonenumber\PhoneNumber. at /var/www/example/webapp/vendor/misd/phone-number-bundle/Form/DataTransformer/PhoneNumberToStringTransformer.php:62)

PhoneNumber constraints in validation.yml

Hello,

I was trying to use phone number validation in a bundle validation.yml file, but got an exception says default options is not configured.

There is any way to validate entity with yaml file or I'm doing something wrong?

Exception Message

No default option is configured for constraint Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber

validation.yml

UserBundle\Entity\User:
    constraints:
        - Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber: PhoneNumber
    properties:
        name:
            - NotBlank: ~
        surname:
            - NotBlank: ~
        mobile:
            - PhoneNumber: ~

Add form type guesser

It would be useful to implement Symfony\Component\Form\FormTypeGuesserInterface to guess the tel form type.

It could check:

  • The @var doc (based on the example code)
  • Validation constraint (see Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser)
  • Doctrine mapping (see Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser)
  • Serializer config (haven't seen an example of this before)

Status of this bundle

Hello,

What is the current status of this bundle ? Is it still maintained ?
No commit since May and many PR are opened...

Add in missing services

Services like the geocoder need to be added to the bundle. Care needs to be taken for any that have appeared in more recent versions.

[Travis CI] Check multiple Symfony versions

The Travis CI should always check against multiple Symfony versions. Currently it only check against the newest version.

I think we should check it against Symfony 2.3 (LTS) and Symfony 2.8 (LTS). Symfony 3.0 could be added once the compatibility of Symfony 3 has been merged into the master branch.

FOSUserBunder with my own user_provider get ErrorException: Catchable Fatal Error: Argument 1 passed to libphonenumber\PhoneNumberUtil::format()

Hello

My name is Andrey. I use FOSUserBundle for my project.
I need users to login via phone_number ONLY.
So I use you bundle. Its great!
add provider in security.yml

providers:
        fos_userbundle:
            #id: fos_user.user_provider.username
            id: equils_user.user_provider.phone

add in services.yml

    equils_user.user_provider.phone:
        class: Equils\UserBundle\Security\PhoneUserProvider
        arguments: [@equils_user.user_manager.default]

    equils_user.user_manager.default:
        class: Equils\UserBundle\Doctrine\UserManager
        arguments:
            - @security.encoder_factory
            - @fos_user.util.username_canonicalizer
            - @fos_user.util.email_canonicalizer
            - @fos_user.entity_manager
            - %fos_user.model.user.class%

add classes

/**
 */
namespace Equils\UserBundle\Security;
use FOS\UserBundle\Security\UserProvider as BaseProvider;
use FOS\UserBundle\Model\UserManagerInterface;

class PhoneUserProvider extends BaseProvider
{
    /**
     * @var UserManagerInterface
     */
    protected $userManager;

    /**
     * Constructor.
     *
     * @param UserManagerInterface $userManager
     */
    public function __construct(UserManagerInterface $userManager)
    {
        $this->userManager = $userManager;
    }

    /**
     * Finds a user by phone number.
     *
     * @param string $phone
     *
     * @return UserInterface|null
     */
    protected function findUser($phone)
    {
        return $this->userManager->findUserByPhoneNumber($phone);
    }

}
/**
 */
namespace Equils\UserBundle\Doctrine;

use Doctrine\Common\Persistence\ObjectManager;
use FOS\UserBundle\Util\CanonicalizerInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use FOS\UserBundle\Doctrine\UserManager as BaseManager;

class UserManager extends BaseManager
{
    public function __construct(EncoderFactoryInterface $encoderFactory, CanonicalizerInterface $usernameCanonicalizer, CanonicalizerInterface $emailCanonicalizer, ObjectManager $om, $class)
    {
        parent::__construct($encoderFactory, $usernameCanonicalizer, $emailCanonicalizer, $om, $class);
    }

    /**
     * Finds a user by phone number
     *
     * @param string $phone
     *
     * @return UserInterface
     */
    public function findUserByPhoneNumber($phone)
    {
        return $this->findUserBy(array('phone_number' => $phone));
    }
}

and so on... but
when I try to log in I get error:

22 10

I found place in code where I guess error happen and fix that...

/**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (null === $value) {
            return null;
        }

        $phoneNumber = PhoneNumberUtil::getInstance()->parse($value, 'RU');
        $util = PhoneNumberUtil::getInstance();

        return $util->format($phoneNumber, PhoneNumberFormat::E164);
    }

Please tell me, what do you think about this fix. Is it valid ?

Wrong documentation, missing argument

Your documentation example for parsing a string is wrong.

Warning: Missing argument 2 for libphonenumber\PhoneNumberUtil::parse()

Because the function parse() needs a second argument ($defaultRegion):
public function parse($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null, $keepRawInput = false)

Accessing phone number string from Controller

I see you have details on how to access and output a phone number in a template file, but when I have the column from the Entity that is a "phone_number" type, I cannot see how to convert this to a string within the controller. It just returns a phone_number object which is not displayable.

I need to do this to return json output from the controller.

Thanks for your help!

Validator with french numbers

It seems that the validator refuse to validate mobile phones that begin with 07 in france.
In france, mobile phones begin with 06 or 07.

Dynamically pass "defaultRegion"

Hi,
In my use case, users can be from many country and each country may have its own phone number format. How I can pass "defaultRegion" dynamically based upon user's country?

Add translations

The form/validation messages should have translations, currently only English is available.

get error Could not convert database value "" to Doctrine Type phone_number

Hi thank for this bundle, how is going to be userfull for me to!
i have just install lake description, and i get : Could not convert database value "" to Doctrine Type phone_number

here my config :

doctrine:
    dbal:
        types:
            phone_number: Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType

in builder form :

    use libphonenumber\PhoneNumberFormat;
...........................

                    ->add ( 'phoneNumber', 'tel', array(
                        'default_region' => 'GB',
                        'format' => PhoneNumberFormat::NATIONAL)
                    )

twig :

...........
    {{ form(edit_form) }}
...........

entity :

       /**
         * @ORM\Column(type="phone_number")
         */
        private $phoneNumber;

can you help me ?

thank

Not getting detection for all mobile nos

I am not getting it from the documentation written, if i want to detect is it's a valid phone no (landline + mobile). I don't care if it belongs to any county. I just need to detect if it's a no or not as simple as that.

Please clarify the doubt.

short country name

Hi,

I couldn't find it in the docs: How do I display the country code and identification in the drop down when choosing a widget 'country_choice' ?

I know this could be changed in the Misd\PhoneNumberBundle\Form\Type\PhoneNumberType at line 68 as follow:

    foreach (Intl::getRegionBundle()->getCountryNames() as $region => $name) {
        if (false === isset($countries[$region])) {
            continue;
        }
        $countryChoices[sprintf('%s (+%s)', $region, $countries[$region])] = $region;
    }

But I was wondering if there isn't a cleaner way to do this

~thoroc

Missing or invalid default region.

I'm using the FOSUserBundle with a Doctrine User entity.
I added the "phone_number" type.

/**
 * @var string
 *
 * @ORM\Column(type="phone_number")
 * @AssertPhoneNumber(defaultRegion="US")
 */
protected $telephone;

But now every time I try to load the user from the UserManager or regular Doctrine repositories, I get the error "Missing or invalid default region."

This seems to be caused from re-hydrating the objects and converting the data from the DB. In Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType::convertToPHPValue :

/**
 * {@inheritdoc}
 */
public function convertToPHPValue($value, AbstractPlatform $platform)
{
    if (null === $value) {
        return null;
    }

    $util = PhoneNumberUtil::getInstance();

    return $util->parse($value, PhoneNumberUtil::UNKNOWN_REGION);
}

I see no way to set the Region? Doesn't there need to be a way to set that as libphonenumber::PhoneNumberUtil won't work with region set to PhoneNumberUtil::UNKNOWN_REGION?

Maybe the region should be a bundle configuration?

I'm sure I'm missing something simple and any help would be appreciated. Thanks!

libphonenumber\PhoneNumberUtil::format() must be an instance of libphonenumber\PhoneNumber, string given

I'm using the PhoneNumberBundle with Doctrine, I have this field:

/**
 * @ORM\Column(type="phone_number", nullable=true)
 * @Serializer\Type("libphonenumber\PhoneNumber")
 * @AssertPhoneNumber(defaultRegion="US")
 */
protected $phoneNumber;

The validation is ok, but when I persist the object I get this error:

Catchable Fatal Error: Argument 1 passed to libphonenumber\PhoneNumberUtil::format() must be an instance of libphonenumber\PhoneNumber, string given, called in /miproject/vendor/misd/phone-number-bundle/Misd/PhoneNumberBundle/Doctrine/DBAL/Types/PhoneNumberType.php on line 58 and defined in /myproject/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/PhoneNumberUtil.php line 992

I debugged the code and I saw that in class PhoneNumberType, the function convertToDatabaseValue receives the string and not the libphonenumber\PhoneNumber object...

Should I parse and create the libphonenumber\PhoneNumber before persist the object?

Thanks!

Mixing Field type and Validation

Is it possible to mix field type declaration and phone number validation? Basically I want to only accept US mobile phone numbers, but the following code doesn't seem to be working.

/**
     * @var PhoneNumber
     *
     * @Assert\NotBlank(groups={"registration", "profile"})
     * @AssertPhoneNumber(
     *     defaultRegion="US",
     *     type=AssertPhoneNumber::MOBILE,
     *     message="This is not a valid mobile phone number.",
     *     groups={"registration", "profile"}
     * )
     * @ORM\Column(name="phone_number", type="phone_number", unique=true)
     * @Serializer\Expose()
     * @Serializer\Type("libphonenumber\PhoneNumber")
     */
    private $phoneNumber;

Even though the user enters a valid phone number I would like to reject it if it's not a mobile phone number. Can I do this by simply adding annotations like above?

Question: Can the bundle support multiple regions?

It seems I'm forced to set a default region in order to get phone numbers to persist.
However, if I set my form builder element with a default_region => 'US', format=> PhoneNumberFormat::INTERNATIONAL I'm not allowed to enter and save international phone numbers. e.g. it'll take: 800-800-2775 (US phone number) but not: 0451 029 226 (an Australian phone number). So is it expected that I have to fall into one region with this bundle or have I missed something? My specific application needs to accept phone numbers from around the globe.

Thanks!

National format in a form field breaks international numbers

If I have a field like:

$form->add('with', 'tel', array('constraints' => new PhoneNumber(), 'default_region' => 'GB', 'format' => PhoneNumberFormat::NATIONAL));

If I enter +1 650-253-0000 it's accepted; it's then formatted nationally, turning it into (650) 253-0000. Submitting the form again then leads to a This value is not a valid phone number and the value is then 6502530000 as it's not recognised as a GB number.

To resolve this, if format is set to national it will need to format numbers that aren't from the default region differently (so it would need something like an international_format setting).

Deprecate the Twig phone_number_format function and replace it with a filter

Currently the Twig extension provides a function called phone_number_format that serves the purpose of formatting a given phone number. I think that a filter would be more appropriate in this case. There are already many bundles that provides filters to format numbers and dates, so why should this bundle provide a function? I prepared a PR with unit tests to handle this issue without breaking BC. I even refactored a bit the code of the classes by removing some namespace imports were not needed

Use libphonenumber\PhoneNumber object in DQL

Have a repository method that takes the PhoneNumber object as an argument. I have my dql query written as:

    ->createQuery(
        'SELECT p, m FROM AppBundle:Phone p JOIN p.member m WHERE p.phoneNumber = :phone AND m.allowFind = TRUE'
    )
    ->setParameter("phone", $phone)
    ->getOneOrNullResult();

However when it generates the query it puts 'Object(libphonenumber\PhoneNumber)' where I would expect it to actually put the Phone Number in the format +1##########

When I use the default findOneByPhoneNumber($phone) it generates the query fine.

Can't Use PhoneNumberType::WIDGET_COUNTRY_CHOICE without hitting an error (Array to string conversion)

I camr across this bundle and I am trying to integrate it into my application. I have followed all the notations and the database was created as mentioned in the documentation.

My environment is PHP 7 and Symfony 3.

However, I encountered a couple of issues.

  1. "tel" form type doesn't work. Instead I had to use PhoneNumberType::class as the form type in my form setup.
  2. Country choice fields doesn't work. I copied the same line and tried to use it and I get this error.
    An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in form_div_layout.html.twig at line 13.

This line works.
->add('landlineNo', PhoneNumberType::class, array('default_region' => 'GB', 'format' => PhoneNumberFormat::NATIONAL))

This line doesn't.
->add('landlineNo', PhoneNumberType::class, array('widget' => PhoneNumberType::WIDGET_COUNTRY_CHOICE, 'country_choices' => array('GB', 'JE', 'FR', 'US'), 'preferred_country_choices' => array('GB', 'JE')))

Is there any suggestion on how to resolve this so I can use the Country dropdown? Or do I need to append the country code manually?

Would really appreciate a fix since I am trying to get this form done and phone number is the only one pending.

Doctrine phone_number type varchar length incorrect

Based on a valid phone number in the US, I can provide a number like 123-456-7890 ext 1234567. It seems the phone number is invalid when there's an 8 digit extension. However, the point is this value is stored as +11234567890 ext. 1234567 which is 25 characters. The current doctrine type is set to 20.

Removing Phone Number with Widget

If I have a Country Widget in my form, how can I remove phone number from my profile?
There is no option to have an empty value in the country field(!), therefore it is impossible to properly remove the phone number from the entity

Exception with null value in database

Hi,
I have a phone_number in my entity, which can be null :

 * @ORM\Column (type="phone_number", nullable=true)

But when I try to display a user whose phnone_number is null, I get the following exception :

NumberParseException: The string supplied did not seem to be a phone number.
at PhoneNumberUtil ->parseHelper ('', 'ZZ', false, true, object(PhoneNumber))
in /vendor/giggsey/libphonenumber-for-php/src/libphonenumber/PhoneNumberUtil.php at line 2618
at PhoneNumberUtil ->parse ('', 'ZZ')

Is there a way to allow for null values and avoid this issue ?

Thanks
Regards

Extension and content of file validators.fi.yml don't match

The content format is xliff and the extension is yaml, wich trigger this exception:


[Symfony\Component\Translation\Exception\InvalidResourceException]                                                                
  Error parsing YAML, invalid file "<rootPath>/vendor/misd/phone-number-bundle/Resources/translations/validators.fi.yml"  

related with merged pull request #93

procto/libphonenumber-for-php vs giggsey/libphonenumber-for-php

Hello:

Very good bundle. Thanks for your work.

The home page for project libphonenumber at code.google.com lists giggsey/libphonenumber-php and not procto/libphonenumber which is what this bundle is based one.

Is there any specific reason why procto/libphonenumber-for-php was chosen? Both repositories are a fork from the same same repository.

Undefined class constant 'WIDGET_COUNTRY_CHOICE'

I can't find 'WIDGET_COUNTRY_CHOICE' at all. following error I get.

Error: Undefined class constant 'WIDGET_COUNTRY_CHOICE'

use libphonenumber\PhoneNumberFormat;
use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
use Symfony\Component\Form\FormBuilderInterface;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('phone_number', 'tel', array('widget' => PhoneNumberType::WIDGET_COUNTRY_CHOICE, 'country_choices' => array('GB', 'JE', 'FR', 'US'), 'preferred_country_choices' => array('GB', 'JE')));
}

Fix doctrine phpdoc auto generation

Edit: Known issue in Doctrine2: doctrine/orm#4911

I have this code in my entity:

/**
 * @var PhoneNumber
 *
 * @ORM\Column(type="phone_number")
 */
private $number;

Currently doctrine generates this:

/**
 * Set number
 *
 * @param phone_number $number
 *
 * @return ContactPhone
 */
public function setNumber($number)
{
    $this->number = $number;

    return $this;
}

/**
 * Get number
 *
 * @return phone_number
 */
public function getNumber()
{
    return $this->number;
}

As you can see the phpdoc is wrong. It should not be phone_number.
Instead \libphonenumber\PhoneNumber would be right.

Does anybody have an idea how to fix that? It also works with datetime => \DateTime. Why and how?

validation on the form type

I have asset validation on the entity type as following

@AssertPhoneNumber(type="mobile", defaultRegion="GB", groups={"settingsProfile"})

This works prefectly.

Now I want to override this validation on different form. I want to validate phone and mobile, if its coming from uniqe form.

So I wanted to add validation on the form, but not sure how I can do with this plugin.

Break up the README

The README file is quite long now, which isn't great for reading (refs #42). The usage part should be broken up into separate files.

Open request for translations

#15 fixed problems with translations of the validation constraint. All we need now is translation files! Please take a look at the list of currently available ones, and if you're able to speak a language that isn't available (or know of a localisation difference), please open a pull request to add it in. ๐Ÿ˜ƒ

I'm planning to release v1.1.0 in a few weeks which will include the change, and it would be nice to have as many translations as possible by then.

Symfony2 v2.6 supporting ?

will be bundle supporting Symfony2 v2.6 ?

./bin/console doctrine:schema:update --force

showing me

[Doctrine\Common\Annotations\AnnotationException]
  [Semantical Error] The annotation "@Symfony\Component\Validator\Constraints\PhoneNumber" in property Doma\Bundle\CompanyBundle\Entity\Company::$phoneNumber does not exist, or could not be auto-loaded.

FIX phone_number mapping

So when using mapping like in the docs, and telling my field to be a phone_number type, I get this error

Expected AppBundle\Entity\phone_number got \libphonenumber\PhoneNumber

when calling $entity->setPhone($phone);

this is how I create my $phone

$phone = $container->get('libphonenumber.phone_number_util')->parse($string, PhoneNumberUtil::UNKNOWN_REGION);

for example.

Needless to say that this constant warnings makes all my code "non ok" at the eyes of the IDE, and sometimes is a mess because you forgot about this bug...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.