Extending existing Class in Symfony - symfony

I am new to symfony. I have created a registration form using the code:
$user = new Register();
$form = $this->createForm(new RegisterType(), $user);
In the RegisterType class i have 5 fields (for example).I store the values in database when the user registers with the system. Now I display the EDIT page using following code:
$user = $em->getRepository('MysiteUserBundle:Register')->find($id);
$form = $this->createForm(new RegisterType(), $user);
//edit.html.twig code
<form action="{{ path('MysiteUserBundle_register_update',{'id':user.id}) }}" method="post" {{ form_enctype(form) }} class="register">
{{ form_errors(form) }}
{{ form_row(form.firstname) }}
{{ form_row(form.lastname) }}
{{ form_row(form.username) }}
<p>
<input type="submit" value="Submit">
</p>
</form>
The problem with the EDIT code however is that it displays me all of the fields mentioned in RegisterType class.Is it possible to display only some fields. If yes how can this be achieved. Any help will be appreciated

It doesn't make sense to use the registration form type to edit a user, because registration happens once per user. Instead you could create another form type with only those fields you need when editing a user. One can extend the other to avoid duplication.
You could also:
Keep just one form type but add some fields conditionally — that is, only when the entity is new. You can get your entity in the form type as $options['data'] and check if its ID is not null or whatever.
Use form events.

Related

edit form with some disable field

i have a form with some field and i want user edit only some field and the other field must be only visible .
In my controller i have the form
$element = $this->getDoctrine()->getRepository('AppBundle:Element')->find($id_element);
$form = $this->createForm(ElementType::class, $element, array('user' => $user));
code here`$form->handleRequest($request);
Now in my twig file
{{ form_start(form) }}
{{ form_widget(form.element,{ 'attr':{'disabled':'disabled'}}) }}
In this way when i click submit button say not focusable field so i add
{{ form_widget(form.element,{ 'attr':{'disabled':'disabled'}}) }}
but when i save the field element in database become null
How i can do it ??
Use readonly attribute for it
{{ form_widget(form.element,{ 'attr':{'readonly':'1'}}) }}
Values of disabled controls are not submitted with a form.
https://www.w3.org/TR/PR-html40-971107/interact/forms.html#h-17.7

edit only the first entity inside an embedded collection

I have a parent entity called Publisher and a child entity called User with a ManyToMany relation.
Inside the publisher form, I want to create/edit also the first user, which I achieve like this:
$builder
->add('title')
->add('users', 'collection', array(
'type' => new UserType(),
'allow_add' => true,
))
and in my twig template, I do
{{ form_row(edit_form.users.0.firstname) }}
{{ form_row(edit_form.users.0.lastname) }}
{{ form_row(edit_form.users.0.email) }}
This obviously only works as long as there is just one user assigned to the publisher, because otherwise symfony tries to validate the other users as well, whose data is missing.
Can someone give me a hint how to edit only the first user item in the collection from the publisher form?
You can set the field users "rendered" after having displayed the firt user:
{{ form_row(edit_form.users.0.firstname) }}
{{ form_row(edit_form.users.0.lastname) }}
{{ form_row(edit_form.users.0.email) }}
{% do edit_form.users.setRendered %}
With setRendered, Symfony2 won't try to validate the next users.
I solved the problem using Cerad's solution by introducing a getter and setter for the first user.
public function setFirstUser($user)
{
$this->users[0] = $user;
return $this;
}
public function getFirstUser()
{
return $this->users[0];
}
and in the form doing this
$builder
->add('title')
->add('firstUser', new UserType())
and calling the fields of the firstUser in the twig template The setRendered line just supresses other properties of the user object.
{{ form_row(edit_form.firstUser.firstname) }}
{{ form_row(edit_form.firstUser.lastname) }}
{{ form_row(edit_form.firstUser.email) }}
{% do edit_form.firstUser.setRendered %}
EDIT: because of Cerads feedback about the non-deterministic ordering of SQL rows I chose to create a real property "adminUser", which is a OneToOne relation to the first user attached to the entity.

Get value of a field not declared in FormType

I have a form declared in nameType.php and the view render all field but I want add another field manually.
Form:
<form action="{{ path('create') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="text" value="2">
</form>
And get the values in the controller:
$form->bindRequest($request);
How can I collect the value of the input in the controller?
If you are trying this because the form is linked to your entity field you can add a field to FormType as not mapped. Then you do not need getters and setters on your entity.
->add("inputName", "text", array("mapped"=>false, "data"=>2, "label"=>false))
To get the data in the controller:
$form->get("inputName")->getData();
You can not retrieve the input value from the $form, because it's not part of it.
You have to retrieve it from the request in the Controller by using the name attribute :
HTML : <input type="text" value="2" name"var_name">
Controller: $request->request->get('var_name')
how could collect the value of the input to the controller?
The instant-gratification way would be to use
$form->get('inputName')->getViewData()
for an unmapped field. But I'm sure there are better ways which are Symfony validation-compliant.
After calling $form->bindRequest($request) you can call: $form->getData() to get input from user.
But if you want to receive input data for field that is not mapped you need to use mentioned $request->request->get('field_name').

Symfony2 : How to upload a file without Doctrine?

I use Symfony2.3. I have a form like this :
<form action="{{ path("member_update") }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form.pic) }}
...
{{ form_widget(form._token) }}
</form>
and i want to upload user pictures in a directory.Then i use this in controller :
$member , $form , $dm is defined...
if ($form->isValid()) {
// Handle profile picture upload process
$uploadDir=dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/mybundle/myfiles';
$form['pic']->getData()->move($uploadDir,$member->getId());
// End of upload
$dm->persist($member);
$dm->flush();
return $this->redirect($this->generateUrl("member_profile"));
}
It must work,but i see this error:
Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
1. in pathToMyProject...\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DataCollector\DataCollector.php line 27
2. at serialize(.....
What's the problem??!
The problem solved! I change this line in MemberType :
$builder->add('pic','file');
to this :
$builder->add('pic','file', array('mapped'=>false));
My mistake was that i must explain the "pic" field is not mapped to the Entity(or Document in Mongo,as my project). Else Symfony kernel try to put the value of "pic" in a field of Entity. And i have not any field that hold a file! I upload the picture in a directory and store only path to the picture within the entity. When i changed this,the problem solved easily! :-)
So keep in mind to explain all things clearly to Symfony!

How to pass data from twig to Symfony2 controller using form

I would like to know if there is a method to pass some variables (text from textarea) from Twig to Symfony2 controller via form.
<form action="{{ path('admin_core_save') }}" method="post">
<div id="edit-template">
{% if template.getData() is defined %}
<textarea id="template">{{ template.getData() }}</textarea>
{% endif %}
</div>
<input type="submit" value="Save" />
</form>
When I press save button it is going to saveAction() method
public function saveAction(Request $request)
{
var_dump($request);
return new Response('abc');
}
but response does not contain any textarea text. Is there a way to get this there?
I know I can build form inside the controller and send it to Twig, but I would like to know if this way is possible.
you can access POST values through request object like:
$this->get('request')->request->get('name');
I'm sure you have to learn a bit about Symfony2 Form Component. You will find that symfony already has built-in system for rendering forms handling user data posted through them.
Answering your question. There is a Request object that provides you full access to all request data, including POST variables.
To access POST values use Request::get() method:
$request->get('variable_name');
To pass any data to the twig template, use TwigEngine::renderResponse
$this->container->get('templating')->renderResponse('AcmeDemoBundle:Demo:template.twig,html',
array(
'someVar' => 'some value'
)
);
This var will be avaliable in your template as:
{{ someVar }}

Resources