symfony2: trying to render a form in the template - symfony

I'm trying to render a form that I've just generated from an entity, but Im getting the error below...
<?php
namespace Prueba\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Prueba\FrontendBundle\Form\ItemType;
class DefaultController extends Controller
{
/**
* #Route("/hello")
* #Template()
*/
public function indexAction($name)
{
$form = new ItemType();var_dump(get_class($form));
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
}
string(35) "Prueba\FrontendBundle\Form\ItemType" Fatal error: Call to
undefined method Prueba\FrontendBundle\Form\ItemType::createView() in
/home/javier/programacion/sf2000/src/Prueba/FrontendBundle/Controller/DefaultController.php
on line 20

Change
$form = new ItemType();
to
$form = $this->createForm(new FormType());
And if you want to attach an empty entity to the form (easier validation and form processing):
$item = new Item();
$form = $this->createForm(new FormType(), $item);

Related

add normal text type field (not text box) to form in symfony

I want to show a list of names (which I get from a database) in a form with its corresponding delete and update button. But by adding a field to the form like this:->add('nombre',null,array('data' => $gen["name"],'label' =>'nombre', 'attr' => array('class' => 'className')))
It appears to me as a text box and what I want is the text, I do not know if I explain myself, not as a textbox. I want it like this: https://postimg.cc/2LWQhMDM
This is the code of my controller:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use AppBundle\Entity\Genus;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use AppBundle\Form\GenusFormType;
use Symfony\Component\Form\Extension\Core\Type\AddressType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage"))
*/
public function newAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$genuses = $em->getRepository('AppBundle:Genus')
->consulta(20);
foreach ($genuses as $gen)
{
$form = $this->createFormBuilder()
//->setAction($this->generateUrl('app_lucky_number'))
->setAction($this->generateUrl('homepage'))
->setMethod ("POST")
->add('nombre',null,array('data' => $gen["name"],'label' =>'nombre', 'attr' => array('class' => 'className')))
->add('id',HiddenType::class, ['data' => $gen["id"],])
->add('actualizar', SubmitType::class,array('label' => 'actualizar','attr' => array('class' => 'className')))
->add('borrar', SubmitType::class,array('label' => 'borrar','attr' => array('class' => 'className')))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$genus = $form->getData();
$id=$genus["id"];
if ($form->get('borrar')->isClicked())
{
$em = $this->getDoctrine()->getManager();
$genuses = $em->getRepository('AppBundle:Genus')
->borrar($id);
}
//return $this->render('genus/principal.html.twig',array('name'=>$name));
return $this->render('genus/principal.html.twig',array('id'=>$id));
}
$formularios[]=$form->createView();
}
return $this->render('genus/show.html.twig',['genuses'=>$formularios]);
}
}
?>
I think the better solution would be to create separate update and delete methods in the controller.
So u can build a tabel as showen in your screenshop by giveing the data of $genuses to the template show.html.twig .
And there u make an a-tag like:
Delete

How to submit form in PHPunit with symfony?

I am using symfony 3.0 and phpunit 3.7.1.I want to submit a form via phpunit file.
File Name: abcControllerTest.php
<?php
namespace AbcBundle\Tests\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
class AbcControllerTest extends WebTestCase {
public function testEmpty() {
$whereParams = array('params' => array(
'var' => '',
));
return $whereParams;
}
/**
* ABC Builder
* #depends testEmpty
*/
public function testAbc(array $whereParams) {
$client = static::createClient();
$crawler = $client->request('GET', $GLOBALS['host'] . '/abc/ac_file/param', $whereParams);
$buttonCrawlerNode = $crawler->selectButton('Submit');
$form = $buttonCrawlerNode->form();
$crawler = $client->submit($form);
}
}
I am testing export report functionality thats why i am just creating a submit button and trying to submit form on specific url with some parameter.
Error Message: InvalidArgumentException: The current node list is empty.
Anyone can suggest me what can i do?

Submitting to database

I can't submit my form to database when I validate I have nothing in my table in phpMyAdmin. Here is the code in the controller. I want to submit a form which contains an upload type.
<?php
// src/AppBundle/Controller/ProductController.php
namespace Upload\FileBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Upload\FileBundle\Entity\Product;
use Upload\FileBundle\Form\ProductType;
use Symfony\Component\Form\FormView;
class ProductController extends Controller
{
/**
* #Route("/product/new", name="app_product_new")
*/
public function newAction(Request $request)
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
$form->handleRequest($request);
if ($form->isValid()) {
// $file stores the uploaded PDF file
/** #var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $product->getBrochure();
// Generate a unique name for the file before saving it
$fileName = md5(uniqid()).'.'.$file->guessExtension();
// Move the file to the directory where brochures are stored
$brochuresDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/brochures';
$file->move($brochuresDir, $fileName);
// Update the 'brochure' property to store the PDF file name
// instead of its contents
$product->setBrochure($fileName);
// ... persist the $product variable or any other work
return $this->redirect($this->generateUrl('app_product_list'));
}
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('upload_file_success'));
}
return $this->render('UploadFileBundle:Product:new.html.twig', array(
'form' => $form->createView(),
));
}
}
Your logic is wrong.
Try this code:
<?php
// src/AppBundle/Controller/ProductController.php
namespace Upload\FileBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Upload\FileBundle\Entity\Product;
use Upload\FileBundle\Form\ProductType;
use Symfony\Component\Form\FormView;
class ProductController extends Controller
{
/**
* #Route("/product/new", name="app_product_new")
*/
public function newAction(Request $request)
{
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
if ($request->isMethod(Request::POST))
{
$form->handleRequest($request);
if ($form->isValid()) {
// $file stores the uploaded PDF file
$file = $product->getBrochure();
/* #var Symfony\Component\HttpFoundation\File\UploadedFile $file */
// Generate a unique name for the file before saving it
$fileName = md5(uniqid()).'.'.$file->guessExtension();
// Move the file to the directory where brochures are stored
$brochuresDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/brochures';
$file->move($brochuresDir, $fileName);
// Update the 'brochure' property to store the PDF file name
// instead of its contents
$product->setBrochure($fileName);
// ... persist the $product variable or any other work
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('app_product_list'));
}
}
return $this->render('UploadFileBundle:Product:new.html.twig', array(
'form' => $form->createView(),
));
}
}
I also recommend using VichUploaderBundle
https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/index.md
Because your logic is wrong. You check form in first if and redirect code to list page. But your code can not work second if ever.

How to get doctrine from abstract class in Symfony2?

In my code I need to download from database some data and put it to the form, but I don't know how to get doctrone outside Controller class.
I tried create new service, but it didn't work (I think I can't use in this case __controller(), am I right?). I tried also transfer instance of the controller to the parameters of buildForm() method but I got message: FatalErrorException: Compile Error: Declaration of MyBundle\Form\Type\TemplateType::buildForm() must be compatible with that of Symfony\Component\Form\FormTypeInterface::buildForm() ).
This is my code:
class TemplateType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name', 'text')
// ...
->add('description', 'textarea');
}
public function getName() {
return 'template';
}
}
How can I use inside buildForm() doctrine?
In order to send data from doctrine to your form, you need to do this into your controller:
public function doSomethingWithOneObjectAction( $id )
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository( 'AcmeBundle:ObjectEntity' )->find( $id );
if ( ! $entity) {
throw $this->createNotFoundException( 'Unable to find Object entity.' );
}
$form = $this->createForm(
new TemplateType(),
$entity
);
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
If you want to access a service from container inside your form type, you need first to register it as an service and inject into it the services you need. Something like this

symfony2 form error

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess,
but is an instance of class Ecs\CrmBundle\Entity\Customer.
Is the error I get in my browser..
FORM CODE:
<?php
namespace Ecs\CrmBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class CustomerDefaultConfigType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('customerStatus')
->add('tags', null, array('multiple' => true, 'property' => 'tag_name'))
;
}
public function getName()
{
return 'ecs_crmbundle_customerdefaultconfigtype';
}
}
and the controller Action:
<?php
namespace Ecs\CrmBundle\Controller;
use Ecs\CrmBundle\Entity\CustomerDefaultConfig;
use Ecs\CrmBundle\Form\CustomerDefaultConfigType;
public function newAction()
{
$entity = new CustomerDefaultConfig();
$form = $this->createForm(new CustomerDefaultConfigType(), $entity);
return $this->render('EcsCrmBundle:CustomerDefaultConfig:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
This is using symfony2.1 with composer... Any ideas on how to get this working?
Since the last form refactoring, you have to specified the data_class in the setDefaultOptions method in your type.
See here (search for data_class).
Edit: Correct link

Resources