2016-07-30 26 views
2

私は、ページをリロードせずにチェックボックスを使ってユーザを有効/無効にする方法を理解しようとしています。Symfony:Ajax urlにパラメータを渡す

index.html.twig

<table> 
    <thead> 
    <tr> 
     <th>UserName</th> 
     <th>Enabled</th> 
    </tr> 
    </thead> 
    <tbody> 
    {% for user in users %} 
    <td><a href="{{ path('user_show', {'id': user.id}) }}"> 
      {{ user.username }}</a> 
    </td> 
    <td><input id="user_enable_{{ user.id }}" onclick="enabledChange({{ user.id }})" 
    type="checkbox" {% if user.enabled %}checked{% endif %}/> 
    </td> 
    {% endfor %} 
    </tbody> 
</table> 

<script> 
var changePath = {{ path('user_enable_change', {'id': user.id}) }}; 

function enabledChange(id) 
{ 
    var value = $(this).val(); 
    console.log('value: ' + value); 
    $.ajax({ 
     type: "POST", 
     url: changePath, 
     async: true, 
     data: { }, 
     success: function() { 
      console.log('success'); 
     } 
    }); 
} 
</script> 

UserControllerで

/** 
* @Route("/enable/{id}", name="user_enable_change") 
*/ 
public function userDisableAction(User $user) { 

    if($user->isEnabled()){ 
     $user->setEnabled(false); 
    }else { 
     $user->setEnabled(true); 
    } 

    try { 
     $em = $this->getDoctrine()->getManager(); 
     $em->persist($user); 
     $em->flush(); 
    } 
    catch(\Exception $e) { 
     return new JsonResponse('error'); 
    } 

    return new JsonResponse('success'); 

} 

私はenabledChange機能するためのユーザーIDに対応する設定と変更が依存状態を確認することができますどのように質問

ユーザーst食べた?

+0

現在のコードではどのような問題がありますか? –

+0

@alokpatelエラーが発生しました:パラメータ%user.idを{user%}のユーザの%%の外にchangePathに設定しているため、 '変数'ユーザが@ Admin/UserPanel/index.html.twigに存在しません – blahblah

+0

'内部で 'var changePath'関数を定義し、渡されたパラメータを使用しました。 –

答えて

2

あなたの変数に引用符を追加し、引数としてchangePathを渡す必要があります:

onclick="enabledChange('{{ user.id }}', '{{ path('user_enable_change', {'id': user.id}) }}')" 

その後:

function enabledChange(id, changePath) { 
    var value = $(this).val(); 
    console.log('value: ' + value); 
    $.ajax({ 
     type: "POST", 
     url: changePath, 
     async: true, 
     data: { }, 
     success: function() { 
      console.log('success'); 
     } 
    }); 
} 

私はこれが役立つことを願っています。

関連する問題