Programing

Symfony2 컨트롤러에서 양식 값을 얻는 방법

lottogame 2020. 10. 11. 09:02
반응형

Symfony2 컨트롤러에서 양식 값을 얻는 방법


다음 컨트롤러 코드로 Symfony2에서 로그인 양식을 사용하고 있습니다.

public function loginAction(Request $request)
{
    $user = new SiteUser();
    $form = $this->createForm(new LoginType(), $user);


    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        $data = $form->getValues();
        // Need to do something with the data here
    }

    return $this->render('GDSiteBundle::header.html.twig', array('form' => $form->createView()));
}

하지만 다음과 같은 경고가 표시됩니다.

경고 : array_replace_recursive () [function.array-replace-recursive] : 인수 # 1은 \ vendor \ symfony \ src \ Symfony \ Component \ Form \ Form.php 라인 593 500 내부 서버 오류-ErrorException의 배열이 아닙니다.

누군가가 잘못된 내용을 이해하도록 도와 줄 수 있으며 어떻게 수정할 수 있습니까? 감사.

업데이트 : twig 파일은 다음과 같습니다.

<div class="form">
    {{ form_errors(form) }}
    <form action="{{ path('site_user_login') }}" method="POST" {{ form_enctype(form) }}>
        <div class="level1">
            {{ form_row(form.username) }}
            <a href="javascript:void(0)" id="inscription">{% trans %}Registration{% endtrans %}</a>
        </div>
        <div class="level2">
            {{ form_row(form.pwd_hash) }}
            <div class="forget_pass"><a href="#" id="frgt">{% trans %}Forgot Password ?{% endtrans %}</a></div>
        </div>
        <input type="submit" class="submit" name="login" value/>
        <div class="clr"></div>
    </form>
</div>

다음은 양식 유형의 기능입니다.

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('username', 'text', array('label' => 'Username : '));
    $builder->add('pwd_hash','password', array('label' => 'Password : '));
}

경로는 다음과 같습니다.

site_user_login:
    pattern: /{_locale}/login
    defaults: {_controller: GDSiteBundle:SiteUser:login}

간단히 :

$data = $form->getData();

위의 어느 것도 나를 위해 일하지 않았습니다. 이것은 나를 위해 작동합니다.

$username = $form["username"]->getData();
$password = $form["password"]->getData();

도움이되기를 바랍니다.


Symfony 2 (좀 더 구체적으로 말하자면 2.3 버전)에서는 다음과 같이 필드의 데이터를 얻을 수 있습니다.

$var = $form->get('yourformfieldname')->getData();

또는 모든 데이터를 전송할 수 있습니다.

$data = $form->getData();

여기서 '$ data'는 양식 필드의 값을 포함하는 배열입니다.


Symfony> = 2.3에서는 다음을 사용하여 단일 필드의 값을 가져올 수 있습니다.

$var = $form->get('yourformfieldname')->getData();

반면에 다음을 사용할 수 있습니다.

$data = $form->getData();

그러나 이것은 두 가지 다른 것을 얻을 것입니다.

  • 양식에 data-class옵션이 활성화 된 경우 양식에 의해 채워진 값이있는 엔티티 (따라서 엔티티에 바인딩 됨) 이 것 제외 어떤 필드 'mapping' => false옵션

  • 그렇지 않으면 모든 양식의 필드가있는 배열


Entity에 정의되지 않은 양식에 추가 필드가 있고 $form->getData()작동하지 않는 경우 한 가지 방법은 다음과 같습니다.

$request->get("form")["foo"] 

또는 :

$form->get('foo')->getData();

Symfony 양식 에는 두 가지 유형의 변환기 와 세 가지 유형의 기본 데이터가 있습니다. 여기에 이미지 설명 입력어떤 양식에서든 세 가지 유형의 데이터는 다음과 같습니다.

  • 모델 데이터

    This is the data in the format used in your application (e.g. an Issue object). If you call Form::getData() or Form::setData(), you're dealing with the "model" data.

  • Norm Data

    This is a normalized version of your data and is commonly the same as your "model" data (though not in our example). It's not commonly used directly.

  • View Data

    This is the format that's used to fill in the form fields themselves. It's also the format in which the user will submit the data. When you call Form::submit($data), the $data is in the "view" data format.

The two different types of transformers help convert to and from each of these types of data:

  • Model transformers:

    transform(): "model data" => "norm data"
    reverseTransform(): "norm data" => "model data"

  • View transformers:

    transform(): "norm data" => "view data"
    reverseTransform(): "view data" => "norm data"

Which transformer you need depends on your situation.

To use the view transformer, call addViewTransformer().


If you want to get all form data:

$form->getData();

If you are after a specific form field (for example first_name):

$form->get('first_name')->getData();

I got it working by this:

if ($request->getMethod() == 'POST') {
    $username = $request->request->get('username');
    $password = $request->request->get('password');

    // Do something with the post data
}

You need to have the Request $request as a parameter in the function too! Hope this helps.


I think that in order to get the request data, bound and validated by the form object, you must use this command :

$form->getViewData();
$form->getClientData(); // Deprecated since version 2.1, to be removed in 2.3.

private function getFormDataArray($form)
{
    $data = [];
    foreach ( $form as $key => $value) {
        $data[$key] = $value->getData();
    }
    return $data;
}

If you're using Symfony 2 security management, you don't need to get posted values, you only need to manage form template (see documentation).

Symfony 2 보안 관리를 사용하지 않는 경우 사용하는 것이 좋습니다. 원하지 않거나 할 수 없다면 LoginType출처 를 알려 주실 수 있습니까?


특정 필드의 데이터를 얻으려면

$form->get('fieldName')->getData();

또는 모든 양식 데이터

$form->getData();

문서 링크 : https://symfony.com/doc/2.7/forms.html


매핑되지 않은 양식 필드의 경우 $ form-> get ( 'inputName')-> getViewData ();

참고 URL : https://stackoverflow.com/questions/8987418/how-to-get-form-values-in-symfony2-controller

반응형