2015-08-04 2 views
0

В моем контроллере у меня есть действие:Добавить кнопку в целях Symfony без многократного использования типа формы

/** 
    * @Route("/admin/tour/approve/{id}",name="approve_one_tour") 
    */ 
    public function approveOneTourAction($id,Request $request) 
    { 
     $tour=$this->getDoctrine()->getRepository('HearWeGoHearWeGoBundle:Tour')->findById($id); 

     if ($request=='POST') 
     { 
      $tour->setStatus(true); 
      $em=$this->getDoctrine()->getEntityManager(); 
      $em->persist($tour); 
      $em->flush(); 
      return $this->redirectToRoute('manage_tour'); 
     } 
     else { 
      return $this->render('@HearWeGoHearWeGo/Manage/tour/approveonetour.html.twig', array('tour' => $tour)); 
     } 
    } 

В Виде:

{% extends('admin/admin.html.twig') %} 

{% block mainpageheader %} 
    <h1 class="page-heading">APPROVE TOUR</h1> 
{% endblock %} 


{% block mainpagecontainerheader %} 
    <h3 class="block-title">Approve {{ tour.name }}</h3> 
{% endblock %} 

{% block mainpagecontainer %} 
    <div class="block"> 
     <div class="block-content"> 
      <table class="table"> 
       <thead> 
       <tr> 
        <th class="text-center" style="width: 50px;">#</th> 
        <th style="width:15%">Name</th> 
        <th style="width:15%">Company</th> 
        <th style="width:15%">Destination</th> 
        <th style="width:20px">Start Date</th> 
        <th style="width:20px">End Date</th> 
        <th>Price</th> 
        <th>Discount</th> 
        <th style="width:40%">Info</th> 
        <th style="width:20px">Submission Date</th> 
       </tr> 
       </thead> 
       <tbody> 
        <tr> 
         <td class="text-center">{{ tour.id }}</td> 
         <td>{{ tour.name }}</td> 
         <td>{{ tour.company.name }}</td> 
         <td>{{ tour.destination.name }}</td> 
         <td>{{ tour.startdate|date('Y-m-d') }}</td> 
         <td>{{ tour.enddate|date('Y-m-d') }}</td> 
         <td>{{ tour.price }}</td> 
         <td>{{ tour.discount }}</td> 
         <td>{{ tour.info|raw }}</td> 
         <td>{{ tour.createdAt|date('Y-m-d') }}</td> 
        </tr> 
       </tbody> 
      </table> 
      <form action="{{ path('approve_one_tour',{'id':tour.id}) }}" method="POST"> 
       <input type="submit" class="btn btn-primary" value="Approve"/> 
      </form> 
     </div> 
    </div> 
{% endblock %} 

Когда кнопка нажата, ничего не происходит

Поскольку я хочу показать данные объекта-объекта Tour, не разрешайте пользователю редактировать его, поэтому я думаю, что мне не нужно создавать тип формы, который добавляет редактируемые и повторно используемые атрибуты. Единственное, что мне нужно, это кнопка, когда я нажимаю кнопку, единственным атрибутом Tour требуется изменение объекта status, от false (по умолчанию) до true. Там в любом случае? Если есть, пожалуйста, помогите исправить мой код выше

+0

почему это, что ваш метод форма POST? – aizele

+0

О, извините, я ошибся Это должно было быть 'if ($ request-> getMethod() == 'POST')' После того, как я исправил это, он работает плавно, остальные остаются одинаковыми В любом случае, спасибо вы! – necroface

ответ

0

Прежде всего используйте $request->getMethod()== вместо $request, если вы хотите проверить способ запроса.
Вы можете создать форму только с кнопкой отправки.

//in your controller 
protected function createForm(){ 
    $ff = $this->get('form.factory'); // get the form factory service, or inject it in 
    $builder = $ff->createBuilder('form'); 
    $builder->add('submit', 'submit'); 

    return $builder->getForm(); 
} 

public function approveOneTourAction(Request $request, $id){ 
    $form = $this->createForm(); 
    $form->handleRequest($request); 
    if($form->isValid() && $form['submit']->isClicked()){ 
    // ... do what you want with the tour here 
    } 

    return $this->render('@HearWeGoHearWeGo/Manage/tour/approveonetour.html.twig', array('tour' => $tour, 'form' => $form->createView())); 

} 

Затем делают вид, передаваемый в качестве form в шаблон, как описано в Symfony forms Documentation

+0

О, извините, я ошибся Это должно было быть 'if ($ request-> getMethod() == 'POST')' После того, как я исправил это, он работает плавно, остальные остаются одинаковыми В любом случае, спасибо вы! – necroface

Смежные вопросы