shayster01
shayster01

Reputation: 214

Symfony: How to pass non-entity variables to form

I have a form which collects data from three entities. I collect the data and want some of that filled out on the submitted form. This all works fine and I can even pass the data to the controller but I have an entity which doesn't contain the data I am trying to just use as a paragraph tag but don't want to persist:

members.php(entity)

/**
 * @var integer
 */
private $orgId;

/**
 * @var integer
 */
private $personId;


/**
 * @var string
 */
private $title;

/**
 * @var integer
 */
private $rank;

/**
 * @var integer
 */
private $myMemberId;

So I want to show The person's name and organization name instead of $personId and $orgId. So I thought I would pass them as well and show them in a paragraph tag but I can't figure out how to pass them. Here is what I have:

membersController.php

 public function mynewAction(Request $request)
{
    $data = $request->get("companynameofbundle_jquery");
    $entity = new Members();
    $entity->setOrgId($data['orgid']);
    $entity->setPersonId($data['personId']);

    //var_dump($request); shows organization name and person name
    //need to pass person name and organization name to edit form just to display
    $form   = $this->createCreateForm($entity);

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

I did think about re-looking up the values but seems like more db work when I already have the values and don't need all the other data or overhead.

Thought the for might help:

class MemberType extends AbstractType
{



 /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //Would like person name and organization name instead of id's
            ->add('orgId', 'hidden')
            ->add('personId', 'hidden')
            ->add('title')
            ->add('rank')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Company\NameofBundle\Entity\OrgMember'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'company_nameofbundle_orgmember';
    }
}

Upvotes: 0

Views: 478

Answers (1)

Frank B
Frank B

Reputation: 3697

You can add extra fields with mapped => FALSE.

->add('apple', 'text', array('mapped' => false))
->add('banana', 'hidden', array('mapped' => false))

In the controller you can retrieve the submitted data from field like this:

$form->handleRequest($request);

$data = $form->get('apple')->getData(); // after handleRequest() !

Upvotes: 2

Related Questions