具有实体信息的Symfony2小部件数据

时间:2015-11-03 14:07:03

标签: php symfony date entity symfony-forms

这个项目是由另一个开发人员启动的,现在有一个函数可以在表单中插入来自DB的数据但是在日期输入中我不能用db值更新输入..

我的数据小部件表单有问题。 我有我的小部件的代码:

                ->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'
            ))

我想在DB中使用我的实体的值,在另一个小部件中,例如name:

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

我已经收到此功能,但没有收到日期.. 我该怎么办?

/**
 * 
 * @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
    ));
}

1 个答案:

答案 0 :(得分:1)

那么,如果我在尝试更新数据库上的日期值时理解正确,那么你总是得到原始值吗?

问题是实体管理器像对象一样处理DateTime。如果您想要更新字段中的日期,则需要创建一个新的DateTime对象来更新日期。

例如,在您处理$form->isValid()的控制器中,您必须执行类似$person->setBorndate(new \DateTime([Value for the new Date]));的操作。

现在你所要做的就是获取日期的新值。在变量$request$form中,您应该能够找到它。