在symfony中将新表单字段保存在数据库中

时间:2014-01-30 11:12:28

标签: php symfony symfony1 symfony-2.1 orangehrm

我今天开始使用symfony。我必须在表单中添加一个新字段并将其保存在表格中(橙色hrm自定义)。 我创建了一个新的表单字段评论。我也改变了目标表。当我提交表单时,评论不会保存。我想我必须在symfony中进行一些配置,以便在数据库中保存 comment 。请帮我解决问题

编辑:我的代码是

    public function execute($request) { 

        $this->form = $this->getForm();

        print "<pre>";
    print_r($this->form->getValues());
    print "</pre>";

    //Output shows [comment] => dddd

    $leaveEntitlement = $this->getLeaveEntitlement($this->form->getValues());

    print "<pre>";
    print_r($leaveEntitlement);
    print "</pre>";



    LeaveEntitlement Object
    (
    [_node:protected] => 
    [_id:protected] => Array
    (
        [id] => 1
    )

    [_data:protected] => Array
    (
        [id] => 1
        [emp_number] => 3
        [no_of_days] => 384
        [days_used] => 0.0000
        [leave_type_id] => 2
        [from_date] => 2014-01-01 00:00:00
        [to_date] => 2014-01-31 00:00:00

        [credited_date] => 2014-01-30 00:00:00
        [note] => 
        [entitlement_type] => 1
        [deleted] => 0
        [created_by_id] => 1
        [created_by_name] => Admin
    )

    [_values:protected] => Array
    (
    )


    // It is not showing [comment] => dddd
}

1 个答案:

答案 0 :(得分:0)

这种魔法必须在你的控制器中发生,你必须使用两件事:

您必须致电$form->handleRequest($request)

您还需要使用$em->persist($entity)->flush()

来保留您的实体

以下是基于您的代码的示例。当您处理表单时,这是控制器的一部分:

class YourController extends Controller
{
    public function executeAction($request)
    {
        $entity = new Comment;
        $form = $this->createForm(new CommentType(), $entity);

            $form->handleRequest($request);

            if ($form->isValid())
            {
                $em = $this->getDoctrine()->getManager(); // this is where it begins
                $em->persist($entity); // it goes on
                $em->flush(); // done!

                return $this->redirect($this->generateUrl('your_next_url'));
            }

            return $this->render('YourBundle:YourDirectory:template.html.twig', array(
                'form' => $form->createView(),
            ));
    }
}