Symfony2 Form folder - php

I need to create a form class,I'm following the symfony book in http://symfony.com/doc/current/book/forms.html
I am trying to create a form in src/Acme/TaskBundle/Form/Type/TaskType.php, but when I look at the folder structure on my project there is no "Form" folder.
I try to create the Form folder manually, in src/Acme/TaskBundle/, I get an error in the the Form Folder and in the TaskType.php files ( namespace Acme\TaskBundle\Form\Type Expected:Identifier).
Is there a way to create the Form folder in an automatic way? Or how can I create in manually?

The Form folder is just a convention — you can put your forms wherever you want. The convention extends to:
Form\Type for form types,
Form\Model for form models,
Form\Handler for form handlers,
etc.

Have you tried the command, might be what you're looking for
php app/console generate:doctrine:form

I just created it manually.
form: (my case: LL\NameBundle\Form)
FormName.php
<?php
namespace LL\NameBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class FormName extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('add')
->add('your')
->add('fields')
;
}
public function getName()
{
return 'form-name';
}
}
Controller:
use LL\NameBundle\Form\FormName;
public function()
{
$form = new FormName();
$form = $this->form( $form, $entity );
return array(
'form' => $form->createView()
);
}
This Works for me, if it doesn't work please post some code.

Related

separate one form into 2 independent forms in symfony FOS

I created a login system in symfony with the possibility to register only for those who own a so called "client number", right now my problem is the registration form where user has basically to type in at first his client number which is going to be validated first if it exists in a database and then after submitting it, orm fetches some data about the company which possesses the client number and the application forwards user to another form where he has to type in other details like his username and password. So far right now I have it in one form and I created it after as being described in tutorial like with Registration Controller, Registration Form Handler and Registration Type, right now for example in Registration Type it looks like this
<?php
// src/AppBundle/Form/RegistrationType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
class RegistrationType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->add('name');
// $builder->add('ClientNr'); <-- I want to check it in another form before i come to registration
$builder->add('lanr');
$builder->add('personal_key', HiddenType::class, array(
'data' => $this->getID()));
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
// Or for Symfony < 2.8
// return 'fos_user_registration';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
// For Symfony 2.x
public function getName()
{
return $this->getBlockPrefix();
}
public function getID()
{
return $random = random_int(10000,99999);
}
as far as I know I have again to create files like "PreRegistration Controller, PreRegistrationFormHandler and PreType" or what are the exact steps to realize my idea?

handle which form is submitted and persist entity after findAll

I'll try to explain myself (my English is not as good as I wish)
I'm very inexperienced with symfony2 and doctrine2.
I'm trying to create a twig template and all the logic to handle modifications in, for example, user entity.
I've made the UserType AbstractType class and can handle, modify and persist if I get just one record or, at least, if I show only one form.
I've tried to do the same thing showing to the user every "User" in my database, and allowing him to modify and save one of them each time by clicking in submit button.
What I have right now:
src/Dummy/Form/Type/UserType.php
namespace Dummy\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction('')
->setMethod('POST')
->add('Name')
->add('Adress')
->add('save')
;
}
}
src/Dummy/Test/Controller/TestController.php
namespace Dummy\TestBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Dummy\TestBundle\Entity\Users;
use Dummy\Form\Type\UserType;
class ArticuloController extends Controller
{
public function indexAction(Request $request)
{
//some stuff
$users= $this->getDoctrine()
->getRepository('DummyTestBundle:Users')
->findAll();
$forms = array();
foreach($users as $user)
{
$forms[] = $this->createForm(UserType::class, $user); //*1
}
//... Don't know how to handle request with $forms[index]->submit(...
//... Check if is valid
//... set values
//... persist
$twigForms = array();
foreach($forms as $form)
{
$twigForms[] = $form->createView()
}
//... render twig template
}
}
Also I have the entity Users which works fine, made from yaml config file as described in the documentation
What I want
Handle the request and persist the object modifications.
The part that works
Until clicking in that submit button this works fine, it shows a template with a form for each user in database, every one of them with his submit button. After pressing any of them I'm completely lost.
If I force index to be 0, it works too (but only in the first form).
Because of that, I think that I need to know the index in $users or $forms variable (marked with *1 commented point above) in order to handle that request using something like:
$forms[index]->submit($request->request->get($forms[index]->getName()));
if ($forms[index]->isValid()) {
$users[index]->setName('Name from post');
$users[index]->setAdress('Adress from post');
$em = $this->getDoctrine()->getManager();
$em->persist($users[index]);
$em->flush();
}
But don't know if this is correct or how to do it.
I also read about collections, but don't know how to make this work with them.

Using Symfony Form 2.3 in Silex

I'm trying to build a Symfony form (in Silex) by name. Using the configuration below, I believe I should be able to call $form = $app['form.factory']->createBuilder('address');, however the FormRegistry cannot find a form of this type.
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormTypeExtensionInterface;
class AddressType extends AbstractType implements FormTypeExtensionInterface
{
public function getName()
{
return 'address';
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('addressee', 'text');
// .. fields ..
$builder->add('country', 'text');
}
public function getExtendedType()
{
return 'form';
}
}
This is then added to the form registry using the form.type.extensions provider:
$app['form.type.extensions'] = $app->share($app->extend('form.type.extensions', function($extensions) use ($app) {
$extensions[] = new AddressType();
return $extensions;
}));
Is there something else I need to do or a different way of building the form in this way?
Why not use direct
$app['form.factory']->createBuilder('Namespace\\Form\\Types\\Form')
First, sorry for my poor english. :)
I think you should extend form.extensions, instead of form.type.extensions.
Something like this:
$app['form.extensions'] = $app->share($app->extend('form.extensions',
function($extensions) use ($app) {
$extensions[] = new MyTypesExtension();
return $extensions;
}));
Then your class MyTypesExtension should look like this:
use Symfony\Component\Form\AbstractExtension;
class MyTypesExtension extends AbstractExtension
{
protected function loadTypes()
{
return array(
new AddressType(),
//Others custom types...
);
}
}
Now, you can retrieve your custom type this way:
$app['form.factory']->createBuilder('address')->getForm();
Enjoy it!
I see, this question is quite old but:
What you do is creating a new Form Type not extending an existing one, so the correct way to register it to add it to the 'form.types'. (Remember: form type extension is adding something to the existing types so for the future all instance will have that new 'feature'. Here you are creating a custom form type.)
$app['form.types'] = $app->share($app->extend('form.types', function ($types) use ($app) {
$types[] = new AddressType();
return $types;
}));
I think when you are coming from Symfony to Silex form.type.extension can be misleading.
From Symfony How to Create a Form Type Extension:
You want to add a generic feature to several types (such as adding a "help" text to every field type);
You want to add a specific feature to a single type (such as adding a "download" feature to the "file" field type).
So as your code shows you want to add a FormType which exists in Symfony but you would use the FormServiceProvider in Silex without defining an AbstractType and just use the form.factory service as shown in this example:
In your app.php:
use Silex\Provider\FormServiceProvider;
$app->register(new FormServiceProvider());
In your controller/action:
$form = $app['form.factory']->createBuilder('form', $data)
->add('name')
->add('email')
->add('gender', 'choice', array(
'choices' => array(1 => 'male', 2 => 'female'),
'expanded' => true,
))
->getForm()
;

Custom form type symfony

I need to set up a custom form type in Symfony that uses the choice type as a parent but doesn't actually require choices to be preloaded. As in I want to be able to populate the select with an ajax call and then submit with one of the options from the call without getting This value is not valid. errors, presumably because its not one of the preloaded options.
I don't need a custom data transformer as I am doing that through the bundle controller, I just need Symfony not to complain when I submit with an option that wasn't originally on the list. Here is what my custom form type looks like so far:
<?php
namespace ISFP\Index\IndexBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class NullEntityType extends AbstractType
{
public function getDefaultOptions(array $options)
{
$defaultOptions = array(
'em' => null,
'class' => null,
'property' => null,
);
$options = array_replace($defaultOptions, $options);
return $options;
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'null_entity';
}
}
Dude look at the EntityType it has a parent as a choice. But entire display was handle by ChoiceType. When I was doing similar things I've started from overload Both ChoiceType and EntityType. And then set in overloaded Entity the getParent() to mine overloaded choice.
Finally In my case I modify the new choice and put there my embedded form. It's tricky to do It. And it consumes lot's of time.
But with that approach i don't have any problem with Validation.

Overriding Fosuser profile form's label

I write a formtype extends the forsuser ProfileFormType, but everytime I rendered it in template, there should be always a label "User" appear in top of form. I figured out it comes form original fosuser ProfileFormType:
namespace FOS\UserBundle\Form\Type;
use .....
class ProfileFormType extends AbstractType
{
private $class;
/**
* #param string $class The User class name
*/
public function __construct($class)
{
$this->class = $class;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$child = $builder->create('user', 'form', array('data_class' => $this->class));
$this->buildUserForm($child, $options);
.......
if I add the attribute for this form field like:
$child = $builder->create('user', 'form', array('label'=>'some info','data_class' => $this->class));
it could be worked, but its bad for modify the original files, how can I modify it in my custom formtype or in template when rendering?
You need to extend the FOSUserBundle by creating your own UserBundle and within the Bundle class add:
public function getParent()
{
return 'FOSUserBundle';
}
Then create Form/Type directory and create a new form type called ProfileFormType and within that new form type place:
namespace Acme\UserBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class ProfileFormType extends BaseType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
// add your custom field
$builder->add('name');
}
public function getName()
{
return 'acme_user_profile';
}
After that you need to add the new form to the service like:
<services>
<service id="acme_user.profile.form.type" class="Acme\UserBundle\Form\Type\ProfileFormType">
<tag name="form.type" alias="acme_user_profile" />
<argument>%fos_user.model.user.class%</argument>
</service>
</services>
Finally add this to your config.yml:
fos_user:
# ...
profile:
form:
type: acme_user_profile
Remember to replace acme with your current structure information.
More information can be found at: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.md
If you want to override only labels, just add a FOSUserBundle.xx.yml file in app/Resources/FOSUserBundle/translations directory. No need to override the whole bundle, even if it could the proper for further overrides...
If you already have overrode FOSUserBundle, add the file in YourCustomFOSUserBundle/Resources/translations !
Copy it from the FOSUserBundle/Resources/translations/FOSUserBundle.xx.yml you want to override, and modify translations. You should keep only modified translations in this file.

Categories