IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

remplir un champs de formulaire avec la personne connectée


Sujet :

Symfony PHP

  1. #1
    Membre du Club
    Inscrit en
    Décembre 2010
    Messages
    182
    Détails du profil
    Informations forums :
    Inscription : Décembre 2010
    Messages : 182
    Points : 53
    Points
    53
    Par défaut remplir un champs de formulaire avec la personne connectée
    Bonjour

    je veux que le champs de formulaire affiche la personne connectée lors de chargement de la page

    j'ai fais tout d'abord un simple formulaire avec un champs author dans ce cas je dois écrire a chaque fois le nom de personne connectée j'ai essayé {{ app.user.username}} mais pas de résultat comment je peux le faire pour que le champs prends la valeur {{ app.user.username}}

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     <tr>
                <th>{{ form_label(commentForm.author) }}</th>
                <td>
                {{ form_errors(commentForm.author) }}
                {{ form_widget(commentForm.author,{'attr': {'class': 'author_field'}}) }}
                    </td>
                </tr>
                <tr>
    merci

  2. #2
    Membre actif
    Profil pro
    Inscrit en
    Novembre 2010
    Messages
    168
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2010
    Messages : 168
    Points : 219
    Points
    219
    Par défaut
    Dans ton controller fais un truc du genre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    $comment = new Comment();
     
    $user = $this->get('security.context')->getToken()->getUser();
    $comment->setAuthor($user);
    ....

  3. #3
    Membre du Club
    Inscrit en
    Décembre 2010
    Messages
    182
    Détails du profil
    Informations forums :
    Inscription : Décembre 2010
    Messages : 182
    Points : 53
    Points
    53
    Par défaut
    merci donc j'ai supprimé le champs author de comment.twig.html
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <table class="table" style="width: 100%">
     
     
     
        <tfoot>
            <tr>
                <td colspan="2">
                    <input class="ajaxAdd" type="submit" value="Valider" />
                </td>
                <td  style="display: none" colspan="1">
                    <input   type="reset" class="reset" value="Clear" />
                </td>
            </tr>
        </tfoot>
        <tbody>
     
                <tr>
                    <th>{{ form_label(commentForm.content) }}</th>
                    <td>
                {{ form_errors(commentForm.content) }}
                {{ form_widget(commentForm.content) }}
                        </td>
                    </tr>
     
     
                    </tbody>
                </table>
        {{ form_rest(commentForm) }}
    et dans le contrôleur j'ai modifié la méthode
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    public function commentAddAction($article_id) {
            $request = $this->getRequest();
            if ($request->isXmlHttpRequest()) {
                $em = $this->getDoctrine()->getManager();
                $article = $em->getRepository('MDCommenBundle:Article')->find($article_id);
                if ($article === null) {
                    return new Response("false");
                }
                $comment = new Comment();
                $user = $this->get('security.context')->getToken()->getUser();
    $comment->setAuthor($user);
                $comment->setArticle($article);
                $commentForm = $this->createForm(new \MD\CommeBundle\Form\CommentType(),$comment);
                $commentForm->handleRequest($request);
                if ($commentForm->isValid()) {
                    $em->persist($comment);
                    $em->flush();
                    return $this->render('MDCommeBundle:Article:ajax.comment.html.twig', array(
                                'comment' => $comment,
                    ));
                }
            }
            throw $this->createNotFoundException("Page does not exist");
        }
    mais ça m'arche pas

  4. #4
    Membre actif
    Profil pro
    Inscrit en
    Novembre 2010
    Messages
    168
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2010
    Messages : 168
    Points : 219
    Points
    219
    Par défaut
    Oui,
    mais tu fais quoi ?
    Ton action commentAddAction n'est pas destiné a afficher le formulaire ?
    Et tu "submit" un form ou tu lances une XmlHttpRequest ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     if ($request->isXmlHttpRequest()) {
    Et dans ton entité Comment, t'as bien une relation avec l'entité User ?

  5. #5
    Membre du Club
    Inscrit en
    Décembre 2010
    Messages
    182
    Détails du profil
    Informations forums :
    Inscription : Décembre 2010
    Messages : 182
    Points : 53
    Points
    53
    Par défaut
    alors voila le problème exactement lorsque je clique sur un article une page show s'affiche dans le quel je peux ajouter des commentaires

    show.html.twig
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <div class="col-md-17">
     
    <h1>{{article.title}}</h1>
     
    <br/>
    <p>{{ article.content }}</p>
    <div id="comment_content">
        <h2>Comments :</h2><br/>
        {% for comment in article.comments %}
        <table class="table">
     
            <TR > 
     
          <TD style="width: 80%">{{ comment.author }} <br>{{ comment.content }}</TD>
     
       </TR>
     
     
        </table>
        {%else%}
        no comments right now
        {% endfor %}
    </div>
     
    <br/>
    <form novalidate="" class="ajaxAdd" >
     {% include 'MDCommenBundle:Article:_comment.form.html.twig' with {'commentForm':commentForm} %}
    </form>
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <script type="text/javascript">
            $(document).ready(function() {
                $('form.ajaxAdd').submit(function() {
                    var url = "{{path('commen_create',{'article_id':article.id})}}";
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: $(this).serialize(), // serializes the form's elements.
                        success: function(comment)
                        {
                            $("div#comment_content").append(comment); // show response from the php script.
                            clearForm();
                        }
                    }).fail(function() {
                        alert('Some required  missing');
                    });
                    return false;
                });
     
            });
            function clearForm() {
                $(':input', 'form.ajaxAdd')
                        .not(':button, :submit, :reset, :hidden')
                        .val('')
                        .removeAttr('checked')
                        .removeAttr('selected');
            }
            </script>
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    <?php
     
    namespace MD\CommenBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
    /**
     * MD\CommenBundle\Entity\Comment
     *
     * @ORM\Table()
     * @ORM\Entity()
     * 
     */
    class Comment
    {
     
        /**
         * @var integer $id
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @var string $author
         *
         * @ORM\Column(name="author", type="string", length=255)
         * @Assert\NotNull()
         * @Assert\Length(
         *      min = "2",
         *      max = "50",
         *      minMessage = " Author must have at least {{ limit }} caracters ",
         *      maxMessage = "Author can have a maximum of {{ limit }} caracters"
         * )
         *  */
        private $author;
     
        /**
         * @var string $content
         *
         * @ORM\Column(name="content", type="text")
         */
        private $content;
     
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId() {
            return $this->id;
        }
     
        /**
         * Set author
         *
         * @param string $author
         * @return Coments
         */
        public function setAuthor($author) {
            $this->author = $author;
     
            return $this;
        }
     
        /**
         * Get author
         *
         * @return string 
         */
        public function getAuthor() {
            return $this->author;
        }
     
        /**
         * Set content
         *
         * @param string $content
         * @return Coments
         */
        public function setContent($content) {
            $this->content = $content;
     
            return $this;
        }
     
     
        /**
         * Get content
         *
         * @return string 
         */
        public function getContent() {
            return $this->content;
        }
     
     
        /**
         * @ORM\ManyToOne(targetEntity="Article", inversedBy="comments")
         * @ORM\JoinColumn(name="article_id", referencedColumnName="id",onDelete="CASCADE")
         * @return integer
         */
        private $article;
     
        public function setArticle(\MD\CommenBundle\Entity\Article $article) {
            $this->article = $article;
        }
     
        public function getArticle() {
            return $this->article;
        }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    commen_create:
        pattern: /addComment/{article_id}
        defaults: { _controller: MDCommBundle:Article:commentAdd }

  6. #6
    Membre actif
    Profil pro
    Inscrit en
    Novembre 2010
    Messages
    168
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2010
    Messages : 168
    Points : 219
    Points
    219
    Par défaut
    Je vais être méchant !

    Pourquoi tu ne regardes pas par exemple ce qu'est $user !
    $...->setAuthor demande une string et tu lui balances un objet User ....


    Si tu passes par un render(controller()) autant lui passer l'objet Article et laisser l'action de ce dernier faire le travail de creation du formulaire.

Discussions similaires

  1. Remplir un champ de formulaire avec la date d'aujourd'hui en js
    Par xzoursx dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 28/03/2015, 09h51
  2. Remplir un champ de formulaire avec du js
    Par pracede2005 dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 21/01/2015, 21h35
  3. [MySQL] remplir un champ de formulaire avec plusieurs possibilités
    Par ledisciple dans le forum PHP & Base de données
    Réponses: 0
    Dernier message: 20/01/2011, 17h04
  4. Remplir 3 champs textes différents avec une liste déroulante
    Par azorol dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 20/12/2005, 00h04
  5. Champ de formulaire avec opérations
    Par Marmouz dans le forum Access
    Réponses: 8
    Dernier message: 30/11/2005, 15h00

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo