简体   繁体   中英

how to update an object in symfony 3?

I want to update profile infos, but after everything I have done nothing happened..

I work using ajax to send data from twig to updateAction ..

ajax :

 $(document).ready(function ()
        {
            $("#btnEnregistrer").click(function () {

                var URL = "{{path('profile_update')}}";
                var n = $('#txtNom').val();
                var nAr = $('#txtNomAr').val();
                var pre = $('#txtPrenom').val();
                var preAr = $('#txtPrenomAr').val();
                var passOld = $('#txtPassOld').val();
                var pass1 = $('#txtPassNew').val();
                var pass2 = $('#txtPassNew2').val();
                var dateN = $('#txtDateN').val();
                var ad = $('#txtAdresse').val();
                var adAr = $('#txtAdresseAr').val();
                var mob = $('#txtMobile').val();
                var fixe = $('#txtFixe').val();

                var sexe ;
                if($('#rbHomme').is(':checked'))
                    sexe="Homme";
                else
                    if($('#rbFemme').is(':checked'))
                        sexe="Femme";

                 var DATA = 'nom='+n+'&nomAr='+nAr+'&prenom='+pre+'&prenomAr='+preAr+'&sexe='+sexe+'&passOld='+passOld+'&passNew='+pass1+'&passNew2='+pass2+'&dateN='+dateN+'&adresse='+ad+'&adresseAr='+adAr+'&mobile='+mob+'&fixe='+fixe;

                $.ajax({
                 type: "POST",
                    url: URL,
                    data: DATA,
                    cache: false
                });
            });

});  

{{path('profile_update')}} is the route of updateAction :

public function updateAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        if ($request->isXmlHttpRequest()) {

        $utilisateur = $this->get('session')->get('user');

        $Vparam = $em->getRepository('ParametersBundle:Parameter')->findOneBy(['id' => $utilisateur->getVille()]);

        $utilisateur->setNom($request->get('nom'));
        $utilisateur->setNomAr($request->get('nomAr'));
        $utilisateur->setPrenom($request->get('prenom'));
        $utilisateur->setPrenomAr($request->get('prenomAr'));


        $s = $request->get('sexe');

        if($s == "Homme")
        {
            $utilisateur->setSexe("Homme");
            $utilisateur->setSexeAr("ذكر");
        }
        else
        {
            $utilisateur->setSexe("Femme");
            $utilisateur->setSexeAr("أنثى");
        }

        $utilisateur->setDateN($request->get('dateN'));
        $utilisateur->setAdresse($request->get('adresse'));
        $utilisateur->setAdresseAr($request->get('adresseAr'));


        if($request->get('passOld') !="" && $request->get('passNew') !="" && $request->get('passNew2') !="")
        {
            if($request->get('passOld') == self::getHash($utilisateur->getPassword(), $utilisateur->getSalt()))
            {
                if($request->get('passNew') == $request->get('passNew2'))
                {
                    $utilisateur->setPassword(self::getHash($request->get('passNew'), $utilisateur->getSalt()));
                }
                else
                { 
                    return $this->redirectToRoute('ens_profile');
                }
            }
            else
            {
               return $this->redirectToRoute('ens_profile');
            }
        }

        $em->flush();

        return $this->redirectToRoute('ens_profile');

    }

route.yml :

persons_connexion:
    path:     /connexion
    defaults: { _controller: PersonsBundle:Default:connexion }

persons_deconnexion:
    path:     /deconnexion
    defaults: { _controller: PersonsBundle:Default:deconnexion }

ens_profile:
    path:     /Enseignant/profile
    defaults: { _controller: PersonsBundle:Enseignant:profile }

profile_update:
    path:     /Enseignant/profile/miseajour
    defaults: { _controller: PersonsBundle:Enseignant:update }

the parameters show up in Symfony Profiler as POST Parameters .. but when I look at the table in database, I found that nothing happened .. So, what is the problem? and how can I solve it?

如果刷新不是来自您的实体经理,则需要在刷新前使用$em->persist($utilisateur)

First, you're doing something really odd... Instead of having javascript fetch your user data in the DOM, why don't you use a form and submit it directly?

You seems rather new to Symfony, so I will suggest the best method for you to learn how Symfony does things... Use the commands lines to generate entities, controllers, forms, and so on...

Here is a list of the most user commands to work with Symfony:

Create a bundle
php bin/console generate:bundle

Create an entity
php bin/console doctrine:generate:entity

Refresh all entities getters and setters within a bundle
php bin/console doctrine:generate:entities *NameBundle*

Refresh one entity getters and setters
php bin/console doctrine:generate:entities *NameBundle:Entity*

Check entities relations and and database squeleton
php bin/console d:s:v

Create entity form type
php bin/console doctrine:generate:for

Create entity controller, form type and view
php bin/console doctrine:generate:crud --with-write

Dump SQL changes into console.
php bin/console doctrine:schema:update --dump-sql
Use before updating skeleton to check if every is as you want it.

Apply SQL changes
php bin/console doctrine:schema:update --force

List all existing routes into the console.
php bin/console debug:router

Clear production cache
php bin/console cache:clear --no-warmup --env=prod

Clear developemnt cache
php bin/console cache:clear --no-warmup --env=dev'

Because it make things easier, I would suggest you to use annotation for routes instead of yml.

For your code, it's a real mess and not valid as is...
If you were using a form, this is how the basic edit action should looks like

public function editAction(Request $request, User $user) {
    $editForm=$this->createForm(UserType::class, $user);
    $editForm->handleRequest($request);
    if($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()
             ->getManager()
             ->flush();

        return $this->redirectToRoute('_edit', array('id'=>$user->getId()));
    }

    return $this->render('security/edit.html.twig', array(
        'user'=>$user,
        'edit_form'=>$editForm->createView(),
    ));
}

You code is missing the form part, and is really dangerous as is...
As a good example, you don't submit any form token, which will result in a fail when you try to update database.

I'm afraid that providing help on your code it quite impossible as you're not using symfony as you should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM