Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  66] [ 6]  / answers: 1 / hits: 29869  / 12 Years ago, mon, july 2, 2012, 12:00:00

I have a view called contact.html.twig. It has a form with some textfields. I want to use javascript to validate that none of the fields are empty, as well as some other rules. But I do not know where to put the .js with the definitions. I do not know either how to call the .js script using the Twig notation.


More From » symfony

 Answers
24

This is a generic answer for how to handle javascript... not specifically the validation part. The approach I use is to store individual functionality in separate JS files as plugins in the bundles Resources/public/js directory like so:



(function ($) {

$.fn.userAdmin = function (options) {
var $this = $(this);

$this.on('click', '.delete-item', function (event) {
event.preventDefault();
event.stopPropagation();

// handle deleting an item...
});
}
});


I then include these files in my base template using assetic:



{% javascripts
'@SOTBCoreBundle/Resources/public/js/user.js'
%}
<script src={{ asset_url }}></script>
{% endjavascripts %}


In my base template I have a block at the end of <body> for a $(document).ready();



<script>
$(document).ready(function () {
{% block documentReady %}{% endblock documentReady %}
});
</script>
</body>


Then in my page that has the user admin functionality I can call the userAdmin function like so:



{% block documentReady %}
{{ parent() }}
$('#user-form').userAdmin();
{% endblock documentReady %}

[#84514] Sunday, July 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yaquelina

Total Points: 517
Total Questions: 101
Total Answers: 96

Location: Egypt
Member since Tue, Jul 6, 2021
3 Years ago
yaquelina questions
;