Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre Fill Symfony Form Text Field with Data From the Database

Tags:

php

symfony

How can I pre fill a text field in symfony with data from the database. I have a field in the host table called hostFee and when I create the form I want that data to pre fill this text field.

I am creating a form for new BookingSpecsType()...

Here is my form builder element.

$builder->add('hostFee', 'text', array(
        'required'=>false,
        'error_bubbling'=>true,
        'label'=>'Do you charge a hosting fee?',
        'data' => '??????? (How do I fill this text field dynamically with the Host table hostFee column data) ?????',
        'attr'=>array(
            'placeholder'=>'If yes, enter dollar amount $0.00',
            'class'=>'form-control'
        )
    ));

Thanks.

like image 831
LargeTuna Avatar asked Jul 18 '15 23:07

LargeTuna


2 Answers

The documentation provide many examples.

When you use $this->createForm in your Controller action, the second parameter, allow you to hydrate the form with an object.

For example:

public function editAction()
{
        $user = $this->getDoctrine()->getRepository('User')->find(1); // YOUR OBJECT RETRIEVED FROM THE DB FOR EXAMPLE
        $form = $this->createForm(new EditType(), $user, array(
            'action' => $this->generateUrl('account_edit'),
        ));

        return $this->render(
            'AcmeAccountBundle:Account:edit.html.twig',
            array('form' => $form->createView())
        );
}
like image 146
zilongqiu Avatar answered Nov 09 '22 01:11

zilongqiu


You do not need to define manally the data. If you just init the form from an hydrated entity, then all data are init into all fields.

like image 45
KmeCnin Avatar answered Nov 09 '22 00:11

KmeCnin