symfony

Symfony 5.2.0-BETA1 has just been released with a very long list of changes. Some of the interesting features in Symfony 5.2 are the Twig helpers to get field variables, which will make life much easier for both frontend and backend developers.

Twig helpers to get field variables

The functions introduced in twig are:

  • field_name returns the name of the given field
  • field_value returns the current value of the given field
  • field_label returns the label of the given field, translated if possible
  • field_help returns the help of the given field, translated if possible
  • field_errors returns an iterator of strings for each of the errors of the given field
  • field_choices returns an iterator of choices (the structure depending on whether the field uses or doesn’t use optgroup) with translated labels if possible as keys and values as values

A quick example of usage of these functions could be the following:

<input
    name="{{ field_name(form.username) }}"
    value="{{ field_value(form.username) }}"
    placeholder="{{ field_label(form.username) }}"
    class="form-control"
/>

<select name="{{ field_name(form.country) }}" class="form-control">
    <option value="">{{ field_label(form.country) }}</option>

    {% for label, value in field_choices(form.country) %}
        <option value="{{ value }}">{{ label }}</option>
    {% endfor %}
</select>

<select name="{{ field_name(form.stockStatus) }}" class="form-control">
    <option value="">{{ field_label(form.stockStatus) }}</option>

    {% for groupLabel, groupChoices in field_choices(form.stockStatus) %}
        <optgroup label="{{ groupLabel }}">
            {% for label, value in groupChoices %}
                <option value="{{ value }}">{{ label }}</option>
            {% endfor %}
        </optgroup>
    {% endfor %}
</select>

{% for error in field_errors(form.country) %}
    <div class="text-danger mb-2">
        {{ error }}
    </div>
{% endfor %}

Retryable HTTP client

Also one of the new features in Symfony 5.2 is the Retryable HTTP Client. So if a HTTP request fail for any reason the Symfony 5.2 will retry the request automatically. To enable it add retry_failed in the http_client options :

# config/packages/framework.yaml
framework:
    # ...
    http_client:
        # ...
        retry_failed: true

Now Symfony will retry up to 3 times all failed requests with a status code included in (423, 425, 429, 500, 502, 503, 504, 507, 510) and it will wait exponentially from 1 second (first retry) to 4 seconds (third attempt).

All parameters of this feature are configurable as follows:

# config/packages/framework.yaml
framework:
    # ...
    http_client:
        # ...
        retry_failed:
            # only retry errors with these HTTP codes
            http_codes: [429, 500]
            max_retries: 2
            # waiting time between retries (in milliseconds)
            delay: 1000
            # if set, the waiting time of each retry increases by this factor
            # (e.g. first retry: 1000ms; second retry: 3 * 1000ms; etc.)
            multiplier: 3

New features in the Symfony 5.2 beta 1:

  • feature #38382 [Validator] Use comparison constraints as attributes (@derrabus)
  • feature #38369 [HttpFoundation] Expired cookies string representation consistency & tests (@iquito)
  • feature #38407 [Mime] Prefer .jpg instead of .jpeg (@fabpot)
  • feature #36479 [Notifier][WebProfilerBundle][FrameworkBundle] Add notifier section to profiler (@jschaedl)
  • feature #38395 [lock] Prevent user serializing the key when store does not support it. (@jderusse)
  • feature #38307 [Form] Implement Twig helpers to get field variables (@tgalopin)
  • feature #38177 [Security] Magic login link authentication (@weaverryan)
  • feature #38224 [HttpFoundation] Add Request::toArray() for JSON content (@Nyholm)
  • feature #38323 [Mime] Allow multiple parts with the same name in FormDataPart (@HypeMC)
  • feature #38354 [RateLimiter] add Limit::ensureAccepted() which throws RateLimitExceededException if not accepted (@kbond)
  • feature #32904 [Messenger] Added ErrorDetailsStamp (@TimoBakx)
  • feature #36152 [Messenger] dispatch event when a message is retried (@nikophil)
  • feature #38361 Can define ChatMessage transport to null (@odolbeau)
  • feature #38289 [HttpClient] provide response body to the RetryDecider (@jderusse)
  • feature #38308 [Security][RateLimiter] Added request rate limiter to prevent breadth-first attacks (@wouterj)
  • feature #38257 [RateLimiter] Add limit object on RateLimiter consume method (@Valentin, @vasilvestre)
  • feature #38309 [Validator] Constraints as php 8 Attributes (@derrabus)
  • feature #38332 [Validator] Add support for UUIDv6 in Uuid constraint (@nicolas-grekas)
  • feature #38330 [Contracts] add TranslatableInterface (@nicolas-grekas)
  • feature #38322 [Validator] Add Ulid constraint and validator (@Laurent Clouet)
  • feature #38333 [Uid] make UUIDv6 always return truly random nodes to prevent leaking the MAC of the host (@nicolas-grekas)
  • feature #38296 [lock] Provides default implementation when store does not supports the behavior (@jderusse)
  • feature #38298 [Notifier] Add Sendinblue notifier. (@ptondereau)
  • feature #38305 [PhpUnitBridge] Enable a maximum PHPUnit version to be set via SYMFON _MA _PHPUNI _VERSION (@stevegrunwell)
  • feature #38288 [DomCrawler] Add assertFormValue() in WebTestCase (@mnapoli)
  • feature #38287 [DomCrawler] Add checkbox assertions for functional tests (@mnapoli)
  • feature #36326 [Validator] Add invalid datetime message in Range validator (@przemyslaw-bogusz)
  • feature #38243 [HttpKernel] Auto-register kernel as an extension (@HypeMC)
  • feature #38277 [Mailer] Added Sendinblue bridge (@drixs6o9)
  • feature #35956 [Form] Added “html5” option to both MoneyType and PercentType (@romaricdrigon)
  • feature #38269 [String] allow passing null to string functions (@kbond)
  • feature #38176 [Config] Adding the “info” to a missing option error messages (@weaverryan)
  • feature #38167 [VarDumper] Support for ReflectionAttribute (@derrabus)
  • feature #35740 [MonologBridge] Use composition instead of inheritance in monolog bridge (@pvgnd, @mm-pvgnd)
  • feature #38182 [HttpClient] Added RetryHttpClient (@jderusse)
  • feature #38204 [Security] Added login throttling feature (@wouterj)
  • feature #38007 [Amqp] Add amqps support (@vasilvestre-OS)
  • feature #37546 [RFC] Introduce a RateLimiter component (@wouterj)
  • feature #38193 Make RetryTillSaveStore implements the SharedLockStoreInterface (@jderusse)
  • feature #37968 [Form] Add new way of mapping data using callback functions (@yceruto)
  • feature #38198 [String] allow translit rules to be given as closure (@nicolas-grekas)
  • feature #37829 [RFC][HttpKernel][Security] Allowed adding attributes on controller arguments that will be passed to argument resolvers. (@jvasseur)
  • feature #37752 [RFC][lock] Introduce Shared Lock (or Read/Write Lock) (@jderusse)
  • feature #37759 [Messenger] – Add option to confirm message delivery in Amqp connection (@scyzoryck)
  • feature #30572 [Cache] add integration with Messenger to allow computing cached values in a worker (@nicolas-grekas)
  • feature #38149 [SecurityBundle] Comma separated ips for security.acces _control (@a-menshchikov)
  • feature #38151 [Serializer] add UidNormalizer (@guillbdx, @norkunas)
  • feature #37976 [Messenger] Don’t prevent dispatch out of another bus (@ogizanagi)
  • feature #38134 [Lock] Fix wrong interface for MongoDbStore (@jderusse)
  • feature #38135 [AmazonSqsMessenger] Added the count message awareness on the transport (@raphahardt)
  • feature #38026 [HttpClient] Allow to provide additional curl options to CurlHttpClient (@pizzaminded)
  • feature #37559 [PropertyInfo] fix array types with keys (array<string, string=””>) (@digilist)</string,>
  • feature #37519 [Process] allow setting options esp. “creat _ne _console” to detach a subprocess (@andrei0x309)
  • feature #37704 [MonologBridge] Added SwitchUserTokenProcessor to log the impersonator (@IgorTimoshenko)
  • feature #37545 [DependencyInjection] Add the Required attribute (@derrabus)
  • feature #37474 [RFC][Routing] Added the Route attribute (@derrabus)
  • feature #38068 [Notifier] Register NotificationDataCollector and NotificationLoggerListener service (@jschaedl)
  • feature #32841 Create impersonatio _exi _path() and _url() functions (@dFayet)
  • feature #37706 [Validator] Debug validator command (@loic425, @fabpot)
  • feature #38052 Increase HttpBrowser::getHeaders() visibility to protected (@iansltx)
  • feature #36727 [Messenger] Add option to prevent Redis from deleting messages on rejection (@Steveb-p)
  • feature #37678 [DoctrineBridge] Ulid and Uuid as Doctrine Types (@gennadigennadigennadi)
  • feature #38037 Translate failure messages of json authentication (@Malte Schlüter)
  • feature #35890 [Cache] give control over cache prefix seed (@Tobion)
  • feature #37337 [Security] Configurable execution order for firewall listeners (@scheb)
  • feature #33850 [Serializer] fix denormalization of basic property-types in XML and CSV (@mkrauser)
  • feature #38017 [PHPUnitBridge] deprecations not disabled anymore when disabled=0 (@l-vo)
  • feature #33381 [Form] dispatch submit events for disabled forms too (@xabbuh)
  • feature #35338 Added support for using the “{{ label }}” placeholder in constraint messages (@a-menshchikov)
  • feature #34790 [Console] Remove restriction for choices to be strings (@LordZardeck, @YaFou, @ogizanagi)
  • feature #37979 [Workflow] Expose the Metadata Store in the DIC (@lyrixx)
  • feature #37371 [Translation] Add support for calling ‘trans’ with ICU formatted messages (@someonewithpc)
  • feature #37670 [Translation] Translatable objects (@natewiebe13)
  • feature #37432 [Mailer] Implement additional mailer transport options (@fritzmg)
  • feature #35893 [HttpClient][DI] Add an option to use the MockClient in functional tests (@GaryPEGEOT)
  • feature #35780 [Semaphore] Added the component (@lyrixx)
  • feature #37846 [Security] Lazily load the user during the check passport event (@wouterj)
  • feature #37934 [Mailer] Mailjet Add ability to pass custom headers to API (@tcheymol)
  • feature #37942 [Security] Renamed provider key to firewall name (@wouterj)
  • feature #37951 [FrameworkBundle] Make AbstractPhpFileCacheWarmer public (@ossinkine)
  • feature #30335 [PropertyInfo] ConstructorExtractor which has higher priority than PhpDocExtractor and ReflectionExtractor (@karser)
  • feature #37926 [lock] Lazy create table in lock PDO store (@jderusse)
  • feature #36573 [Notifier] Add Esendex bridge (@odolbeau)
  • feature #33540 [Serializer] Add special ‘’ serialization group that allows any group (@nrobinaubertin)
  • feature #37708 Allow Drupal to wrap the Symfony test listener (@alexpott)
  • feature #36211 [Serializer] Adds FormErrorNormalizer (@YaFou)
  • feature #37087 [Messenger] Add FlattenException Normalizer (@monteiro)
  • feature #37917 [Security] Pass Passport to LoginFailureEvent (@ihmels)
  • feature #37734 [HttpFoundation] add support for _FORWARDE _PREFIX header (@jeff1985)
  • feature #37897 [Mailer] Support Amazon SES ConfigurationSetName (@cvmiert)
  • feature #37915 Improve link script with rollback when using symlink (@noniagriconomie)
  • feature #37889 Toolbar toggler accessibility (@Chi-teck)
  • feature #36515 [HttpKernel] Add $kernel->getBuildDir() to separate it from the cache directory (@mnapoli)
  • feature #32133 [PropertyAccess] Allow to disable magic get & set (@ogizanagi)
  • feature #36016 [Translation] Add a pseudo localization translator (@fancyweb)
  • feature #37755 Fix #37740: Cast all Request parameter values to string (@rgeraads)
  • feature #36541 ✨ [Mailer] Add Mailjet bridge (@tcheymol)
  • feature #36940 [Notifier] add support for smsapi-notifier (@szepczynski)
  • feature #37830 [Notifier] Add LinkedIn provider (@ismail1432)
  • feature #37867 [Messenger] Add message timestamp to amqp connection (@Bartłomiej Zając)
  • feature #36925 [Security] Verifying if the password field is null (@Mbechezi Nawo)
  • feature #37847 [Serializer][Mime] Fix Mime message serialization (@fabpot)
  • feature #37338 [Console] added TableCellStyle (@khoptynskyi)
  • feature #37840 [VarDumper] Support PHPUnit –colors option (@ogizanagi)
  • feature #37138 [Notifier][Slack] Use Slack Web API chat.postMessage instead of WebHooks (@xavierbriand)
  • feature #37827 [Console] Rework the signal integration (@lyrixx)
  • feature #36131 [Mailer] Add a transport that uses php.ini settings for configuration (@l-vo)
  • feature #36596 Add cache.adapter.redi _ta _aware to use RedisCacheAwareAdapter (@l-vo)
  • feature #36582 [Messenger] Add Beanstalkd bridge (@X-Coder264)
  • feature #35967 [VarDumper] Add VA _DUMPE _FORMAT=server format (@ogizanagi)
  • feature #37815 [Workflow] Choose which Workflow events should be dispatched (@stewartmalik, @lyrixx)
  • feature #20054 [Console] Different approach on merging application definition (@ro0NL)
  • feature #36648 [Notifier] Add Mobyt bridge (@Deamon)
  • feature #37332 [FrameworkBundle] Allow to leverage autoconfiguration for DataCollectors with template (@l-vo)
  • feature #37359 [Security] Add event to inspect authenticated token before it becomes effective (@scheb)
  • feature #37539 [Workflow] Added Context to Workflow Event (@epitre)
  • feature #37683 [Console] allow multiline responses to console questions (@ramsey)
  • feature #29117 [Serializer] Add CompiledClassMetadataFactory (@fbourigault)
  • feature #37676 [Stopwatch] Add name property to the stopwatchEvent (@AhmedRaafat14)
  • feature #34704 [Messenger] Add method HandlerFailedException::getNestedExceptionOfClass (@tyx)
  • feature #37793 Revert “[DependencyInjection] Resolve parameters in tag arguments” (@rpkamp)
  • feature #37537 [HttpKernel] Provide status code in fragment handler exception (@gonzalovilaseca)
  • feature #36480 [Notifier] Add Infobip bridge (@jeremyFreeAgent)
  • feature #36496 [Notifier] added telegram options (@krasilnikovm)
  • feature #37754 [FrameworkBundle] Add days before expiration in “about” command (@noniagriconomie)
  • feature #35773 [Notifier] Change notifier recipient handling (@jschaedl)
  • feature #36488 [Notifier] Add Google Chat bridge (@GromNaN)
  • feature #36692 [HttpClient] add EventSourceHttpClient to consume Server-Sent Events (@soyuka)
  • feature #36616 [Notifier] Add Zulip notifier bridge (@phpfour)
  • feature #37747 [Notifier] Make Freemobile config more flexible (@fabpot)
  • feature #37718 [Security] class Security implements AuthorizationCheckerInterface (@SimonHeimberg)
  • feature #37732 [Console] Allow testing single command apps using CommandTester (@chalasr)
  • feature #37480 [Messenger] add redeliveredAt in RedeliveryStamp construct (@qkdreyer)
  • feature #37565 [Validator] Add Isin validator constraint (@lmasforne)
  • feature #37712 [Mailer] Prevent MessageLoggerListener from leaking in env=prod (@vudaltsov)
  • feature #33729 [Console] Add signal event (@marie)
  • feature #36352 [Validator] Added support for cascade validation on typed properties (@HeahDude)
  • feature #37243 [DependencyInjection] Resolve parameters in tag arguments (@rpkamp)
  • feature #37415 [Console] added info method to symfony style (@titospeakap, @titomiguelcosta)
  • feature #36691 [FrameworkBundle] Deprecate some public services to private (@fancyweb)
  • feature #36929 Added a FrenchInflector for the String component (@Alexandre-T)
  • feature #37620 [Security] Use NullToken while checking authorization (@wouterj)
  • feature #37711 [Router] allow to use A and z as regex start and end (@zlodes)
  • feature #37703 Update StopwatchPeriod.php (@ThomasLandauer)
  • feature #37696 [Routing] Allow inline definition of requirements and defaults for host (@julienfalque)
  • feature #37567 [PhpUnitBridge] Polyfill new phpunit 9.1 assertions (@phpfour)
  • feature #37479 [HttpFoundation] Added File::getContent() (@lyrixx)
  • feature #36178 [Mime] allow non-ASCII characters in local part of email (@dmaicher)
  • feature #30931 [Form] Improve invalid messages for form types (@hiddewie)
  • feature #37492 [ErrorHandler] Allow override of the default non-debug template (@PhilETaylor)
  • feature #37482 [HttpClient] always yield a LastChunk in AsyncResponse on destruction (@nicolas-grekas)
  • feature #36364 [HttpKernel][WebProfilerBundle] Add session profiling (@mtarld)
  • feature #37428 [Workflow] Added Function (and Twig extension) to retrieve a specific transition (@Carlos Pereira De Amorim)
  • feature #36487 [HttpClient] Add MockResponse::getRequestMethod() and getRequestUrl() to allow inspecting which request has been sent (@javespi)
  • feature #37295 Move event alias mappings to their components (@derrabus)
  • feature #37443 [HttpClient] add StreamableInterface to ease turning responses into PHP streams (@nicolas-grekas)
  • feature #36739 [TwigBundle] Deprecate the public “twig” service to private (@fancyweb)
  • feature #37272 [HttpFoundation] add HeaderUtils::parseQuery(): it does the same as pars _str() but preserves dots in variable names (@nicolas-grekas)
  • feature #37403 [Notifier] Return SentMessage from the Notifier message handler (@fabpot)
  • feature #36611 Add Notifier SentMessage (@jeremyFreeAgent)
  • feature #37357 [FrameworkBundle] allow configuring trusted proxies using semantic configuration (@nicolas-grekas)
  • feature #37373 [DI] deprecate Definition/Alias::setPrivate() (@nicolas-grekas)
  • feature #37351 [FrameworkBundle] allow enabling the HTTP cache using semantic configuration (@nicolas-grekas)
  • feature #37306 [Messenger] added support for Amazon SQS QueueUrl as DSN (@starred-gijs)
  • feature #37336 [Security] Let security factories add firewall listeners (@scheb)
  • feature #37318 [Security] Add attributes on Passport (@fabpot)
  • feature #37241 [Console] Fix Docblock for CommandTester::getExitCode (@Jean85)
  • feature #35834 [Notifier] Remove default transport property in Transports class (@jschaedl)
  • feature #37198 [FrameworkBundle] Add support for tagge _iterator/tagge _locator in unused tags util (@fabpot)
  • feature #37165 [Mime] Add DKIM support (@fabpot)
  • feature #36778 Use PHP instead of XML as the prefered service/route configuration in core (@fabpot)
  • feature #36802 [Console] Add support for true colors (@fabpot)
  • feature #36775 [DependencyInjection] Add abstrac _arg() and param() (@fabpot)
  • feature #37040 [PropertyInfo] Support using the SerializerExtractor with no group check (@GuilhemN)
  • feature #37175 [Mime] Deprecate Address::fromString() (@fabpot)
  • feature #37114 Provides a way to override cache and log folders from the ENV (@Plopix)
  • feature #36736 [FrameworkBundle][Mailer] Add a way to configure some email headers from semantic configuration (@fabpot)
  • feature #37136 [HttpClient] added support for pausing responses with a new paus _handler callable exposed as an info item (@nicolas-grekas)
  • feature #36779 [HttpClient] add AsyncDecoratorTrait to ease processing responses without breaking async (@nicolas-grekas)
  • feature #36790 Bump Doctrine DBAL to 2.10+ (@fabpot)
  • feature #36818 [Validator] deprecate the “allowEmptyString” option (@xabbuh)

You can use SymfonyInsight upgrade reports to detect the code you will need to change in your project and read our upgrade documentation to learn more. Notice that Symfony 5.2 will be released in November 2020 and its support will finish by July 2021.