Skip to content

Instantly share code, notes, and snippets.

@frodosghost
Last active December 11, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frodosghost/4654901 to your computer and use it in GitHub Desktop.
Save frodosghost/4654901 to your computer and use it in GitHub Desktop.
Base form code for saving multiple classes of data with Symfony2. This is for Jerome.
<?php
namespace Your\Product\Bundle\Form\CommentType;
use Your\Product\Bundle\Form\UserType;
class CommentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('comment', 'textarea', array(
'label' => 'Comments'
))
->add('user', new UserType(), array(
'data_class' => 'Your\Product\Bundle\Entity\User',
))
;
}
// ....
}
<?php
namespace Your\Product\Bundle\Controller\ProductController;
use Your\Product\Bundle\Entity\Comment;
use Your\Product\Bundle\Form\CommentType;
class ProductController extends Controller
{
/**
* Show the Product and display the Comment form
*
* @Route("/{id}/product", name="product")
* @Method("GET")
* @Template()
*/
public function productAction($id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('YourProductBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException('Unable to find Product entity.');
}
$comment = new Comment;
$comment->addProduct($product);
$commentForm = $this->createForm(new CommentType(), $comment);
return array(
'product' => $product,
'comment_form' => $commentForm->createView()
);
}
/**
* Adds a comment to a product
*
* @Route("/{id}/product/comment", name="product_add_comment")
* @Method("PUT")
* @Template("YourProductBundle:Product:product.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('YourProductBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException('Unable to find Product entity.');
}
$comment = new Comment;
$comment->addProduct($product);
$commentForm = $this->createForm(new CommentType(), $comment);
$commentForm->bind($request);
if ($commentForm->isValid()) {
$em->persist($comment);
$em->flush();
return $this->redirect($this->generateUrl('product', array('id' => $id)));
}
return array(
'product' => $product,
'comment_form' => $commentForm->createView()
);
}
}
<?php
namespace Your\Product\Bundle\Form\UserType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'label' => 'Name'
))
->add('email', 'email', array(
'label' => 'Email Address'
))
;
}
// ....
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment