2

i have a little problem with my regex. Everything seems correct and i checked in Symfony docs, but on my page i dont have the message while the $url is wrong ..

(it just shows me an error page like the field is empty if i enter the wrong $url and if it is the good one, no error)

whould someone have an idea about ? :)

Thank you

<?php

namespace App\Entity;


use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="media_video")
 * @ORM\Entity(repositoryClass="App\Repository\MediaVideoRepository")
 * @ORM\HasLifecycleCallbacks // Permet d’utiliser des événements
 */
class MediaVideo
{
    /********** ATTRIBUTS **********/

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $type;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $identif;



    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\tricks", inversedBy="mediaVideos")
     * @ORM\JoinColumn(nullable=false)
     */
    private $trick;

    /**
     * @Assert\Regex(
     *     pattern="#^(http|https)://(www.youtube.com|www.dailymotion.com)/#",
     *     match=true,
     *     message="L'url doit correspondre à l'url d'une vidéo Youtube ou DailyMotion"
     * )
     */
    private $url;

This is the error that appears =>

An exception has been thrown during the rendering of a template ("Parameter "id" for route "deleteVideo" must match "[^/]++" ("" given) to generate a corresponding URL.").

Thats the template =>

{% extends 'base.html.twig' %}


{% block content %}

    <section class="page-section about-heading">
        <div class="container">
            <div class="row" id="box-search">
                <div class="thumbnail text-center">
                    <img class="img-fluid rounded about-heading-img mb-3 mb-lg-0"  src="{{ asset('img/sky.jpg') }}" alt="trick">
                    <div class="caption">
                        <h2 class="section-heading mb-4">
                            <span class="section-heading-upper">Edite ta figure</span>
                            <span class=" titre section-heading-lower">{{ trick.name }}</span>
                        </h2>
                    </div>
                </div>
            </div>
            <div class="about-heading-content">
                <div class="row">
                    <div class="col-xl-9 col-lg-10 mx-auto">
                        <div class="bg-faded rounded p-5">
                            <span class="col-lg-3 badge badge-success edit-span">Créé le 10/10/2018</span>
                            {# AFFICHAGE DES IMAGES #}
                            <div class="album">
                                <div class="container">
                                    {% if trick.hasImages  %}
                                    <h1 class="marge">Images</h1>
                                    <div class="row jumbotron">
                                    {% for image in trick.images %}
                                        <div class="petite col-lg-4 media center-block ">
                                            <div class="row marge">
                                                <div class="  col-12">
                                                    <a href="{{ asset('uploads/'~image.path) }}" data-lightbox="roadtrip">
                                                    <img src="{{ asset('uploads/'~image.path) }}"/></a>
                                                </div>
                                                <div class="col-12">
                                                    <a href="{{ path('deleteImage', {'id': image.id}) }}" >
                                                        <button class="btn btn-danger btn-block" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                                            Supprimer
                                                        </button>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    {% endfor %}
                                    </div>
                                    {% endif %}
                                    {# AFFICHAGE DES VIDEOS #}
                                    {% if trick.hasVideos  %}
                                    <h1 class="marge">Videos</h1>
                                    <div class="row jumbotron">
                                        {% for video in trick.mediaVideos %}
                                        <div class="col-lg-4 media marge">
                                            <div class="row">
                                                <div class="col-12">
                                                        {{ video.video|raw }}
                                                </div>
                                                <div class="col-12" id="videos">
                                                    <a href="{{ path('deleteVideo', {'id': video.id}) }}" class="btn btn-danger btn-block delete-item" data-id="{{ video.id }}">
                                                    Supprimer</a>
                                                </div>
                                            </div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                </div>

                                {# FORMULAIRE #}
                                <div class="well">
                                {{ form_start(form, {'attr': {'class': 'form-horizontal'}}) }}
                                    <div class="form-group">
                                        <div class="row">
                                            {# Génération du label. #}
                                            {{ form_label(form.description, "Description :", {'label_attr': {'class': 'col-sm-2 control-label'}}) }}
                                            {# Affichage des erreurs pour ce champ précis. #}
                                            {{ form_errors(form.description) }}
                                            <div class="col-sm-10">
                                            {# Génération de l'input. #}
                                            {{ form_widget(form.description, {'attr': {'class': 'form-control rows="4" cols="50"'}}) }}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="row">
                                            {# Génération du label. #}
                                            {{ form_label(form.groupe, "Groupe :", {'label_attr': {'class': 'col-sm-2 control-label'}}) }}
                                            {# Affichage des erreurs pour ce champ précis. #}
                                            {{ form_errors(form.groupe) }}
                                            <div class="col-sm-10">
                                            {# Génération de l'input. #}
                                            {{ form_widget(form.groupe, {'attr': {'class': 'form-control'}}) }}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="ajout-media">
                                        {# VIDEO #}

                                        <ul class="list_ul" id="video-fields-list"
                                            data-prototype="{{ form_widget(form.mediaVideos.vars.prototype)|e }}"
                                            data-widget-tags="{{ '<li></li>'|e }}">
                                            {% for video in form.mediaVideos%}
                                                <div>
                                                    {{ form_errors(video) }}
                                                </div>
                                            {% endfor %}
                                        </ul>
                                        <div class="col-sm-7">
                                        <a href="#"
                                           class=" btn btn-info add-another-collection-widget_video"
                                           data-list="#video-fields-list">Ajouter une video</a>
                                        </div>
                                        {# IMAGE #}
                                        <ul class="list_ul" id="image-fields-list"
                                            data-prototype="{{ form_widget(form.images.vars.prototype)|e }}"
                                            data-widget-tags="{{ '<li></li>'|e }}">
                                        </ul>
                                        <div class=" col-sm-7">
                                            <a href="#"
                                               class="image_btn btn btn-info add-another-collection-widget"
                                               data-list="#image-fields-list">Ajouter une image
                                            </a><br>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-12 envoyer">
                                            {{ form_widget(form.save, { 'label': 'Mettre à jour', 'attr': {'class': 'btn btn-signup  my-2 my-sm-0 pull-right'}}) }}
                                        </div>
                                        <a href="{{ path('delete', {'id': trick.id}) }}"><button type="button" class=" col-sm-12 btn btn-danger supprimer" >
                                          Supprimer
                                        </button></a>
                                    </div>
                                   <div class="hidden">
                                       {{ form_rest(form) }}
                                   </div>
                                {{ form_end(form) }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
{% endblock %}
{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript" src="{{ asset('vendor/js/add_media.js') }}"></script>
{% endblock %}

That's the controller =>

  /**
     * @Route("/editer/{id}", name="edit")
     * @param $id
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function edit( $id, Request $request)
    {
        // $trick stock toutes les figures récupérées par la variable $trickRepo
        $trick = $this->trickRepo->find($id);

        if (null === $trick) {
            throw new NotFoundHttpException("Cette page n'existe pas");}


        $form = $this->createForm(TricksEditType::class, $trick);
        $form->handleRequest($request);

        /*
        *   isSubmitted() vérifie si le formulaire est soumis
        *  isValide valide les données saisies
        */
        if ($form->isSubmitted() && $form->isValid()) {

            /*
            * (persist) Demande au gestionnaire d'entités(entityManager) de suivre les modifications apportées à l'objet
            * (flush) Pousse les modifications des objets d’entités qu’il suit dans la base de données en une seule transaction
            */
            $this->entityManager->persist($trick);
            $this->entityManager->flush();

            $request->getSession()->getFlashBag()->add('notice', 'Annonce bien modifiée.');

            return $this->redirectToRoute('show', array('id' => $trick->getId()));
        }
        return $this->render('trick/edit.html.twig', array(
            'trick' => $trick,
            'form'   => $form->createView(),
        ));
    }

0

2 Answers 2

1

Use this one instead:

^(http|https):\/\/(www\.youtube\.com|www\.dailymotion\.com)\/?
Sign up to request clarification or add additional context in comments.

6 Comments

yes it is like this : Doctrine\DBAL\Exception\NotNullConstraintViolationException: An exception occurred while executing 'INSERT INTO media_video (type, identif, trick_id) VALUES (?, ?, ?)' with params [null, null, 95]: SQLSTATE[23000]: Integrity constraint violation: 1048 Le champ 'type' ne peut être vide (null)
As the error says, The 'type' field can not be empty (null). The error has nothing to do with 'url' field
Thank you very much for the idea, i added required = false in my Form :)
And i added , the assert in the form too
like this = 'constraints' => [ new Regex('^(http|https):\/\/(www\.youtube\.com|www\.dailymotion\.com)\/?') ]
|
0

Like most other validation constraints the Regex constraint will also only be evaluated when the value is not empty (this is to allow a constraint to be optional and being only applied when a value is actually present). In your case your database schema seems to require that a URL is given. To handle this during validation of your object you should also add the NotBlank constraint:

// ...

class MediaVideo
{
    // ...

    /**
     * @Assert\NotBlank()
     * @Assert\Regex(
     *     pattern="#^(http|https)://(www.youtube.com|www.dailymotion.com)/#",
     *     match=true,
     *     message="L'url doit correspondre à l'url d'une vidéo Youtube ou DailyMotion"
     * )
     */
    private $url;

    // ...
}

3 Comments

the error is the same, but thank you very mich for try and the time that you waisted for
What is the exact error that you get now? Can you also show how your form handling in the controller looks like?
The error is not related to the url property, but is caused by the path('deleteVideo', {'id': video.id}) part of your template. It seems that the form is used to create new videos. When the form is not valid, this video will tried to be rendered in the template, but since it does not have an id at this stage causes the template rendering to break.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.