Using ajax to submit multiples form(s) in Symfony 3? - javascript

I'm trying to create a dynamic 2-step form using Jquery where in "step 1", I want to submit the form data without refreshing my page so that I can hide my html division containing my form and show the other representing my step 2 using Jquery.
The problem is that I'm using a collection of forms in my controller action like this:
public function indexAction(Request $request)
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('ATPlatformBundle:NoteDeFrais');
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class,array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
And I'm getting the forms data submitted from like this:
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()
&& isset($_POST['next_button'])) {
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$em->persist($ndf);
}
$em->flush();
}
elseif (isset($_POST['validate_button'])) {
foreach ($listNdf as $ndf) {
$ndf->setSubmitted(true);
}
$em->flush();
}
So what I wanted to know is how to send my data via an ajax request and how to get them from my action. So far I tried to proceed like this but it (logically) doesn't work.
$("div#bloc_validation").css("display", "none");
$("#next_button").click(function(){
$(".form_ndf").each(function(){
$.post("{{ path('platform_homepage') }}",
{ndf: $(this).serialize()}, //My issue is here
function(){
alert('SUCCESS!');
}
);
});
$("div#form_bloc ").css("display", "none");
$("div#bloc_validation").css("display", "block");
});
Do you have any ideas ? Thanks in advance

The most basic approach is this:
add a javascripts block in your twig file with the content as below.
Change appbundle_blog in the first line inside the .ready() function in the name of your form. (Inspect your html to find it).
{% extends 'base.html.twig' %}
{% block body %}
{{ form_start(edit_form) }}
{{ form_widget(edit_form) }}
<input type="submit" value="Save Changes" />
{{ form_end(edit_form) }}
{% endblock %}
{% block javascripts %}
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready( function() {
var form = $('form[name=appbundle_blog]');
form.submit( function(e) {
e.preventDefault();
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
});
});
});
</script>
{% endblock %}
If the form has been submitted you have to answer to an AJAX request. Therefore you could render another template..
/**
* Displays a form to edit an existing blog entity.
*
* #Route("/{id}/edit", name="blog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Blog $blog)
{
$editForm = $this->createForm('AppBundle\Form\BlogType', $blog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
/* render some new content */
return $this->render('blog/ajax.html.twig', array(
'blog' => $blog,
));
}
return $this->render('blog/edit.html.twig', array(
'blog' => $blog,
'edit_form' => $editForm->createView(),
));
Or answer in JSON:
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Displays a form to edit an existing blog entity.
*
* #Route("/{id}/edit", name="blog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Blog $blog)
{
$editForm = $this->createForm('AppBundle\Form\BlogType', $blog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return new JsonResponse(array(
'status' => 'success',
// ...
));
}
return $this->render('blog/edit.html.twig', array(
'blog' => $blog,
'edit_form' => $editForm->createView(),
));
}
If you want you can even test if the request is an AJAX request or not:
if($request->isXmlHttpRequest()) {
// yes it is AJAX
}

Related

Dynamically changing form is Symfony 5

I am trying to make a form that changes based on user response, I have a ChoiceType::class for the first part with 'yes' or 'no' as the options. If the user selects 'yes' I want the second part of the form to show up to get their response to that, but if they select 'no' I just want to keep that second form hidden.
This is the form I have so far
public function buildForm(FormBuilderInterface $builder, array $options)
{
->add('attending', ChoiceType::class, [
'choices' => [
'yes' => true,
'no' => false,
],
'attr' => [
'class' => 'attendanceStatus'
],
'mapped' => false,
'required' => true,
'label' => 'Will you be attending?',
'placeholder' => 'Please make selection',
])
->add('bringingGuest', ChoiceType::class, [
'choices' => [
'yes' => true,
'no' => false,
],
I wrapped the forms in a class and gave each form an ID
<div class="attendance">
<div id="attendance-status">
{{ form_label(form.attending) }}
{{ form_errors(form.attending) }}
{{ form_widget(form.attending) }}
</div>
<div id="guest" style="display: none;">
{{ form_label(form.bringingGuest) }}
{{ form_errors(form.bringingGuest) }}
{{ form_widget(form.bringingGuest) }}
</div>
</div>
I'm not the greatest with javascript but I tried to do an if statement like this
if ('.attending' == true) {
document.getElementById('guest').style.display = 'block';
}
I've been at this for a bit of time now and I can't seem to figure out how to do it properly. I thought it would be something like having an event listener for the user selection and then just using javascript to show the second form if conditions are met.
This is, like you probably already know, a javascript question. Like you said, you can use an event listener, for example to run a function whenever a value changes. Here's an example:
const someId = document.getElementById('some-id');
const example = document.getElementById('example');
someId.addEventListener('change', doSomething);
function doSomething() {
if (someId.value === "yes") {
example.innerHTML = "YES!"
} else {
example.innerHTML = ""
}
}
<select name="name" id="some-id">
<option value="no">no</option>
<option value="yes">yes</option>
</select>
<div id="example">
</div>
All you need to do is check what IDs you should target and what you want to happen on which event. To find out more about events, see: https://developer.mozilla.org/en-US/docs/Web/Events.
You may want to check How to Dynamically Modify Forms Using Form Events page in Symfony docs.
In your case it will be Dynamic Generation for Submitted Forms section.
It involves 2 types of events - Form events on PHP/Symfony side and JS mostly "passive" role to listen for element change and replace the HTML.
The idea is next:
On user action on the HTML element send a request to backend and render the new state for the page based on the element's changed value. Here you get full page HTML as a response.
Then just replace dependent chunks of the page with the new rendered pieces of HTML you get from the response.
Here are main parts (copy-pasted from the docs):
// src/Form/Type/SportMeetupType.php
namespace App\Form\Type;
use App\Entity\Position;
use App\Entity\Sport;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormInterface;
// ...
class SportMeetupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('sport', EntityType::class, [
'class' => Sport::class,
'placeholder' => '',
])
;
$formModifier = function (FormInterface $form, Sport $sport = null) {
$positions = null === $sport ? [] : $sport->getAvailablePositions();
$form->add('position', EntityType::class, [
'class' => Position::class,
'placeholder' => '',
'choices' => $positions,
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
$formModifier($event->getForm(), $data->getSport());
}
);
$builder->get('sport')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$sport = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $sport);
}
);
}
// ...
}
in JS:
{# templates/meetup/create.html.twig #}
{{ form_start(form) }}
{{ form_row(form.sport) }} {# <select id="meetup_sport" ... #}
{{ form_row(form.position) }} {# <select id="meetup_position" ... #}
{# ... #}
{{ form_end(form) }}
<script>
var $sport = $('#meetup_sport');
// When sport gets selected ...
$sport.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected sport value.
var data = {};
data[$sport.attr('name')] = $sport.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#meetup_position').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#meetup_position')
);
// Position field now displays the appropriate positions.
}
});
});
</script>

CHALLENGE: Load Gravity Forms via AJAX - Change working PHP solution to Gutenberg code

I had the need to load a Gravity Form through Ajax on a push of a button (in PHP/Wordpress), and thanks to Steven Henty, I've found his solution to fix my issue. Modified it at little to open my form in a modal (lity modal), and it works!
However.... Now I started to migrate my site to the new Gutenberg editor in Wordpress. So I need a system that can do the same from a Gutenberg block (javascript) code.
I can code some, but I am not hardcore, so would love if anyone could tell me how to implement this former (PHP based) 'system', for instance to a (javascript based) Gutenberg Button-block, that implements this code. Here is the code for the current (working) button:
button.php
// Hook up the AJAX ajctions
add_action('wp_ajax_nopriv_gf_button_get_form', 'gf_button_ajax_get_form');
add_action('wp_ajax_gf_button_get_form', 'gf_button_ajax_get_form');
// Add the "button" action to the gravityforms shortcode
// e.g. [gravityforms action="button" id=1 text="button text"]
add_filter('gform_shortcode_button', 'gf_button_shortcode', 10, 3);
function gf_button_shortcode($shortcode_string, $attributes, $content)
{
$a = shortcode_atts(array(
'id' => 0,
'text' => 'Open',
'button_class' => '',
'button_style' => ''
), $attributes);
$form_id = absint($a['id']);
$curr_lang = ICL_LANGUAGE_CODE;
if ($form_id < 1) {
return '<div>Missing the ID attribute.</div>';
}
gravity_form_enqueue_scripts($form_id, true);
$ajax_url = admin_url('admin-ajax.php');
$html = sprintf('<button id="gf_button_get_form_%d" class="gf_button_get_form %s" style="%s"><div class="gf_button_get_form-label">%s</div></button>', $form_id, $a['button_class'], $a['button_style'], $form_id, $a['text']);
$html .= "<script>
(function (SHFormLoader, $) {
$('#gf_button_get_form_{$form_id}').click(function(){
$.ajaxSetup({
beforeSend: function() {
$('.spinner_{$form_id}').addClass('active');
},
complete: function() {
$('.spinner_{$form_id}').removeClass('active');
var fieldsWithHiddenLabels = $('.gfield.hidden-label');
if (fieldsWithHiddenLabels.length) {
fieldsWithHiddenLabels.each(function(){
if($(this).hasClass('gfield_contains_required')){
$(this).find('.ginput_container label').prepend('<span class=\"gfield_required\">*</span>');
}
});
}
}
});
$.get('{$ajax_url}?lang={$curr_lang}&action=gf_button_get_form&form_id={$form_id}',function(response){
lity(response);
if(window['gformInitDatepicker']) {gformInitDatepicker();}
});
});
}(window.SHFormLoader = window.SHFormLoader || {}, jQuery));
</script>";
return $html;
}
function gf_button_ajax_get_form() {
$form_id = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
gravity_form($form_id, true, false, false, false, true);
die();
}
I am using the excellent create-guten-blocks as boilerplate, and my template block file looks like this:
form-button.js
import './style.scss';
import './editor.scss';
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'my-blocks/form-button', {
title: __( 'Form Button' ),
icon: heart,
category: 'common',
keywords: [
__( 'my-blocks — Form Button' )
],
edit: function( props ) {
return (
<div className={ props.className }>
<p>— Hello from the backend.</p>
<p>
CGB BLOCK: <code>configit-blocks</code> is a new Gutenberg block
</p>
<p>
It was created via{ ' ' }
<code>
<a href="https://github.com/ahmadawais/create-guten-block">
create-guten-block
</a>
</code>.
</p>
</div>
);
},
save: function( props ) {
return (
<div>
<p>— Hello from the frontend.</p>
<p>
CGB BLOCK: <code>configit-blocks</code> is a new Gutenberg block.
</p>
<p>
It was created via{ ' ' }
<code>
<a href="https://github.com/ahmadawais/create-guten-block">
create-guten-block
</a>
</code>.
</p>
</div>
);
},
} );
Hope this makes sense. This is my second post on Stackoverflow, so please let me know if you need more details ... Really hope one of you skilled people can handle this. Thanks!

Javascript creates the POST, the Symfony controller handles it and redirects, but the new page is not shown

I'm a beginner in Symfony, PHP and Javascript. I'm struggling with a Javascript tree form based on Fancytree. Thanks to the forum, I made everything working up to POSTing back the form data to the controller, handling the request and redirecting to a success page. The problem is that the success page never shows. Nor IE neither Firefox debuggers show errors. I don't progress anymore, I'm stuck.
Here is my controller:
namespace Solar\DataBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Config\Definition\Exception\Exception;
class DefaultController extends Controller
{
/**
* Test data sent to Twig and javascript tree
*
* #Route("/form_tree_demo", name="form_tree_demo")
* #Method({"GET", "POST"})
*/
public function formTreeDemoAction(Request $request)
{
$test = 'Test string';
$testArray =
array(
array(
'name'=> '1',
'title' => '1',
'children' =>
array(
array('name' => '1.1',
'title' => '1.1'
),
array('name' => '1.2',
'title' => '1.2'
)
)
),
array(
'name'=> '2',
'title' => '2',
'children' =>
array(
array('name' => '2.1',
'title' => '2.1'
),
array('name' => '2.2',
'title' => '2.2'
)
)
)
);
$form = $this->createFormBuilder()
->add('save', SubmitType::class, array('label' => 'Post to the controller'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//for debug
//throw new Exception(var_dump($form->getData()));
return $this->redirectToRoute('success', array('message' => 'Post handled'));
}
return $this->render('formtreedemo.html.twig',
array(
'tree_form' => $form->createView(),
'test_array' => json_encode($testArray)
)
);
}
/**
* #Route("/success", name="success")
*/
public function successAction()
{
return $this->render('success.html.twig');
}
}
Here is the Twig form:
{% extends 'base.html.twig' %}
{% block body %}
<h1>A demo form with Fancytree</h1>
{{ form_start(tree_form) }}
<div id="tree" name="selNodes">
</div>
Additional data: <input type="text" name="otherFormData" /><br><br>
{{ form_end(tree_form) }}
{% endblock %}
{% block javascripts %}
<script type="text/javascript" src="{{asset('assets/vendor/jquery/dist/jquery.js')}}"></script>
<script type="text/javascript" src="{{asset('assets/vendor/jquery-ui/jquery-ui.js')}}"></script>
<script type="text/javascript" src="{{asset('assets/vendor/bootstrap/dist/js/bootstrap.js')}}"></script>
<link rel="stylesheet" type="text/css" id="skinSheet" href="{{asset('assets/vendor/fancytree/src/skin-lion/ui.fancytree.css')}}" />
<script type="text/javascript" src="{{asset('assets/vendor/fancytree/src/jquery.fancytree.js')}}"></script>
<script type="text/javascript">
$(function(){
$("#tree").fancytree({
checkbox: true,
selectMode: 2,
source:$.parseJSON('{{test_array}}'.replace(/"/ig,'"'))
});
$("form").submit(function() {
$("#tree").fancytree("getTree").generateFormElements();
jQuery.ajax({
type: "POST",
url: "{{path("form_tree_demo")}}",
data: formData
});
return false;
});
});
</script>
{% endblock %}
And finally here is the IE console dump :
URL Method Result Type Initiateur
/web/app_dev.php/form_tree_demo GET 200 text/html actualiser
/web/assets/vendor/bootstrap/dist/css/bootstrap.css GET 200 text/css <link rel="stylesheet">
/web/assets/vendor/bootstrap/dist/css/bootstrap-theme.css GET 200 text/css <link rel="stylesheet">
/web/assets/vendor/jquery/dist/jquery.js GET 200 application/javascript <script>
/web/assets/vendor/jquery-ui/jquery-ui.js GET 200 application/javascript <script>
/web/assets/vendor/bootstrap/dist/js/bootstrap.js GET 200 application/javascript <script>
/web/assets/vendor/fancytree/src/skin-lion/ui.fancytree.css GET 200 text/css <link rel="stylesheet">
/web/assets/vendor/fancytree/src/jquery.fancytree.js GET 200 application/javascript <script>
/web/app_dev.php/_wdt/115370 GET 200 text/html XMLHttpRequest
/web/assets/vendor/fancytree/src/skin-lion/icons.gif GET 200 image/gif background-image
/web/app_dev.php/form_tree_demo POST 302 text/html XMLHttpRequest
/web/app_dev.php/success?message=Post%20handled GET 200 text/html XMLHttpRequest
Additional info:
I run Symfony 3.2 under Windows 8, OpenSuse and Ubuntu VM server. Same results everywhere. Same results with deprecated Dynatree also.
Kind help would be appreciated.
Jean-Michel
You need to handle the success/failure of the ajax and load the new page from there. At present you are returning the html of the redirect call in your controller and your javascript function does not handle the return in any way and just returns false.
If the form in your controller only responds to ajax, then on success pass back the url to redirect to, then get your javascript to perform the redirect.
If the form is only to handle the ajax call, I personally would create a route/function to handle just that.
That why you can perform some checks (like $request->isXmlHttpRequest()) to ensure the call is coming from the ajax only.
E.g.
public function ajaxAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$form_element1 = $request->request->get('form_element1');
$form_element2 = $request->request->get('form_element2');
// do whatever
$data['success'] = true;
$data['url'] = $this->generateUrl('new_route');;
return new \Symfony\Component\HttpFoundation\JsonResponse($data);
}
}
Then your javascript
<script type="text/javascript">
$(function(){
$("#tree").fancytree({
checkbox: true,
selectMode: 2,
source:$.parseJSON('{{test_array}}'.replace(/"/ig,'"'))
});
$("form").submit(function(e) {
e.preventDefault();
var formData = $("#tree").fancytree("getTree").generateFormElements();
var jqxhr = $.ajax({
type: "POST",
url: "{{path('ajax_action')}}",
data: formData
})
.done(function(data) {
if (data.success === true) {
window.location.href = data.url;
}
})
.fail(function(data) {
alert('error');
})
.always(function(data) {
});
return false;
});
});
</script>

Symfony check box with action

I using symfony and have template with array with some entities array, and need create in for in check box for all entity and when checked some entities and click ready go to action with ids(from all check box) - example - taskExecution.id
I don't used symfony form with type entity because taskExecutions complicated DTO, from this DTO i need only id for to send on another action
$taskExecutions = $this->getTaskExecution()
->getTaskExecutionByFilter($form->getData());
return [
'form' => $form->createView(),
'taskExecutions' => $taskExecutions
];
{% for taskExecution in taskExecutions %}
<input class="searchType" type="checkbox" name="SharingNotification" id={{ taskExecution.id }}>
<label class="searchtype2label">{{ taskExecution.id }}</label>
</input>
{% endfor %}
{% javascripts
'#EconomyBundle/Resources/public/js/check-task-executions.js'
filter='?yui_js' combine=true %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
add js
$('.searchType').click(function() {
alert($(this).attr('id'));
if(this.checked){
$.ajax({
type: "POST",
url: '/manage/outbound_invoices/task_executions/ids',
data: $(this).attr('id'), //--> send id of checked checkbox on other page
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
this my action
/**
* give task executions ids for created row.
*
* #Route("/manage/outbound_invoices/task_executions/ids", name="ids_task_executions_")
* #Method({"POST", "GET"})
*/
public function getIdsTaskExecutionsAction(Request $request)
{
$ids = $request->get('ids');
}
I don't know js, help please for understand how get check box value (1 or 0) and entity id parameter and send to another action
I don't think you need javascript for that. Instead you should have a look to the Symfony doc on how to use a form without data_class
your form will looks like :
<?php
class TaskExecutionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('taskExecution', EntityType::class, array(
'class' => 'AppBundle/TaskExecution',
'expanded' => true,
'multiple' => true
))
->add('submit', SubmitType::class)
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_protection' => false
));
}
/**
* #return string
*/
public function getName()
{
return 'execution_task_type';
}
}
And in your controller:
<?php
/**
* give task executions ids for created row.
*
* #Route("/manage/outbound_invoices/task_executions/ids", name="ids_task_executions_")
* #Method({"POST", "GET"})
*/
public function getIdsTaskExecutionsAction(Request $request)
{
$form = $this->createForm(TaskExecutionType::class, null, array(
'method' => 'POST',
'action' => 'ids_task_executions'
));
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData(); //this will be an array of all the TaskExecution entities you selected
//your own logic
}
return $this->render('template.html.twig', array(
'form' => $form->createView()
));
}

how to use symfony controller variables in frontend js?

Say I have a controller like this:
public function showAction(Request $request, $id, $context = array())
{
$url = $this->getPlayUrl($id, $context);
//some code here}
I want to use the variable $url in a frontend js file like this :
var html = '<iframe src=\''+ url +'\' name=\'viewerIframe\' id=\'viewerIframe\' width=\'100%\'allowfullscreen webkitallowfullscreen height=\'100%\' style=\'border:0px\'></iframe>';
How am I supposed to make this happen? For the code above ,it gave me 'undefined url' error.
Thank you.
Another option would be to have your template call a controller action (so you can pass parameters as required), for example, like this example for using highchart.js:
{% block javascripts %}
{{ parent() }}
<script src="/js/highcharts.js"></script>
<script src="/js/exporting.js"></script>
<script type="text/javascript">
{{ render(controller('AppBundle:Default:script')) }}
</script>
{% endblock %}
In the controller it looks like this:
public function scriptAction() {
$reports = $this->get('app.reports');
$chart = $reports->getDistsFYToDate();
return $this->render('Default/script.js.twig', array(
'chart' => $chart,
));
}
and script.js.twig looks like this:
$(document).ready(function () {
var options = {
chart: {
type: 'line'
},
title: {
text: 'Distributions, FY{{ chart.fy }} to date'
},
xAxis: {
categories: [{% for category in chart.categories %}{{category|raw}}{%endfor%}]
},
yAxis: {
title: {
text: 'Distributions'
}
},
series: {{ chart.series|raw }}
};
$('#linechart').highcharts(options);
})
Maybe it's better if you use HTML5 data attributes: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
In you view add some script tags and assign a javascript vraible to the twig variable. Don't forget to quote the twig (if required).
Firstly, I would ensure that the $url always had a value;
return $this->render('MyWebBundle:Player:show.html.twig', array(
'file' => $file,
'url' => (empty($url)) ? '' : $url,
'context' => $context,
'player' => $player,
'agentInWhiteList' => $agentInWhiteList
));
Something like;
<script>
var jsVar = '{{ url }}';
var html = false;
if (jsVar.length > 0) {
html = '<iframe src=\''+ jsVar +'\' name=\'viewerIframe\' id=\'viewerIframe\' width=\'100%\'allowfullscreen webkitallowfullscreen height=\'100%\' style=\'border:0px\'></iframe>';
}
// test html !== false before using it
</script>

Categories

Resources