0

This project was started by another developer and now there is the function for insert in a form the data from DB but in date input i can't update input with db value..

I have a problem with a data widget form. I have this code for my widget:

                ->add('borndate', 'birthday', array(
                'widget' => 'choice',
                'attr'  => array(
                    'class' => 'form-control'
                ),
                'label' => 'user.birthday.label',
                'input' => 'string',
                'format' => 'dd.MM.yyyy',
                'data' => '1950-01-01'
            ))

I would like to have the value of my entity on DB, in another widget like for example name:

->add('name','text',array(
'label'=>'user.name.label',
'required'=>true
 ))

I receive already this function but not in date.. How can i do??


/**
 * 
 * @param Request $request
 * @param type $expert  : 0 = utente normale, 1= utente esperto ,2 ritornare errore
 * @return type
 */
public function editAction(Request $request,$expert=2) {

    $user = $this->getUser();

    if (!is_object($user) || !$user instanceof UserInterface) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    if($expert == 1 ){
        if (false === $this->get('security.authorization_checker')->isGranted('ROLE_USER_EXPERT')) {  
            throw new AccessDeniedException('This user does not have access to this section.');
        }
    }elseif($expert == 0){
        if (false === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {  
            throw new AccessDeniedException('This user does not have access to this section.');
        }
    }else{
        die("No expert mode $expert");
    }

    //Set variabili
    $em = $this->getDoctrine()->getManager();
    $dt_ec = $this->get('dt_ec');
    $tagManager = $this->get('fpn_tag.tag_manager');
    $work_plan = null;
    $formSettingsView = "";

    //Creo il form
    $form = $this->createForm(new UserType($em,$this->container), $user,array(
        'action' => $this->generateUrl('profilo_edit', array('expert' => $expert)),
        'method' => 'POST')
    );
    //Carico i tags;
    $tagManager->loadTagging($user);
    $tags = $user->getTags();
    //Ottengo la stringa dei tag per il form
    $tag_string = "";
    for ($x = 0; $x < count($tags);$x++){
        $tag_string .= $tags[$x]->getName();
        if($x < count($tags) -1)
            $tag_string .= ",";
    }

    //Ottengo le categorie ben formattate e le aggiungo al form
    $arr = $dt_ec->getWellFormattedCategory($user->getCategories());
    $form->add('well_cat','choice',array('choices'=>$arr['well_cat'],'multiple'=>true ,'data'=>$arr['data']))
         ->add('tags','text',array('required'=>false,
            'label'=>'user.expert.specialization.label',
            'data' => $tag_string,
            "attr"=>array("data-provide"=>"typeahead","class"=>"typeahead tt-input")
                                ));

    if($expert == 0){

        //Rimuovo i dati dell'utente esperto perché non mi servono per un utente normale
        $request_form =$request->request->get('dt_ec_user');            
        unset($request_form['user_expert']);
        $request->request->set('dt_ec_user',$request_form);
        $request_form =$request->request->get('dt_ec_user');
    }else{
        //Controllo i piani di lavoro
        $user_schedule = $em->getRepository("DtAppointmentBundle:UserSchedule")->findOneBy( array("id_user" => $user->getId()) );
        if(null !== $user_schedule)
            $work_plan = $user_schedule->getWorkPlan();
        else
            $work_plan = "";
        //Ottengo i settaggi del profilo e creo il form per esso (e trasformo già in view)
        $user_profile_setting = $em->getRepository("DtEcBundle:UserProfileSetting")->findOneBy( array("id_user" => $user->getId()) );
        $formSettings = $this->createForm(new UserProfileSettingType(), $user_profile_setting,array(
            'action' => $this->generateUrl('profilo_edit', array('expert' => $expert)),
            'method' => 'POST')
        );
        $formSettings->add("submit",'button',array( 'attr'=>array( 'class'=>'save' ) )) ;
        $formSettingsView = $formSettings->createView();
    }
    $form->handleRequest($request);

    if ($form->isValid()) {
        if($expert == 0){
            //Tolgo l'utente esperto e persisto l'entità
            $user->setUserExpert(NULL);
            $em->persist($user);
            $em->flush();
        }else{
            $well_cat = $user->getWellCat();
            //Salvo le categorie
            $user_categories = $user->getCategories();
            $ids_user_categories = array();

            foreach ($user_categories as $category) {
                $ids_user_categories[] = $category->getId();
            }
            foreach ($well_cat as $category) {
                $cat = $em->getRepository("DtEcBundle:Category")->findOneBy(array("id"=>$category));
                if( count($cat) > 0  ){
                    if(!in_array($cat->getId(), $ids_user_categories) ) 
                        $user->addCategory($cat);
                } 
            }

            //Salvo i tags
            $user->setTags(NULL);
            $array= $request->request->get('dt_ec_user');
            $tags = $array["tags"];
            $tagNames =$tagManager->splitTagNames($tags);
            //Subito dopo persisto l'utente esperto
            $em->persist($user->getUserExpert());
            //Ora posso persistere i tag
            $tags = $tagManager->loadOrCreateTags($tagNames);
            $tagManager->addTags($tags,$user);
            $tagManager->saveTagging($user);
            // e in fine l'utente
            $em->persist($user);
            $em->flush();
        }
        return $this->redirectToRoute('profilo_index');
    }



    return $this->render('DtEcBundle:Profilo:edit.html.twig', array(
        'form'                   => $form->createView(),
        'is_expert_registration' => $expert,
        'workplan'               =>$work_plan,
        'form_setting'           =>$formSettingsView
    ));
}
Luca M
  • 371
  • 3
  • 18

1 Answers1

1

So, if I understand correctly when trying to update the date value on the database you always get the original value?

The problem is that the entity manager handles DateTime like an object. If you ever want to update the date in a field you will need to create a new DateTime object to update the date.

For example, in your controller where you handle the $form->isValid() you would have to do something like this $person->setBorndate(new \DateTime([Value for the new Date]));.

Now all you have to do is get is the new value for date. Either in the variable $request or $form you should be able to find it.

Dayany
  • 86
  • 4
  • I do not think you understand.. I have a date field when i can edit my user-profile, in all field like name, surname i receive the data value update but the date field remains '1950-01-01'... So i would this field update too.. How can i do?? @Dayany – Luca M Nov 03 '15 at 14:32
  • Hopefully, I understood right this time and I answered your question – Dayany Nov 03 '15 at 14:47
  • Thanks... but i don't know how i put this line.. I edit with the code of my controller, Can you help me???? @Dayany – Luca M Nov 03 '15 at 15:31
  • Before the `$em->flush();` Retrieve the value of the new through the `$_POST` and add something like `$user->setBorndate(new \DateTime([$postVariableWithValue)]);`. Something that can be easier but I am not sure that will work is to just put `$user->setBorndate(new \DateTime([$user->getBorndate())]);` I know it seems redundant but the problem comes when UPDATING to the database not when populating the variable itself. So the `$user->getBorndate()` should have whatever value you just try to update with. – Dayany Nov 03 '15 at 15:35
  • Found something better than my answer. [Ocramius's Answer To DateTime not updating](http://stackoverflow.com/questions/15486402/doctrine2-orm-does-not-save-changes-to-a-datetime-field) – Dayany Nov 03 '15 at 15:45
  • '$prova = $user->getBorndate(); var_dump($prova->format('d-m-Y')); $em->setBorndate(new \DateTime($prova->format('Y-m-d'))); $em->flush();' I tried in this way like you say me but nothing.. I can't see my actualy date in a form... @Dayany – Luca M Nov 03 '15 at 16:16
  • I tried with $user too but nothing.. $user->setBorndate(new \DateTime($prova->format('Y-m-d'))); @Dayany – Luca M Nov 03 '15 at 16:27
  • Then retrieve it from $_POST – Dayany Nov 03 '15 at 16:40
  • Yes if i do a var_dump() of my variable with $_POST i receive the value but when i put this in $em->setBorndate(new \DateTime($prova->format('Y-m-d'))); – Luca M Nov 04 '15 at 08:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/94207/discussion-between-luca-m-and-dayany). – Luca M Nov 04 '15 at 13:23