Search code examples
phpformssymfonyentity

Symfony2: how to add label, attr to Entity to show in form (ContactType form, entity ContactMessage)?


How to add label, trim, attr => [placeholder => "Field name"] to Entity to show in form (form ContactMessageType, entity ContactMessage)? I'm trying to configure form fields and entity fields in one file -> entity class ContactMessage. Is that possible? If yes, how? If no, what to do?

My entity:

 use Symfony\Component\Validator\Constraints as Assert;
 use Doctrine\ORM\Mapping as ORM;
 /**
 * php app/console doctrine:schema:validate
 * php app/console doctrine:schema:update --force
 *
 * Class ContactMessage
 * @see http://symfony.com/doc/2.8/doctrine/registration_form.html
 *
 * @ORM\Entity
 * @ORM\Table(name="contact_messages", options={"collate"="utf8_general_ci"})
 */
class ContactMessage
{
    public function __construct()
    {
        $this->createdDateTime = new \DateTime("now");
    }

/**
 * @ORM\Column(type="integer", nullable=false, options={"unsigned":true, "length":11})
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 *
 * @var integer
 */
protected $id;
/**
 * @Assert\NotBlank()
 *
 * @ORM\Column(type="string", name="sender_name", nullable=false, length=255, options={})
 *
 * @var string
 */
protected $senderName;
/**
 * @Assert\NotBlank()
 *
 * @ORM\Column(type="string", name="sender_email", nullable=false, length=512, options={"default":""})
 *
 * @var string
 */
protected $senderEmail;
/**
 *
 *
 * @ORM\Column(type="string", name="sender_message", nullable=false, length=4096, options={"default":""})
 *
 * @var string
 */
protected $senderMessage;
/**
 *
 * @ORM\Column(type="string", name="sender_phone_number", nullable=false, length=16, options={"default":""})
 *
 * @var string
 */
protected $senderPhoneNumber;

/**
 * @ORM\Column(type="datetime", name="created_date_time", nullable=false,  options={"default": "0000-00-00 00:00:00"})
 *
 * @var \DateTime
 */
protected $createdDateTime;

}

Solution

  • I'm not sure understand your problem, but you can add labels and placeholder inside yout FormType:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('senderName', TextType::class, [
                'required' => false,
                'label'    => 'Your label',
                'attr'     => [
                    'placeholder' => 'Your placeholder',
                ],
            ]);
    }