Include jQuery into Symfony2
Assuming your jquery.min.js is placed undersrc/Acme/FooBundle/Resources/public/js/
You can use either
<script type="text/javascript" src="{{ asset('bundles/acmefoo/js/jquery.min.js') }}"></script>
or
{% javascripts
'@AcmeFooBundle/Resources/public/js/jquery.min.js'
%}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
Into your twig template.
Make sure you installed the assets afterwards or run this command
php app/console assets:install web --symlink
What is the best way to include jQuery for symfony project using composer and assets
I'm not a big fan of installing jquery in the vendor directory in Symfony, as it's not a PHP library. Composer and vendor
directory should only be used for PHP dependencies.
You should separates the frontend part from the backend part.
All the js, css and other assets should go somewhere else.
Therefore you have 2 options:
- If you want to have separate resources per bundle, then put your resources you use for the frontend in the public directory of your bundle: for example put your
jquery.min.js
in theResources/public/js
folder of your bundle.
Then run the command php app/console assets:install
. this will copy your js files to the web/bundles/yourbundle/js/
directory.
Finally use <script type="text/javascript" src="{{ asset('yourbundle/js/jquery.min.js') }}"></script>
in your twig file to add jquery.
- If you have common resources for all your bundles, put your resources directly in the
web
folder, for example:web/js
,web/css
,web/img
...
And then use<script type="text/javascript" src="{{ asset('js/jquery.min.js') }}"></script>
in your twig template.
How to use JQuery in TWIG (symfony2)
Yes, in your block of javascripts you must include the jQuery file. An example:
{% block javascripts %}
<script type="text/javascript" src="{{ asset('bundles/uamdatatables/js/jquery.min.js') }}"></script>
{% endblock %}
Take care not to overwrite inherited javascripts, maybe you have to add {{ parent() }}
to the {% block javascripts %}
EDIT:
If you don't already have a jQuery file you can download it from the official website: http://jquery.com/
Symfony 2.6 - Add jQuery file to Twig
{% block javascripts %} <script src="{{ asset('bundles/interemplea/js/jquery-1.11.3.min.js') }}" type="text/javascript"></script> {% endblock %}
app/console assets:install
Thats all
Pay attention to the correct filepath
How to use jQuery with webpack-encore in a Symfony project?
I solved the issue. I changed asset function inside the twig with encore_entry_script_tags, now jQuery and $ are defined.
Load file in symfony 2 directory from jQuery
Put it in web/some_path
directory, and when you want to reference it in your template do it like this:
$(..).load('{{ asset("some_path/objectives.html") }}');
Update: if you can't process the js
file using twig, you have to pass the value i.e: path to that js file, from your main template. If you're using some external library, then it almost certainly provides a way for you to do that. If you've written the js yourself, you can do something like this:
// in your js file
var YourScriptObject = {
path: '',
setPath: function(p){
this.path = p;
}
init: function(){
// do everything that you did before in the js here,
// but use YourScriptObject.path as your path.
}
}
// in the main template
// first include the js
// then
$(document).ready(function(){
YourScriptObject.setPath('{{ asset("some_path/objectives.html") }}');
YourScriptObject.init();
});
Symfony2 can't find jquery.js file in components
Composer doesn't need to find the file, Assetic needs to find it.
I currently use jquery loaded with components/jquery and have the assetic set up like so..
assetic:
... debug, filters, etc ...
assets:
jquery: %kernel.root_dir%/../vendor/components/jquery/jquery.min.js
underscore: %kernel.root_dir%/../vendor/components/underscore/underscore-min.js
and so on...
This is loading the file with the source as the components/jquery folder in the vendor directory.
Adding JQuery Autocomplete in Symfony2 Entity field
First you have to start creating a route and action that returns json data. JQuery's autocomplete remote gives you a $_GET variabele with the index 'term' and wants to receive JSON back. Here is an example that uses an Entity with the name City and a property $name
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* City controller.
*
* @Route("/city")
*/
class CityController extends Controller
{
/**
* @Route("/autocomplete", name="city_autocomplete")
*/
public function autocompleteAction(Request $request)
{
$names = array();
$term = trim(strip_tags($request->get('term')));
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AppBundle:City')->createQueryBuilder('c')
->where('c.name LIKE :name')
->setParameter('name', '%'.$term.'%')
->getQuery()
->getResult();
foreach ($entities as $entity)
{
$names[] = $entity->getName();
}
$response = new JsonResponse();
$response->setData($names);
return $response;
}
}
Secondary you can make a twig view just like the source from jQuery's autocomplete. The only difference is the source variable in the autocomplete() function . There you have to specify te twig's path() function with your route key eg city_autocomplete.
(This view needs another route and another (normal) action.)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
</style>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "{{ path('city_autocomplete') }}",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
And finaly you can slightly change this view and use your own form.
Related Topics
Soapfault Exception: Could Not Connect to Host
Difference Between File, File_Get_Contents, and Fopen in PHP
Curl Requires Curlopt_Ssl_Verifypeer=False
How to Search Through a JSON Array in PHP
How to Send Cookies with File_Get_Contents
Php: Check Who Had Read Sent Email
Warning: "Continue" Targeting Switch Is Equivalent to "Break". Did You Mean to Use "Continue 2"
PHP Date Time Current Time Add Minutes
How Validate Unique Email Out of the User That Is Updating It in Laravel
Can a User Alter the Value of $_Session in PHP
Any Way to Keep Curl's Cookies in Memory and Not on Disk
How Many Days Until X-Y-Z Date
Convert to Date Format Dd/Mm/Yyyy
Try Catch Cannot Work with Require_Once in PHP
How to Get Cookie's Expire Time
Using SQLite3 in PHP How to Count the Number of Rows in a Result Set