Reputation: 3549
I have form like this :
name (required).
slug (required).
slug
is required in back end but user is allowed to leave it blank in form field ( if user leave slug blank, it will use name
as the input instead ).
I have tried with Event form listener
but it said You cannot change value of submitted form. I tried with Data transformers
like this :
public function reverseTransform($slug)
{
if ($slug) {
return $slug;
} else {
return $this->builder->get('name')->getData();
}
}
return $this->builder->get('name')->getData();
always return null. So I tried like this:
public function reverseTransform($slug)
{
if ($slug) {
return $slug;
} else {
return $_POST['category']['name'];
}
}
it works but I think it against the framework. How I can done this with right way?
Upvotes: 1
Views: 4137
Reputation: 3549
Another possible way is to set via request class like this:
Array form <input name="tag['slug']"...>
:
public function createAction(Request $request)
{
$postData = $request->request->get('tag');
$slug = ($postData['slug']) ? $postData['slug'] : $postData['name'];
$request->request->set('tag', array_merge($postData,['slug' => $slug]));
.......
Common form <input name="slug"...>
:
$request->request->set('slug', 'your value');
I think this is the best way because if you are using dml-filter-bundle
you don't need to filter your input in your controller like this again:
$this->get('dms.filter')->filterEntity($entity);
Upvotes: 0
Reputation: 634
You can also do it in the controller
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
// get the data sent from your form
$data = $form->getData();
$slug = $data->getSlug();
// if no slug manually hydrate the $formObject
if(!$slug)
{
$formObject->setSlug($data->getName());
}
$em->persist($formObject);
$em->flush();
return ....
}
}
Upvotes: 2
Reputation: 1258
If you use a function to keep the code at one place then you should also not work with Request data. In the form action you call that function including the name variable.
public function reverseTransform($name, $slug)
{
if (!empty($slug)) {
return $slug;
} else {
return $name;
}
}
Upvotes: 1