简体   繁体   中英

Modify form value after submit in symfony2

I have form like this :

  1. name (required).

  2. 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?

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 ....
      }
  }

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;
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM