render a twig template on condition - php

In my page show.html.twig i have this block
<div class="col-md-9 col-sm-9 user-wrapper">
<div class="description">
{{ render(controller('FLYBookingsBundle:Post:new')) }}
</div>
</div>
As you can see there is a render that render the page new.html.twig, i want to render the page product << {{ render(controller('FLYBookingsBundle:Post:product')) }} >> in the div description only if the user click on the link My Product List . how do i do that with twig ?

Here is the solution I used to "pop-up" a form for sending an e-mail to an entity based on a button appearing with that entity.
You will need to install jquery if not already installed. There are many possible ways to do this. Use your pal Google & "symfony install jquery" to find one. You may also want to find a good javascript debugger for your browser. I use the Firebug add-on in Firefox.
Template with link (edited for brevity). The returned e-mail form appears in <div id="dialog"></div>:
<div id="dialog"></div>
{% for opp in opportunities %}
<div class="row">
<div class="col-md-9">
<ul class="list-unstyled">
...
<li><a href="#" value="{{ opp.id }}" id="emailOrganization" class="btn btn-xs btn-info" >E-mail {{ opp.orgName }}</a>
</ul>
</div>
</div>
{% endfor %}
Javascript:
$(document).on("click", "#emailOrganization", function () {
var where = $(location).attr('pathname');
var id = $(this).attr("value");
//replaces URI ending in 'search' with 'oppForm/' + id (of organization)
var url = where.replace('search', 'oppForm/' + id);
$.get(url, function (data) {
//creates dialog box containing e-mail form
$('#dialog').dialog();
$('#dialog').dialog({
modal: true,
buttons: [
{
text: "Send",
id: "send",
class: "btn-xs btn-primary",
click: function () {
var formData = $("form").serialize();
$.post(url, formData, function (response) {
if (response.indexOf("Email sent") >= 0) {
$("#send").hide();
}
$('#dialog').html(response);
})
}
},
{
text: 'Close',
id: "close",
class: "btn-xs btn-primary",
click: function () {
$(this).dialog("close");
}
}
],
resizable: true,
});
$('#dialog').dialog("widget").find(".ui-dialog-titlebar").hide();
$('#dialog').html(data);
});
});
Controller (edited for brevity)
/**
* #Route("/oppForm/{id}", name="opp_form")
* #Template("default/oppEmail.html.twig")
*/
public function oppFormAction(Request $request, $id)
{
...
$form = $this->createForm(new OpportunityEmailType($oppName, $orgName, $email, $id));
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isValid()) {
...
}
$response = new Response("Email sent: " . count($to));
return $response;
}
}
return [
'form' => $form->createView(),
'id' => $id,
];
}
Template:
<form role="form" action="{{ path('opp_form', {'id': id}) }}" method="post" name="opp_email">
{# hidden submit button allows functional test; also tested with codeception #}
<div style="visibility: hidden;"><input type="submit" value="Mail"></div>
{{ form_widget(form._token) }}
{{ form_row(form.id) }}
{{ form_row(form.to) }}
{{ form_row(form.from) }}
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</form>

Related

Get the file object in the form's controller, from a javascript array collection prototype in Symfony 5

Here is what i'm trying to do :
I have a classic Folder entity which contains Sku entities in a OneToMany relation as an ArrayCollection. So far so good.
I want the FolderType to dynamically create as many Skus as I want in it. For that, I followed the Symfony fast track method to generate prototypes in javascript. Works great.
Now, in this folder form, "skus" are an array collection of entities. In the SkuType, I have files to uploads. Here are the forms (Folder and Sku) :
$builder
->add('norlogReference', TextType::class, [
'label' => 'Référence du dossier'
])
->add('skus', CollectionType::class, [
'entry_type' => SkuType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'prototype' => 'skus'
]);
As for the SkuType, here are my upload fields :
->add('picture_1', FileType::class, [
'label' => 'Image 1 du produit',
'mapped' => false,
'required' => false,
'attr' => ['accept' => 'image/*']
])
->add('picture_2', FileType::class, [
'label' => 'Image 2 du produit',
'mapped' => false,
'required' => false,
'attr' => ['accept' => 'image/*']
])
Here is the controller recieving the form :
/**
* #Route("/new", name="folder_new")
*/
public function new(Request $request): Response
{
$entityManager = $this->getDoctrine()->getManager();
$norlogFolder = new NorlogFolder();
$form = $this->createForm(NorlogFolderType::class, $norlogFolder);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
foreach ($norlogFolder->getSkus() as $sku) {
I want to get both file objects here, pass them in handleUploadedFile(), and use $sku->setPicture1() and setPicture2 with the $newfileName returned by the private method.
$sku->setFolder($norlogFolder);
$sku->setSKU($norlogFolder->getNorlogReference() . '-' . $sku->getSKU());
}
$entityManager->persist($norlogFolder);
$entityManager->flush();
return $this->redirectToRoute('folder_edit', ['id' => $norlogFolder->getId()]);
}
return $this->render('folder/new.html.twig', [
'form' => $form->createView(),
]);
}
and the little private method I want to use in order to handle the file :
private function handleUploadedFile(UploadedFile $uploadedFile): string
{
$destination = $this->getParameter('kernel.project_dir').'/public/uploads/sku_medias';
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $uploadedFile->guessExtension();
$uploadedFile->move(
$destination,
$newFilename
);
return $newFilename;
}
And the folder form view :
{{ form_start(form, {
attr: {
class: 'sku-form'
}
}) }}
<div class="form-group">
{{ form_row(form.norlogReference, {
attr: {
placeholder: 'ex: XOTP-25',
class: 'sku-form-input'
}
}) }}
</div>
<div class="form-group sku-row skus" data-prototype="{{ form_widget(form.skus.vars.prototype)|e('html_attr') }}">
{% if form.skus|length > 0 %}
{% for sku in form.skus %}
<div class="row sku-bloc bg-light">
<div class="field-title">
<p class="display-3 text-center">Produit #{{ loop.index }}</p>
<a href="{{ path('sku_delete', {id: sku.vars.data.id}) }}"
class="btn bg-danger btn-sku-remove"><i class="fas fa-trash-alt"></i></a>
</div>
<span class="btn btn-secondary form-extend-btn">Voir</span>
<div class="col-12 sku-fields-bloc">
<div class="form-control">
{{ form_row(sku.SKU, {
attr: {
placeholder: 'ex: XVF-25663',
class: 'sku-form-input'
}
}) }}
</div>
<div class="container">
<div class="row">
{{ form_label(sku.marque) }}
{{ form_widget(sku.marque, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.taille) }}
{{ form_widget(sku.taille, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.designation) }}
{{ form_widget(sku.designation, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.couleur) }}
{{ form_widget(sku.couleur, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.etat) }}
{{ form_widget(sku.etat, {
attr: {
class: 'sku-form-input'
}
}) }}
{{ form_label(sku.composition) }}
{{ form_widget(sku.composition, {
attr: {
class: 'sku-form-input'
}
}) }}
</div>
</div>
<div class="form-control mt-3">
{{ form_row(sku.picture_1, {
attr: {
placeholder: 'Image 1',
class: 'sku-form-input'
}
}) }}
</div>
<div class="form-control mt-3">
{{ form_row(sku.picture_2, {
attr: {
placeholder: 'Image 2',
class: 'sku-form-input'
}
}) }}
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="row">
<div class="col-12 mt-4">
<p class="p-3 bg-info">Pas encore de {{ form_label(form.skus) }} ajoutés</p>
{{ form_widget(form.skus) }}
</div>
</div>
{% endif %}
</div>
<div class="row">
<div class="col-4">
<button type="button" class="btn btn-primary btn-nav w-100 mt-2 mb-2 add_item_link"
data-collection-holder-class="skus">
Ajouter Sku
</button>
</div>
<div class="col-4">
<button type="submit"
class="btn btn-success btn-nav w-100 mt-2 mb-2">{{ button_label|default('Enregistrer') }}</button>
</div>
<div class="col-4">
<a href="{{ path('folder_list') }}"
class="btn btn-primary btn-nav w-100 mt-2 mb-2">Retour liste</a>
</div>
</div>
{{ form_end(form) }}
So the question is : how to get these picture_1 and 2 objects (and not path which I already have by remapping them to true), by Sku, in the controller side, in order to handle the files as usual ?
I tried :
$request->files->get() (result = null, and I have the enctype right in the form)
$sku->getPicture_1() (result = temporary linux path, but is there a simple way to retrieve the file from that, and on every OS ?)
Trying to access the $form from inside the sku loop (result = nada)
$request->get('picture_1') and that + ->getData()
Various weird tries I forgot which gave me nothing
I might miss something obvious here, but I can't think properly on this project anymore.
Please don't mind the necessary refactoring for now =) Ty !
With 'mapped' => false, you need to handle the collection of uploads like this:
if ($form->isSubmitted() && $form->isValid()) {
foreach ($form->get('skus') as $formChild)
{
// Get the unmapped picture fields
$uploadedPicture1 = $formChild->get('picture_1')->getData();
$uploadedPicture2 = $formChild->get('picture_2')->getData();
// Get the sku
$sku = $formChild->getData();
// Upload the pictures
$picture1Filename = $this->handleUploadedFile($uploadedPicture1);
$picture2Filename = $this->handleUploadedFile($uploadedPicture2);
// Set the new filenames onto the sku
$sku->setPicture1($picture1Filename);
$sku->setPicture2($picture2Filename);
// Your original code
$sku->setFolder($norlogFolder);
$sku->setSKU($norlogFolder->getNorlogReference() . '-' . $sku->getSKU());
}
}
$entityManager->persist($norlogFolder);
$entityManager->flush();
return $this->redirectToRoute('folder_edit', ['id' => $norlogFolder->getId()]);
}
Edit: do check if a picture was actually uploaded, as in the other answer. :-)
Your picuter_1 and picture_2 are mapped: false.
That means, you have to use ->getData() (or maybe ->getNormData()) on each SkuType or your NorlogFolderType
instead of looping through SKUs entities collection, loop through sku formtypes and get the data directly from 'picture_1' and 'picture_2' field
if ($form->isSubmitted() && $form->isValid())
{
if ($form->has('skus'))
{
foreach ($form->get('skus') as $skuForm)
{
// always check if field named 'picture_1' is there
if ($skuForm->has('picture_1'))
{
/** #var \Symfony\Component\HttpFoundation\File\UploadedFile $firstPic */
$firstPic = $skuForm->get('picture_1')->getData();
//todo: maybe check if null
$picOne = $this->handleUploadedFile($firstPic);
}
// do the same with picture_2 (and others if any)
}
}
}

Refresh table after request Ajax is success

I am beginner with Ajax. I try refresh a table when user select an option in form-select filter. I use Symfony and Twig.
I get the new datas in the Json format in my console when i select a new filter, but the table does'nt show with the new datas. I failed to find the solution when my request ajax is success.
My Select filter :
{{ form_start(form) }}
<div class="container-fluid">
<div class="row">
<div class="col-fluid">
{{ form_row(form.isAttending) }}
</div>
<button type="submit" class="btn btn-outline-success mb-2">{{ button_label|default('Envoyer') }}</button>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-1-fluid">
{{ form_row(form.active) }}
</div>
</div>
</div>
{{ form_end(form) }}
In my Controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200);
}
}
In my Template :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
Any ideas ?
According to your question and comments your problem is not Symfony, not Ajax and also not Twig related. You get the correct data and you just do not know how to manipulate the DOM. DOM manipulation is a basic capability of JavaScript.
Here you can learn how to manipulate the DOM: https://www.w3schools.com/js/js_htmldom.asp
And here you can learn how to easily can manipulate it with jQuery which you are obviously using: https://www.w3schools.com/js/js_jquery_dom.asp
Sample:
$('#my-table').append(response.myWhatever);

Easy admin bundle modal dialog for custom action?

I'm working with Easy Admin Bundle for Symfony2. How can I use my own modal dialog with text input for the custom action in the list?
Let's say custom action is called rename and after hitting button Rename in the list I wanna in modal dialog write a new name of something. Then after hitting button OK I wanna call ranameAction in the controller which will do everything needed, but parameter called name must be sent there.
I have the solution but it is not good, there must be some better way.
I created _simple_form.html.twig:
{{
form(rename_form, {
action: rename_form.vars.action ~ '&referer=' ~ referer,
method: 'POST',
attr: { id: 'rename-form', style: 'display: none' }
})
}}
<div id="modal-rename" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h4>{{ 'rename_modal.title'|trans(_trans_parameters, 'EasyAdminBundle') }}</h4>
<p>{{ 'rename_modal.content'|trans(_trans_parameters, 'EasyAdminBundle') }}</p>
<br />
<input class="form-control" type="text" />
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn">
{{ 'action.cancel'|trans(_trans_parameters, _translation_domain) }}
</button>
{% if easyadmin_action_is_enabled(view, 'rename', _entity_config.name) %}
{% set _rename_action = easyadmin_get_action(view, 'rename', _entity_config.name) %}
<button type="button" data-dismiss="modal" class="btn btn-danger" id="modal-rename-button" formtarget="{{ _rename_action.target }}">
{% if _rename_action.icon %}<i class="fa fa-{{ _rename_action.icon }}"></i>{% endif %}
{{ 'rename_modal.action'|trans(_trans_parameters, 'EasyAdminBundle') }}
</button>
{% endif %}
</div>
</div>
</div>
</div>
In config.yml is a new option:
list:
actions:
rename: { name: rename, type: method, label: 'Rename', css_class: 'btn btn-primary', icon: pencil }
In list.html.twig which I'm using:
{% block main %}
{% block rename_form %}
{% set referer = paginator.currentPage == paginator.nbPages and 1 != paginator.currentPage and 1 == paginator.currentPageResults.count
? path('easyadmin', app.request.query|merge({ page: app.request.query.get('page') - 1 }))
: app.request.requestUri
%}
{{ include('#EasyAdmin/default/includes/_simple_form.html.twig', {
view: 'list',
referer: referer|url_encode,
rename_form: rename_form_template,
_translation_domain: _entity_config.translation_domain,
_trans_parameters: _trans_parameters,
_entity_config: _entity_config,
}, with_context = false) }}
{% endblock rename_form %}
{% endblock %}
{% block body_javascript %}
{{ parent() }}
<script type="text/javascript">
$(function() {
$('#modal-rename-button').on('click', function(e) {
e.preventDefault();
var name = $('#name').val();
var renameForm = $('#rename-form');
renameForm.attr('action', renameForm.attr('action').replace('__name__', name));
});
$('a.action-rename').on('click', function(e) {
e.preventDefault();
var id = $(this).parents('tr').first().data('id');
$('#modal-rename').modal({ backdrop: true, keyboard: true })
.off('click', '#modal-rename-button')
.on('click', '#modal-rename-button', function () {
var renameForm = $('#rename-form');
renameForm.attr('action', renameForm.attr('action').replace('__id__', id));
renameForm.trigger('submit');
});
});
});
</script>
{% endblock %}
And finally controller:
protected function createRenameForm($entityName, $entityId, $name)
{
$formBuilder = $this->get('form.factory')->createNamedBuilder('rename_form')
->setAction($this->generateUrl('easyadmin', array('action' => 'rename', 'entity' => $entityName, 'id' => $entityId, 'name' => $name)))
->setMethod('POST')
;
$formBuilder->add('submit', LegacyFormHelper::getType('submit'), array('label' => 'rename_modal.action', 'translation_domain' => 'EasyAdminBundle'));
$formBuilder->add('_easyadmin_rename_flag', LegacyFormHelper::getType('hidden'), array('data' => '1'));
return $formBuilder->getForm();
}
public function listAction() {
$this->dispatch(EasyAdminEvents::PRE_LIST);
$fields = $this->entity['list']['fields'];
$paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->config['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
$this->dispatch(EasyAdminEvents::POST_LIST, array('paginator' => $paginator));
return $this->render($this->entity['templates']['list'], array(
'title' => 'Branches',
'entity' => $this->entity['name'],
'currentBranch' => $this->repo->getCurrentBranchName(),
'paginator' => $paginator,
'fields' => $fields,
'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
'rename_form_template' => $this->createRenameForm($this->entity['name'], '__id__', '__name__')->createView(),
));
}
I had a similar issue because I wanted to show a modal before to perform a custom action. So what I did was modify the button action with jquery
$(document).ready(function () {
var $archiveButton = $('a.action-archive');
$archiveButton.attr('href', '#');
$archiveButton.attr('data-toggle', 'modal');
$archiveButton.attr('data-target', '#archive-modal');
$archiveButton.attr('data-url', '/url/to/load/form/inside/modal/body');
});
I don't know if it is the better way, but it helped me to show some info to the user before execute the archiveAction() in the AdminController
EDITED: a way to access POST variables
You can access to POST variables through the Container
public function renameAction()
{
$name = $this->container->get('request')->get('your variable');
var_dump($name);
die();
return $this->redirectToRoute('admin', ['entity' => 'Branch', 'action' => 'list']);
}
Play a while with the $this->container->get('request') to find what you are looking for

Laravel Ajax request returning whole page rather than just data

I'm trying to use ajax to find the next page on my pagination. However it keeps bringing in the whole body. I've taken a print screen to show the problem.
I'm not an expert on ajax show would appreciate some help as to how I can rectify this issue?
My code is below:
public function viewall()
{
$data["projects"] = $projects = Auth::user()->projects()->paginate(3);
if(Request::ajax())
{
$html = View::make('projects.viewall', $data)->render();
return Response::json(array('html' => $html));
}
return View::make('projects.viewall')->with('projects', $projects);
}
Js/js.js
$(".pagination a").click(function()
{
var myurl = $(this).attr('href');
$.ajax(
{
url: myurl,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajax-loading').show();
}
})
.done(function(data)
{
$('#ajax-loading').hide();
$("#projects").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
viewall.blade.php
#extends("layout")
#section("content")
<div class="container">
<h4>Your Projects</h4>
<div id="ajax-loading" class="alert alert-warning" style="display: none;">
<strong>Loading...</strong>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<div class="one-third column" id="projects">
{{ $project->project_name }}
{{ $project->project_brief }}
{{ date("d-m-Y", strtotime($project->start_day)) }}
</div>
#endforeach
#else
<h5 class="errorslist">You have no projects click <a class="errorslist" href="/project/create">here to create a project</a></h5>
#endif
#endif
<div class="sixteen columns">
{{ $projects->links() }}
</div>
</div>
#stop
This line:
$("#projects").empty().html(data.html);
will fill the #project up with your returned html which you created here:
$html = View::make('projects.viewall', $data)->render();
So,you just need to change projects.viewall with only 'partial view' that you want to load.
Probably you don't need to extends your main layout.
But you render a view here:
$html = View::make('projects.viewall', $data)->render();
so html is created by Laravel and then you insert it as html into the #projects domElement.
I experienced this kind of problem, just run
dd( json_decode( json_encode( Products::paginate(5) ), true) );
and can get a hint :)
I have read a solution about this here:
http://www.tagipuru.xyz/2016/05/17/displaying-data-using-laravel-pagination-in-the-html-table-without-page-reload/

Symfony2: The CSRF token is invalid. Please try to resubmit the form

I have a form wher I have to fill in some information in a field.
Even if I put something inside, I am getting the error:
The CSRF token is invalid. Please try to resubmit the form
Related to this question: symfony2 CSRF invalid I am using correctly the $form->bindRequest()
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
if ($form->isValid())
{
...
}
Here is my template (twig) code:
<div class="item item-last">
<h1>Create Affiliation</h1>
{% if valid == false %}
<div class="error">
{{ form_errors(form) }}
{{ form_errors(form.affiliation) }}
{{ error }}
</div>
{% endif %}
{% if app.session.flash('user-notice') != '' %}
<div class="flash-notice">
{% autoescape false %}
{{ app.session.flash('user-notice') }}
{% endautoescape %}
</div>
{% endif %}
</div>
<div class="item item-last">
<form action="{{ path('SciForumVersion2Bundle_user_submission_affiliation_create', {'hash_key' : submission.hashkey, 'author_id' : author.id }) }}?ajax=no" method="POST" class="authorForm" {{ form_enctype(form) }}>
<div style="float:left;">
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td>
{{ form_label(form.affiliation) }}
</td>
<td>
{{ form_widget(form.affiliation, { 'attr': {'size': 40} }) }}
</td>
</tr>
<tr>
<td>
</td>
<td>
<div class="button button-left button-cancel">
<img src="{{ asset('bundles/sciforumversion2/images/design/new/button-red.png') }}"/>
cancel
</div>
<div style="float: left;"> </div>
<div class="button button-left button-cancel">
<img src="{{ asset('bundles/sciforumversion2/images/design/new/button.png') }}"/>
<input type="submit" name="login" value="submit" />
</div>
<div style="clear: both;"></div>
</td>
</tr>
</table>
</div>
{{ form_rest(form) }}
</form>
</div>
And here is the js code:
function init_submission_functions()
{
init_fck();
$(".submission_link").unbind("click").bind("click", function() {
var href = $(this).attr("href");
if( href == null || href == '' ) return false;
$.ajax({
type: "POST",
async: true,
url: href,
cache: false,
dataType: "json",
success: function(data) {
$("#content .contentwrap .itemwrap").html( data.content );
init_submission_functions();
}
});
return false;
});
$(".authorForm").unbind("submit").bind("submit", function() {
var href = $(this).attr("action");
if( href == null || href == '' ) return false;
var affiliation = "blabla";
$.ajax({
type: "POST",
async: true,
url: href,
affiliation: affiliation,
cache: false,
dataType: "json",
success: function(data) {
$("#content .contentwrap .itemwrap").html( data.content );
init_submission_functions();
}
});
return false;
});
}
But I am still getting the same error.
Send a serialized form using the serialize jQuery method:
$form.submit(function (e) {
e.preventDefault();
$this = $(this);
$.post($this.attr('action'), $this.serialize(), function (response) {
// handle the response here
});
});
This way Symfony will handle the submit request as a normal request — you don't have to do anything special to handle an Ajax form submission. All you'll need to do is to return a JsonResponse — if you need it, of course.
Here is an example of handling the form — adapt it to your needs:
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid()) {
// do something here — like persisting or updating an entity
return new JsonResponse([
'success' => true,
]);
}
return new JsonResponse([
'success' => false,
'form' => $this->render($pathToTheTemplateHere, [
'form' => $form,
],
]);
}
The other way would be to use different templates: form.json.twig and form.html.twig — read the docs for details.

Categories