在Symfony2中保存没有隐藏字段的单身日期


Save singup date whitout hidden field in Symfony2

首先感谢您的阅读和努力帮助我。我是symfony的新手。

我有一个属性为FechaAlta (SingUpDate)的实体。我想保存用户更新日期

/**
 * @var date
 *
 * @ORM'Column(name="fechaAlta", type="datetime")
 */
private $fechaAlta;
/**
 * Set fechaAlta
 *
 * @return Promotor
 */
public function setFechaAlta()
{
    $this->fechaAlta = new 'DateTime('now');
    return $this;
}

我想知道保存这个日期的最好方法是什么,而不是在表单上有一个隐藏的字段。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('nombre')
        #->add('slug')
        ->add('fechaAlta')
    ;
}

我已经尝试删除表单字段"fechaAlta",但保持得到以下错误

An exception occurred while executing 'INSERT INTO Promotor (nombre, slug, fechaAlta) VALUES (?, ?, ?)' with params {"1":"Prueba","2":"prueba","3":null}:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fechaAlta' cannot be null

在newAction()中调用$promotor->setFechaAlta();这将保存当前日期。

public function newAction()
{
    $promotor = new Promotor();
    $promotor->setFechaAlta();
    $form   = $this->createForm(new PromotorType(), $promotor);
    return $this->render('PromotorBundle:Promotor:new.html.twig', array(
        'entity' => $promotor,
        'form'   => $form->createView(),
    ));
}

Thank you so much

您可以使用@Lighthart解决方案,也可以使用您的实体构造函数。
使用实体构造函数的好处是,如果你在第二个控制器/动作中创建了这种类型的对象,并希望保持相同的行为,你不需要重复自己。

//Your entity code
/**
 * @var date
 *
 * @ORM'Column(name="fechaAlta", type="datetime")
 */
private $fechaAlta;
public function __construct()
{
    $this->fechaAlta = new 'DateTime('now');
}

不要忘记从表单中删除字段:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('nombre');
}

默认的symfony模式是newAction生成一个表单并发送给createAction。

createAction是你应该设置日期的地方:

public function createAction( Request $request, $id ) {
    $promotor = new Promotor();
    $promotor->setFechaAlta();
    $form   = $this->createForm(new PromotorType(), $promotor);
    $form->bind( $request );
    if ( $form->isValid() ) {
        $this->getDoctrine()->getManager()->persist( $promotor );
        $this->getDoctrine()->getManager()->flush();
    return $this->redirect( 
        $this->generateUrl( 'promotor_show', array( 'id' => $promotor->getId() ) ) 
        );
    }
    return $this->render( 'PromotorBundle:Promotor:new.html.twig'
        , array(
        )
    );
}