Reputation: 201
I have a reply form setup for replies to posts.
I want to setup the author to be the user currently logged in. Right now it's just a drop down menu of previous authors that's already posted, which isn't what I want.
How do I set it up to use the current logged in username as an author instead having a list of authors already saved to the database?
Is there a global command to access the currently logged in user to pass in to the ->add('author)
line in the form?
ReplyType form
class ReplyType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('author')
->add('body')
->add('post', 'submit');
}
/**
* {@inheritDoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Reply'
));
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'acme_demobundle_reply';
}
}
Reply entity
/**
* @var Author
*
* @ORM\ManyToOne(targetEntity="Author", inversedBy="replies")
* @ORM\JoinColumn(name="author_id", referencedColumnName="id", nullable=false)
* @Assert\NotBlank
*/
private $author;
Upvotes: 0
Views: 234
Reputation: 650
Since the logged in user is the author, how about removing the field and setting the author to the currently logged in user inside the controller? The user should not actually select the author (ie: see Stackoverflow.com reply or comment forms).
// ...
use Symfony\Component\HttpFoundation\Request;
public function postReplyAction(Request $request)
{
$reply = new Reply();
$form = $this->createForm(new ReplyType(), $reply);
$form->handleRequest($request);
if ($form->isValid()) {
// perform your logic and before savig the reply to the database
$reply->setAuthor($this->getUser());
// save your reply
return $this->redirect($this->generateUrl('reply_success'));
}
// ...
}
And your form type becomes:
class ReplyType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('body')
->add('post', 'submit');
}
/**
* {@inheritDoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Reply'
));
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'acme_demobundle_reply';
}
}
Upvotes: 4