定制 c0ntax/parsley-bundle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

c0ntax/parsley-bundle

Composer 安装命令:

composer require c0ntax/parsley-bundle

包简介

A bridge between Symfony and Parsley.js

README 文档

README

A Symfony bundle to help wire Parsley.js into projects

Introduction

Wouldn't it be nice if there was a way to expose Symfony Form Constraints and Entity Annotations to the user as client side validations? Yes. Yes it would. It'd also be nice to stand on the shoulders of giants an use a well respected client side validation library to do this! To that end, I started (about 2 years before typing this sentence) to think about using Parsley.js to do the validation by converting Symfony validations into parsley data-parsley-* attributes.

So, eventually, I wrote something.

Installation

You know the score:

composer require c0ntax/parsley-bundle

And don't forget to add the following to your Kernel if you're not using Flex:

    public function registerBundles()
    {
        $bundles = [
            // ...
            new C0ntax\ParsleyBundle\C0ntaxParsleyBundle(),
            // ...
        ];
    }

Configuration

Currently, a little configuration-light, you can add the following:

c0ntax_parsley:
    enabled: true # Obviously set to false to switch it all off
    field:
        trigger: focusout # Set all fields to trigger validation on one or more jQuery events

Supported Parsley Validations

Since this library is very much alpha, I haven't had time to add all the validations in yet, so here's a list of ones that are currently supported

  • Email
  • Length
  • MaxLength
  • MinLength
  • Pattern
  • Max
  • Min
  • Required
  • Range

Specific Validaton Notes

Sometimes there is not a 1-2-1 mapping of Symfony error messages to Parsley. This is because with Parsley, you supply only one error message for the validator which is then displayed at runtime, whereas with Symfony constraints, they can pick a specific error message based on what didn't validate. Listed here are any Symfony validators where I've had to pick a specific error message that you should override using the ConstraintErrorMessage directive (so that if server based validations kick in, they will still have a message that makes sense)

  • Range

Usage

Client Side Only Validations

For reasons that I can't quite imagine, you might only want to just add client side validation. To do this, simply add a parsley constraint to your form:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'textThing',
                TextType::class,
                [
                    'parsleys' => [
                        new \C0ntax\ParsleyBundle\Parsleys\Directive\Field\Constraint\MinLength(2, 'You need more than %s chars'),
                    ],
                ]
            )
        ;
    }

The above example will add a client side validation to ensure that the data is greater than or equal to 2 characters

You can add any number of these 'parsleys'

Form and Client Side Validation

This use-case makes a little more sense. This is for where you want to explicitly add constraints to a form and have them validate on both the client and the server (just in case the user has they javascript turned off or is messing about with your forms)

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'textThing',
                TextType::class,
                [
                    'constrains' => [
                        new \Symfony\Component\Validator\Constraints\Length(['min' => 2, 'message' => 'You need more that {{ limit }} chars']),
                    ]
                ]
            )
        ;
    }

If you've used Symfony Forms before, you'll probably notice that there's nothing special here! What happens behind the scenes is that this library picks up Symfony constraints applied to form elements and converts them to their corresponding Parsley constraints.

So, as long as there is a mapping (See [Supported Parsley Validations](#Supported Parsley Validations)) for the Symfony constraint, it'll be added to the form automagically.

Entity Annotation and Client Side Validation

One of the really cool things about Symfony is that you can 'configure' the validations for an Entity within the entity itself. (Some people will tell you that this is a bad thing. They are wrong in the face.)

These are also picked up by the library, so added the 'assert' to the Entity will 'just work'(tm).

class Entity {
    /**
     * @Assert\Length(min=2)
     */
    private $textThing;
}

3rd-Party Entity Annotation and Client Side Validation

This is where I really wanted to get to with this library. Imagine the crazy world of the future where you have a nicely swagger/OASed spec for your API. You then use Swagger Codegen to produce a portable entity model. You may even tweak Codegen so that it uses Symfony Annotations for its data validation. Well, out of the box, those annotations will now be converted to Client Side Validations too! YAY! But... What swagger/OAS doesn't account for is the error message that you might want to display to the user. That's where the ErrorMessage Directive comes it. With this, you can add in your own error messages for annotations that you might not have 'control' over.

Let's assume that the Entity in the example above is out of your control. It's come in via a 3rd party library. You may want to give it a specific error message.

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'textThing',
                TextType::class,
                [
                    'parsleys' => [
                        new \C0ntax\ParsleyBundle\Parsleys\Directive\Field\ConstraintErrorMessage(\C0ntax\ParsleyBundle\Parsleys\Directive\Field\Constraint\MinLength::class, 'You need more than %s chars'),
                    ],
                ]
            )
        ;
    }

NOTE The class passed to identify where to attache the error message is the ParsleyBundle one and not the Symfony one!

Removals

There may be occassions where you want the bridge between Symfony and Parsley enabled, but specific validations 'removed' from a form element. For example, in the case of Group Sequences where there is no equivalent in Parsley. With removals, you can 'turn off' the Symfony Constraint and manually add your own custom Parsely validation. For example, say we wanted to have a Regex symfony validation on the server, but not on the client side:

  $builder->add(
    'field',
    TextType::class,
    [
      'constraints' => [new Regex(['pattern' => '/bla/]),
      'parsleys' => [new RemoveSymfonyConstraint(Regex::class)],]
    ]
  );

There is also the RemoveParsleyDirective() class that can be used to remove specific Parsley constrains. This is handy if you want to remove something that was auto-generated from a Symfony Constraint.

Rolling your own

You can add your own parsley directives by simply implementing the DirectiveInterface. The only requirement is that it passes back an array of attributes that will be injected into your form HTML.

Is that it

Yes, for now. As mentioned, this is very much 'alpha' as it only supports a small subset of the Symfony Validations, for now...

c0ntax/parsley-bundle 适用场景与选型建议

c0ntax/parsley-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.92k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2018 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「bundle」 「parsleyjs」 「parsley.js」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 c0ntax/parsley-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 c0ntax/parsley-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 c0ntax/parsley-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8.92k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2018-01-04