Symfony embed edit controller not working - forms

I'm trying to have an edit form in a modal but this edit form is not working in the context.
It is working when I try the form directy in a webpage using the URI address but it is not when I try it in my page context. I'm gonna explain more ...
In my webpage, I have a render controller :
<div class="card">
<div class="body">
{{ render(controller('AppBundle:Classeur3:vacation', {'request':app.request , 'id': zone.id})) }}
</div>
</div>
This controller retrieve somme Entities and display a table as following :
<table id="sites-list" class="table table-bordered datatable">
<thead>
<tr>
<th>Employé</th>
<th>Heure d'entrée</th>
<th>Heure de sortie</th>
<th>Durée</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for v in vacations %}
<tr id="tr-vacation-{{ v.id }}">
<td>{{ v.user }}</td>
<td>{{ v.entryTime|date }}</td>
<td>{{ v.exitTime|date }}</td>
<td>{{ v.totalTime }}</td>
<td style="width: 150px;">
<button onclick="$('#modal').modal({remote: '{{ path('edit_vacation', {'id': v.id}) }}' });" type="button" class="btn btn-circle waves-effect waves-circle waves-float" style="margin-right: 5px;">
<i class="material-icons">search</i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
My edit_vacation ressource is defined bby the following route :
edit_vacation:
path: /vacation/{id}/edit
defaults: { _controller: AppBundle:Classeur3:editVacation }
This is my controller function :
public function editVacationAction(Request $request, $id){
$vacation = $this->getDoctrine()->getRepository(Answ31Vacation::class)->find($id);
$form = $this->createForm(Answ31VacationType::class, $vacation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($vacation);
$entityManager->flush();
//Message
$this->addFlash('success', 'Vacation mise à jours');
//Redirect to Zone edit page
return $this->redirectToRoute('zone_edit', array('id' => $vacation->getZone()->getId()));
}
return $this->render('AppBundle:Classeur3:edit_vacation.html.twig', array(
"form" => $form->createView()
));
}
And here is my view :
<div class="modal-body">
<div class="row">
<div class="col-sm-12">
{{ form(form) }}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">Fermer</button>
</div>
The modal is perfectly displayed, but when I submit the form, the page is reloaded as planed but the data are not updated.
When I try to call directly in URL my ressource ( baseurl/vacation/1/edit ) I have the form and the modifications are working, when I press my submit button the data are updated.
Any thought ?

In your editVacationAction you should try setting the target action of your form, like this
$form = $this->createForm(Answ31VacationType::class, $vacation, ["action"=>$this->generateUrl('edit_vacation']);
But when you submit, the page will change and you will loose the modal without some extra JavaScript.

Related

symfony 3.4 pass variable to a modal in twig

I need help to solve my problem. I have a page with my list of "equipos". Every "equipo" in the table has an Edit buttom, and the page show another buttom to add new "equipos".
So far I manage to call a modal for NEW using the {{ render() }} syntax, the equipoNewModal works fine because is an "static" route (/equipo/new) in Symfony; but the EDIT don't work because I can't pass the "equipo" variable to the equipoEditModal and get the id to complete the route (/equipo/{id}/edit) and call the controller.
Symfony can't render the page and return an error: Variable "equipo" does not exist.
The controller isn't the problem, if I create an tag with href={{ path('edit_equipo', {'id': equipo.id}) }} in the list.html.twig template and skip the modal I can edit every equipo. To dismiss the controller, if I hardcoded the line:
{{ form_start(equipoForm, {'action': path('edit_equipo', {'id': equipo.id})}) }}
in the edit.html.twig to:
{{ form_start(equipoForm, {'action': path('edit_equipo', {'id': 1})}) }}
the edit action works, of course for every equipo the edit action call the edition of the item with id=1 in the database, but it say that the controller works fine.
I'm missing something and hope the community find the solution... sorry my english.
==============
list.html.twig
<table id="datatable-buttoms" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>EQUIPOS</th>
</tr>
</thead>
<tbody>
{% for equipo in equipos %}
<tr>
<td>{{ equipo.id }}</td>
<td>{{ equipo.equipo }}</td>
<td>{{ equipo.nomenclador }}</td>
<td>{{ equipo.nomenclador.especialidad }}</td>
<td>
<button type="button" class="btn btn-primary" href="" data-toggle="modal" data-target="#equipoEditModal">
Editar
</button>
<button type="button" class="btn btn-danger" href="" data-toggle="modal" data-target="#equipoDeleteModal">
Eliminar
</button>
</td>
</tr>
{{ render(controller('AppBundle:Equipo:edit', {'id': equipo.id})) }}
{% endfor %}
</tbody>
</table>
<button type="button" class="btn btn-primary" href="" data-toggle="modal" data-target="#equipoNewModal">
Agregar
</button>
{{ render(controller('AppBundle:Equipo:new')) }}
=============
new.html.twig
<div class="modal fade" id="equipoNewModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">NUEVO</h4>
</div>
<div class="modal-body">
{{ form_start(equipoForm, {'action': path('new_equipo')}) }}
{{ form_widget(equipoForm) }}
<button type="submit" class="btn btn-primary">Guardar</button>
{{ form_end(equipoForm) }}
</div>
</div>
</div>
</div>
==============
edit.html.twig
<div class="modal fade" id="equipoEditModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">EDITAR</h4>
</div>
<div class="modal-body">
{{ form_start(equipoForm, {'action': path('edit_equipo', {'id': equipo.id})}) }}
{{ form_widget(equipoForm) }}
<button type="submit" class="btn btn-primary">Guardar</button>
{{ form_end(equipoForm) }}
</div>
</div>
</div>
</div>
===============
Edit Controller
/**
* #Route("/equipo/{id}/edit", name="edit_equipo")
*/
public function editAction(Request $request, Equipo $equipo)
{
$form = $this->createForm(EquipoFormType::class, $equipo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$equipo = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($equipo);
$em->flush();
return $this->redirectToRoute('list_equipos');
}
return $this->render('sysreport/equipos/edit.html.twig', [
'equipoForm' => $form->createView(),
]);
}
EDIT:
To solve the problem only add the line that #Nobady says in the editAction controller...
To call every modal depending of the equipo change data-target in the list.html.twig file:
<button type="button" class="btn btn-primary" href="" data-toggle="modal" data-target="#equipo{{ equipo.id }}">
and of course in the edit.html.twig file too:
<div class="modal fade" id="equipo{{ equipo.id }}">
to solve then you have to pass equipo as parameter, like this in Edit Controller:
/**
* #Route("/equipo/{id}/edit", name="edit_equipo")
*/
public function editAction(Request $request, Equipo $equipo)
{
$form = $this->createForm(EquipoFormType::class, $equipo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$equipo = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($equipo);
$em->flush();
return $this->redirectToRoute('list_equipos');
}
return $this->render('sysreport/equipos/edit.html.twig', [
'equipoForm' => $form->createView(),
'equipo' => $equipo
]);
}

Flask redirect not working with form submitted via POST

I'm trying to submit the form -- which appears at the bottom of my books.html page (see relevant html below) -- to a /reviews route, which has a return redirect(url_for('reviews')) statement in it. On form submission, however, I receive a 405 Method Not Allowed Error.
I checked other posts and discovered that, yes, redirect works with the POST method, cross-checked my methods for the submission of forms required to reach the /books and /reviews routes, plus their form action attributes and methods associated therewith. All seemed fine. I still cannot unearth the error.
The desired behavior is that users submit a review via the form on the /books page below, and the page updates and displays the review, rating, and avg. rating. The logic in the /reviews route should do the processing and updating.
{% extends "layout.html" %}
{% block body %}
<div>
<table class="table">
<thead>
<tr>
<th><strong>Username</strong></th>
<th><strong>Review</strong></th>
<th class="text-center"><strong>Rating</strong></th>
</tr>
</thead>
{% for review in reviews %}
<tr>
<td>{{ review.username }}</td>
<td>{{ review.reviews }}</td>
<td class="text-center">{{ review.rating }}</td>
</tr>
{% endfor %}
<tfoot>
<tr>
<th>Average Rating</th>
<td colspan="1"></td>
<td class="text-center">{{ avg_rating }}</td>
</tr>
</tfoot>
</table>
</div>
<form action="{{ url_for('reviews') }}" method="post">
<fieldset>
<div class="form-group">
<div class="form-inline">
<label class="mr-3">Rate This Title & Write a Review</label>
<label class="mr-3 form-check-label">
<input type="radio" class="form-check-input" name="bookrating" id="onestar" value="1">
<i class="fas fa-star"></i>
</label>
</div>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="userreview" type="text"/>
<input autocomplete="off" autofocus class="form-control" name="bookid" value="{{ books.id }}" type="hidden"/>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</fieldset>
</form>
{% endblock %}
#app.route("/reviews", methods=["POST"])
#login_required
def reviews():
book_id = request.form.get("bookid")
register_id = session["user_id"]
books = db.execute("SELECT * FROM books WHERE id = :id", {"id": book_id}).fetchone()
reviews = db.execute("SELECT register.username, reviews, rating FROM reviews JOIN register ON reviews.book_id = :id AND reviews.user_id = register.id", {"id": book_id})
avg_rating = db.execute("SELECT ROUND(AVG(rating),0) FROM reviews WHERE book_id = :book_id", {"book_id": book_id}).scalar()
user_reviews = db.execute("SELECT * FROM reviews WHERE user_id = :id AND book_id = :book_id", {"id": register_id, "book_id": book_id}).fetchone()
if not user_reviews:
target_review = request.form.get("userreview")
db.execute("INSERT INTO reviews (book_id, reviews, user_id) VALUES (:book_id, :reviews, :user_id)", {"book_id": book_id, "reviews": target_review, "user_id": register_id})
db.commit()
return redirect(url_for('reviews'))
else:
return render_template("books.html", books=books, reviews=reviews)
Can you try and add "GET" to your methods:
#app.route("/reviews", methods=["GET", "POST"])
#login_required
def reviews():
book_id = request.form.get("bookid")
register_id = session["user_id"]
Could be that the implementation of redirect in flask changes the request to a GET request and your reviews route does not allow it
It's because you want to redirect to reviews function (which is route /reviews). But your methods only post. I believe that redirect need GET methods to load some page.

Flask SQLAlchemy inserts null value for text field in PostgreSQL despite text

The commands in the books() method are based on code that already works. The INSERT INTO statement is the problem. When the HTML form is submitted (bottom of screen) the userreview in the input field text box is not pulled by my books() method and inserted into my postgres DB, despite the presence of text. To check whether or not anything from the HTML page was being pulled in properly, I tested the hidden book_id, and it was pulled by the books() method and inserted, as expected, into the DB.
Any idea why this would steadfastly refuse to pull text from an input field into my method and insert it into my DB?
#app.route("/books", methods=["POST"])
#login_required
def books():
book_id = request.form.get("bookid")
review = request.form.get("userreview")
db.execute("INSERT INTO test (review, bookid) VALUES (:review, :bookid)", {"review": review, "bookid":book_id})
db.commit()
{% block body %}
<div>
<table class="table">
<thead>
<tr>
<th><strong>Username</strong></th>
<th><strong>Review</strong></th>
<th class="text-center"><strong>Rating</strong></th>
</tr>
</thead>
{% for review in reviews %}
<tr>
<td>{{ review.username }}</td>
<td>{{ review.reviews }}</td>
<td class="text-center">{{ review.rating }}</td>
</tr>
{% endfor %}
</table>
</div>
<form action="{{ url_for('books') }}", method="post">
<div class="form-group">
<input name="userreview" type="text" class="form-control" id="bookreview">
<input type="hidden" name="bookid" value="{{ books.id }}" />
</div>
<button type="button" class="btn btn-primary">Submit</button>
</form>
This HTML works just fine, though I have yet to figure out what part of the markup made the difference. I thought it was the errant comma in the above code <form action="{{ url_for('books') }}", method="post">, but that makes no difference.
<form action="{{ url_for('books') }}" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form control" name="userreview" type="text"/>
</div>
<div class="form-group">
<input autocomplete="off" autofocus class="form control" name="bookid" value="{{ books.id }}" type="hidden"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Submit</button>
</div>
</fieldset>
</form>

Generated <form> inside Bootstrap-Modal needs to have a unique ID

Well, I searched the whole Internet the last days to find a way to attach an unique ID and/or name to a GENERATED form inside a Bootstrap-Modal and I never succeeded...
I know I'm making mistakes in the code, but I ran out of ideas, I don't know what to use.
*Edit: I'm using Bootstrap 3, I created a table, having a live search field using JavaScript. The table rows are displayed from a database using a query. The last column of the row pops up a Bootstrap-Modal inside which a form is located, now here is the problem! I managed to assign a unique ID to each Modal and each Modal popup button, but the form! From here everything is mist.
Here is the code:
<div id="fm-<?php echo $row['PacientID']; ?>" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
<b>
Fișa medicală #<?php echo $row['PacientID']; ?>: <?php echo $row['Name'].' '.$row['Surname']; ?>
</b>
</h4>
<?php
if (isset ($entranceSuccess))
{
?>
<div class="alert alert-success text-center">
<?php echo $entranceSuccess; ?>
</div>
<?php
}
?>
<?php
if (isset ($entranceError))
{
?>
<div class="alert alert-danger text-center">
<?php echo $entranceError; ?>
</div>
<?php
}
?>
</div>
<form data-toggle="validator" id="entranceForm" role="form" method="POST">
<div class="modal-body">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center">Data Intrării</th>
<th class="text-center">Medic Stomatolog</th>
<th class="text-center">Tratament</th>
<th class="text-center">Achitat</th>
</tr>
</thead>
<tbody>
<?php
$intrari = "SELECT * FROM intrari";
$intrariResults = $db -> query($intrari);
while ($row2 = $intrariResults -> fetch_assoc())
{
if ($row2['Pacient'] == $row['PacientID'])
{
?>
<tr class="text-center">
<th scope="row" class="text-center">
<?php echo $row2['EntranceDate'];?>
</th>
<td>
<?php
if ($row2['Medic'] == 1)
{
echo 'Dr. Carmen Pădurean';
}
else if ($row2['Medic'] == 2)
{
echo 'Dr. Claudiu Șuc';
}
else if ($row2['Medic'] == 3)
{
echo 'Dr. Mihaela Toncean';
}
else if ($row2['Medic'] == 4)
{
echo 'Dr. Alexandra Cenan';
}
else
{
echo 'MEDICUL STOMATOLOG NU A FOST DEFINIT!';
}
?>
</td>
<td>
<?php echo $row2['Treatment'];?>
</td>
<td>
<?php echo $row2['Achitat'];?>
</td>
</tr>
<?php
}
}
?>
<tr>
<th scope="row" class="text-center">
<div class="form-group">
<div class="input-group date entranceDateField">
<input type="text" class="form-control" id="entranceDate" name="entranceDate">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</th>
<td>
<div class="form-group">
<select class="form-control" id="medic" name="medic">
<option value="1">Dr. Carmen Pădurean</option>
<option value="2">Dr. Claudiu Șuc</option>
<option value="3">Dr. Mihaela Toncean</option>
<option value="4">Dr. Alexandra Cenan</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="treatment" name="treatment">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="achitat" name="achitat">
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="addEntrance" name="addEntrance-<?php echo $row['PacientID'];?>">
<span class='glyphicon glyphicon-plus'></span> Adaugă Intrare
</button>
<?php
if (isset ($_POST['addEntrance-<?php echo $row[PacientID]; ?>']))
{
$entranceDate = $_POST['entranceDate'];
$pacient = $row['PacientID'];
$medic = $_POST['medic'];
$treatment = $_POST['treatment'];
$achitat = $_POST['achitat'];
$insertEntrance = "INSERT INTO intrari (EntranceDate, Pacient, Medic, Treatment, Achitat)
VALUES ('$entranceDate', '$pacient', '$medic', '$treatment', '$achitat')";
if (mysqli_query ($db, $insertEntrance))
{
$entranceSuccess = "Pacientul a fost adăugat în baza de date cu succes!";
}
else
{
$entranceError = "A apărut o eroare nedefinită! Suna-l pe Andrei (0755 696 200) și dictează-i: \"Error code: " . mysqli_error ($db) . "\"";
}
}
?>
</div>
</form>
</div>
</div>
By looking at your code, I see you are putting Modal HTML inside loop and by assigning unique id's to modal selector id="fm-<?php echo $row['PacientID']; ?>" trying to create multiple modals with unique id(s), it will cause the page to load slow and running queries inside each unique modal fetching the records from database when even you don't need fetched records on page load, it's not a good practice,
so let's go one step backward and remove the Modal from while loop and put it outside and remove <?php echo $row['PacientID']; ?> from Modal id selector.
<div id="fm" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
//Modal-Header, Modal-Body, Modal-Footer Comes Here
</div>
</div>
</div>
Now as you stated The last column of the row pops up a Bootstrap-Modal
Assuming you are triggering the modal with default behaviour with data attributes data-toggle="modal" data-target="#fm" and you have other information in other columns of rows like <?php echo $row['Name'].' '.$row['Surname']; ?> so you must have something like
<tr>
<td><?php echo $row['PacientID']; ?></td>
<td><?php echo $row['Name'].' '.$row['Surname']; ?></td>
<td><button type="button" class="btn btn-info" data-toggle="modal" data-target="#fm">Open Modal</button></td>
</tr>
Now Let's pass the pacientid and name to modal, Add data-attribute data-pacient to name col and to modal trigger button so above table col's will be
<tr>
<td><?php echo $row['PacientID']; ?></td>
<td><span class="pacientname" data-pacient="<?php echo $row['PacientID']; ?>"><?php echo $row['Name'].' '.$row['Surname']; ?></span></td>
<td><button type="button" data-pacient="<?php echo $row['PacientID']; ?>" class="btn btn-info" data-toggle="modal" data-target="#fm">Open Modal</button></td>
</tr>
With bootstrap modal event listener, you can pass the information to modal when modal about to show or shown
$(document).ready(function(){ //Dom Ready
$('#fm').on('show.bs.modal', function (e) { //Show event listener
var id = $(e.relatedTarget).data('pacient'); //Fetch val from modal data-attribute
var name = $('.pacientname[data-pacient="' + id +'"]').html(); //fetch val from selector `pacientname` data-attribute with match the val of modal button data-attribute
$(".pid").html(id); //selector inside modal header to pass id
$(".pname").html(name); //selector inside modal header to pass name
$("#addEntrance").val(id); //Passing id to hidden input in form, explained below
//Ajax method comes here which explains below
});
});
Modal-Header
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="pid"></span> <span class="pname"></span></h4>
</div>
Fiddle Example to pass information to modal
Now about the query you are running inside modal, it can be done via Ajax method and display the information in modal. As we already have the required variable var id = $(e.relatedTarget).data('pacient'); can use it to fetch the required information via Ajax method
var dataString = 'id='+ id;
alert(dataString);
$.ajax({
type: "POST",
url: "file.php", //Create this file and handle query in it.
data: dataString,
cache: false,
success: function (data) {
$("#morecontent > tbody.showHere").html(data); //show fetched information from database
}
});
and file.php will be
<?php
//Database Connection Here
if(isset($_POST["id"])) {
$id = $_POST["id"]; //escape the string
$queryIntrari = "SELECT * FROM intrari WHERE Pacient = '$id'";
$intrariResults = $db -> query($queryIntrari);
while ($row2 = $intrariResults -> fetch_assoc()){
?>
<tr class="text-center">
<th scope="row" class="text-center">
<?php echo $row2['EntranceDate'];?>
</th>
<td>
<?php
if ($row2['Medic'] == 1)
{
echo 'Dr. Carmen Pădurean';
}
else if ($row2['Medic'] == 2)
{
echo 'Dr. Claudiu Șuc';
}
else if ($row2['Medic'] == 3)
{
echo 'Dr. Mihaela Toncean';
}
else if ($row2['Medic'] == 4)
{
echo 'Dr. Alexandra Cenan';
}
else
{
echo 'MEDICUL STOMATOLOG NU A FOST DEFINIT!';
}
?>
</td>
<td><?php echo $row2['Treatment'];?></td>
<td><?php echo $row2['Achitat'];?></td>
</tr>
<?php } } ?>
and the Modal-body, Modal-Footer with form and information fetched from database using Ajax will be like
<table class="table table-hover table-bordered" id="morecontent">
<form data-toggle="validator" id="entranceForm" role="form" method="POST">
<input type="hidden" id="addEntrance" name="addEntrance" value="">
<div class="modal-body">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center">Data Intrării</th>
<th class="text-center">Medic Stomatolog</th>
<th class="text-center">Tratament</th>
<th class="text-center">Achitat</th>
</tr>
</thead>
<tbody class="showHere">
//Information Fetched from Database Using Ajax will show Here
</tbody>
<tbody>
<tr>
<th scope="row" class="text-center">
<div class="form-group">
<div class="input-group date entranceDateField">
<input type="text" class="form-control" id="entranceDate" name="entranceDate">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</th>
<td>
<div class="form-group">
<select class="form-control" id="medic" name="medic">
<option value="1">Dr. Carmen Pădurean</option>
<option value="2">Dr. Claudiu Șuc</option>
<option value="3">Dr. Mihaela Toncean</option>
<option value="4">Dr. Alexandra Cenan</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="treatment" name="treatment">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" id="achitat" name="achitat">
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">
<span class='glyphicon glyphicon-plus'></span> Adaugă Intrare
</button>
</div>
</form>
Note: Created a hidden input in <form> above, passed the value <?php echo $row['PacientID']; ?> to the hidden input when modal show, Post this hidden input along with other inputs when submitted the form in modal to insert or update values into database
an example here
Mission accomplished and hope you figure it out how to pass and get information in modal
Note: You can submit the modal form either the way you are doing or can also do it with Ajax and show success or error message inside modal without closing it and leaving the page but that's another story to tell some other time.
Happy Coding.

Submit button in Symfony view without a reusable form type

In my Controller I have an action:
/**
* #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));
}
}
In View:
{% 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 %}
When the button is clicked, nothing happens
Because I only want to show the data of a Tour entity object, not allow the user to edit it, so I think I needn't create a Form Type that adds editable and reusable attributes. The only thing I need is a button, when I click the button, the only attribute of Tour entity needs changing is status, from false (default) to true. Is there any way? If any, please help fix my code above
First of all use $request->getMethod()== instead of $request if you want to check the request method.
You can create a form with just a submit button like so.
//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()));
}
Then render the form passed as form to your template as explained in Symfony forms Documentation