I'm new in Symfony2 and AngularJS. I´m trying to use json_encode to show my database's content. But it doens't work. This is my controller:
public function catalogonewAction()
{
$data = $this->getDoctrine()->getManager()
->getRepository('AcmeRetroBundle:Game')->findAll();
return $this->render('AcmeRetroBundle:Default:catalogonew.html.twig',
array('data' => json_encode($data)));}
This is my html.twig:
{% verbatim %}
<div ng-app="myApp1" ng-init="mydata = {{ list|raw }}">
<table id="sortedData">
<tr><th>T1</th><th>T2</th></tr>
<tr ng-repeat="data in mydata | filter:sortData">
<td>{{data.nombreJuego}}</td>
<td>{{data.description}}</td>
</tr>
</table>
</div>
{% endverbatim %}
And my app.js:
angular.module('myApp1', []).
filter('sortData', function() {
alert('Hi');
return out;
});
When I refresh my page it is shown this:
T1 T2
{{data.nombreJuego}} {{data.description}}
What is wrong?
I don't like to pass data from back-end to an
anuglarJS like that, it's a common to use ajax request to retrieve data.
Try to pass you data to a javascript variable that you could affect is to an object in you angular scope :
<script>
var list= {{ data }}
</script>
{% verbatim %}
<div ng-app="myApp1" ng-init="mydata = list">
<table id="sortedData">
<tr><th>T1</th><th>T2</th></tr>
<tr ng-repeat="data in mydata | filter:sortData">
<td>{{data.nombreJuego}}</td>
<td>{{data.description}}</td>
</tr>
</table>
</div>
{% endverbatim %}
Related
I try to update the 'archive' value of the database when I click on a check box. After searching the site and google, I managed to do it.
However, by adding a second article, it only works for the first one. If you ever have ideas, I will be grateful!
Thank you
I have fosjsroutingbundle installed.
Here is my controller :
public function archiveAction($id, Request $request)
{
if ($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$glasse = $em->getRepository('SosMontagesBundle:Glasse')->find($id);
$glasseArchiveStat = $glasse->getArchive();
if ($glasseArchiveStat == false) {
$glasse->setArchive(true);
$em->flush();
} else {
$glasse->setArchive(false);
$em->flush();
}
return new Response('d');
}
}
My route :
sos_montage_archive:
path: /admin/archive/{id}
defaults: { _controller: SosMontagesBundle:Admin:archive }
requirements:
id: \d+
options:
expose: true
My view :
{% extends '#SosMontages/layout.html.twig' %}
{% block content %}
<div class="col-md-6 col-md-offset-3">
<h2>Liste des lunettes</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Marque - Model</th>
<th>Description</th>
<th>Archive</th>
<th>Ordre</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for article in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
<td>{{ article.id }}</td>
<td>{{ article.name ~ ' - ' ~ article.brand }}</td>
<td>{{ article.content }}</td>
{% if article.archive == false %}
<td><input type="checkbox" name="{{ article.id }}" id="archive"></td>
{% else %}
<td><input type="checkbox" name="{{ article.id }}" id="archive" checked></td>
{% endif %}
<td></td>
<td><i class="fa fa-pencil fa-2x" aria-hidden="true"></i>
<i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
</div>
{% endblock %}
{% block javascript %}
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script>
<script>
$(document).ready(function () {
$("#archive").click(function () {
var id = $("#archive").attr('name');
var DATA = 'sentValue=' + id;
$.ajax({
type: "POST",
url: Routing.generate('sos_montage_archive', { id: id }),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
</script>
{% endblock %}
Your click listenner on your checkbox may not be correct. You should use a change listener while it's a checkbox. Change your click function in js to change:
$('#archive').change(function() {
if($(this).is(":checked")) {
//'checked' event code
return;
}
//'unchecked' event code
});
However you also have two checkboxes and only one id. This might create weird bugs. Changing your ids to #archive1 and #archive2 may fix your code.
You have to fix your HTML and differentiate your #archive id selector.
You can do that by using loop.index for example:
id="archive{{ loop.index }}" //output : archive1, archive2...
Twig doc :
http://twig.sensiolabs.org/doc/2.x/tags/for.html#the-loop-variable
Iam learning symfony and I want to build a shop system for my school project. I want to send the list of items that the user select to another controller i don't know how.
here is my ShowItemAction
public function ShowItemAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createFormBuilder()
->add('search', 'textbox', array(
'attr' => array(
'label' => false
)))->getForm();
$form->handleRequest($request);
if (($form->isSubmitted()) && ($form->isValid())) {
$formdata = $request->request->get('form');
$search = $formdata['search'];
$products_Repo = $em->getRepository('MyShopBundle:Products')->GetProducts($search);
return $this->render('MyShopBundle:Products:show.html.twig',array(
'form' => $form->createView(),
'products'=> $products_Repo
));
}
return $this->render('MyShopBundle:Products:show.html.twig',array(
'form' => $form->createView()
));
}
and my show.html.Twig
{% block body%}
<div id="cart-content">
</div>
<div class="cart-buttons">
<button id="cart">View Shopping Cart</button>
<button id="clear-cart">Clear Cart</button>
</div>
{{ form(form) }}
{% if products is defined %}
<table>
<thead>
<tr>
<th>Partner-Name</th>
<th>ProductNr</th>
<th>Description</th>
<th>price</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td><div class="partner">{{product.partner}}</div></td>
<td><div class="partnerdata" data-value="{{ product.id }}">{{ product.productnr }}</div></td>
<td><div class="description"> {{ product.description }}</div></td>
<td><div class="price">{{ product.price }}</div></td>
<td class="counter"><input type="number" name="count" min="1" step="1"></td>
<td class="cart">
<button type='submit'>in den Warenkorb</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% endblock %}
my javascript:
$('.cart').click(function (event) {
event.preventDefault();
var closestTr = $(this).closest('tr');
var ref = closestTr.find('.partner').text();
var data_value = closestTr.find('.partnerdata').data('value');
var productNr= closestTr.find('.partnerdata').html();
var price= closestTr.find('.price').html();
var count = closestTr.find('input').val();
if (count < 1) {
}
else {
$(".cart-content").prepend(HS_ref + "|" + data_value + "|" + herstellerNr + "|" + count + "|" + vk);
}
});
I can see the data which the user has selected(inside <div id="cart-content"></div>) but I don't know how to send those contents perhaps as a POST to the controller.
Something like this: https://www.codeofaninja.com/2013/04/shopping-cart-in-php.html
I am working on Symfony 2.7
You can do this with AJAX
First, you need to get the html data
Second, you have to send this data to the controller
Third, you have to get the data in the controller
Here is an example :
First "you need to get the html data"
HTML :
<div id="cart-content" data-route="{{ path('get_user_card_items') }}">
<span data-item-id="item1" data-quantity="2"></span>
<span data-item-id="item2" data-quantity="1"></span>
<span data-item-id="item3" data-quantity="5"></span>
</div>
JS
/**
* Get the content of #cart-content
*/
function getCartItems() {
var items = [];
$('#cart-content span').each(function(){ // loop into all span
var item = { // create an item object who get all the data
'id' : $(this).attr('data-item-id'),
'quantity' : $(this).attr('data-quantity'),
}
items.push(item); // push into an array
});
return items;
}
Second "you have to send this data to the controller"
JS
function sendCartItems() {
$.ajax({
url: $('#cart-content').attr('data-route'), // here is a route variable
method: 'POST',
data: {items: getCartItems()},
success: function (data) {
// do some stuff when it's send
}
});
}
Third "you have to get the data in the controller"
CustomController.php
class CustomController extends Controller
{
/**
* #Route("/getUserCardItems", name="get_user_card_items")
*/
public function getUserCardItemsAction(Request $request)
{
$items = $request->get('items');
var_dump($items);die; // display for you the items to see if it's works (look into the networks console tab on google chrome)
// some stuff like sending items to database...
}
}
Access network tab google chrome
And you done ;)
I'm following the basic quickstart with laravel 5. I'm deviating only in that I'm using TwigBridge to allow me to use twig templates instead of blade. I'm getting in error when I tried to load my view.
Unknown "method_field" function in "/home/vagrant/laravel-test/resources/views/tasks.twig" at line 63.
method_field should be an available default helper function in laravel. I'm not really sure why twigbridge isn't finding it. Is there something I'm missing I need to make this function available to TwigBridge?
Edit
Here's my code:
{% if tasks|length > 0 %}
<div class="panel panel-default">
<div class="panel-heading">
Current Tasks
</div>
<div class="panel-body">
<table class="table table-striped task-table">
<!-- Table Headings -->
<thead>
<th>Task</th>
<th> </th>
</thead>
<!-- Table Body -->
<tbody>
{% for task in tasks %}
<tr>
<!-- Task Name -->
<td class="table-text">
<div>{{ task.name }}</div>
</td>
<td>
<form action="{{ url('task/'~task.id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Task</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
Edit 2
I partially figured it out. I had to add method_field to the config/twigbridge.php file in the functions array:
'functions' => [
'elixir',
'head',
'last',
'method_field',
].
This got it to run the function, however the output is converted to html entities because it actually renders the input tag text instead of the tag itself. So I need to figure out away to make it not escape the output.
The answer is that you have to add the function to the config/twigbridge.php with an is_safe option. That can be done this way:
in /app/config/twigbridge.php
'functions' => [
// Other functions
'method_field' => [
'is_safe' => [true],
],
],
I am working on a project using symfony framework. I just want to make a simple search function wherein it can search all the entities that contain with what the user inputted. When I tried to run my code, its not working it keeps on redirecting to my no found result even if their is a related files to be found with.
Here is my controller:
public function searchAction(Request $request){
$request = $this->getRequest();
$data = $request->request->get('search');
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT a,b,c
FROM SampleBundle:transactionDetail a
JOIN a.transaction b
JOIN b.documentRelated c
WHERE a.pNumber LIKE :data
AND b.senderId LIKE :data
AND b.receiverId LIKE :data
AND b.transactDate LIKE :data
AND a.amountPaid LIKE :data')
->setParameter('data',$data);
$res = $query->getResult();
if($res == null){
return $this->render('SampleBundle:Sample:noresult.html.twig');
}
return $this->render('SampleBundle:Sample:search.html.twig', array('res' => $res));
}
and for my search.html.twig
{% extends '::layout.html.twig' %}
{% block pageTitle %} Related Files Found{% endblock %}
{% block body %}
div class="table-responsive margins" >
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
<thead>
<tr style="height: 40px; ">
<th>Transaction Date</th>
<th>Sender ID</th>
<th>Receiver ID</th>
<th>P Number</th>
<th>Amount Paid</th>
</tr>
</thead>
<tbody>
<tr>
{% for res in res %}
{% for other in res.transaction %}
<td >{{res.transaction.transactDate|date('YMd')}} {{res.ediTransaction.transactionDate|date('H:i')}}</td>
<td>{{res.transaction.senderId}}</td>
<td >{{res.transaction.receiverId}}</td>
{% if other.pNumber != null %}
<td style="word-break: break-all">{{other.pNumber}}</td>
{% else %}
<td>N/A</td>
{% endif %}
{% if other.amountPaid != null %}
<td style="word-break: break-all">{{other.amountPaid}}</td>
{% else %}
<td>N/A</td>
{% endif %}
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
{% block javascripts %}
{% javascripts
'bundles/sampledoc/js/jQuery.js'
'bundles/sampledoc/js/bootstrap.js'
%}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
my form for searching:
<form action="{{path('sample_search')}}" method="POST">
<div class="form-group input-group">
<input type="text" name="search" class="form-control" placeholder="Search" style="width: 200px; float: right;" >
<span class="input-group-btn"><button class="btn btn-default" type="submit" style="margin-right: 20px;"><i class="fa fa-search"></i></button></span>
</div>
</form>
Can somebody help me with this one? thanks in advance.
Data can't equal all your criteria. If you AND everything in your query data has to match all fields, so you will probably return no results.
Try something like:
WHERE a.pNumber LIKE :data
OR b.senderId LIKE :data
OR b.receiverId LIKE :data
OR b.transactDate LIKE :data
OR a.amountPaid LIKE :data')
->setParameter('data', "%$data%");
And look at the generated SQL with
$query->getSQL()
This way you can actually test your query directly on the DB.
Assuming $data is an associative array holding all the goodies, I do not think you can just hand it to setParameter() the way you are doing. You need to break it down more specifically, for each of those "LIKE" clauses.
Completely untested but I suspect you are looking for something like:
`
WHERE a.pNumber LIKE :pNumber
AND b.senderId LIKE :senderId
AND b.receiverId LIKE :recieveId
AND b.transactDate LIKE :transactDate
AND a.amountPaid LIKE :amountPaid')
->setParameters(array(
'pNumber' => $data['pNumber'],
'receiverId' => $data['receiverId'],
'transactDate' => $data['transactDate'],
'amountPaid' => $data['amountPaid'],
));
`
Im relatively new to web development and html forms. In my webapp i have a list (of gpstracks) and each list entry has a checkbox so the user can edit, delete, download, whatever... all selected tracks at once. In order to increase usability i would like to add an "select all" button or checkbox, that automatically checks all other checkboxes in the form (preferably without reloading the entire form).
Is there any possibility at all to do this? I have been trying to use
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($tracks){
$form = $event->getForm();
foreach($tracks as $track)
{
$form->get($track->getId())->setData(array('checked'=>true));
}
}
in combination with a second button of the type 'submit' that reads 'select all'. Obviously, this reloads the entire form. But after the reload all checkboxes remain unchecked, so the setData method seems to have no effect at all.
Is there any option to programmatically check checkboxes checkboxes in a form, preferably even without reloading the entire form?
Using jquery:
// cerad.js
Cerad = {};
Cerad.checkboxAll = function(e)
{
var nameRoot = $(this).attr('name'); // "refSchedSearchData[ages][]";
nameRoot = nameRoot.substring(0,nameRoot.lastIndexOf('['));
var group = 'input[type=checkbox][name^="' + nameRoot + '"]';
var checked = $(this).prop('checked') ? true : false;
$(group).prop('checked', checked);
};
{# searchform.html.twig #}
{# form.dates is an array of form check boxes #}
{% if form.dates is defined %}
{% set items = form.dates %}
<td>{% include '#CeradGame/Project/Schedule/Twig/ScheduleSearchCheckboxes.html.twig' %}</td>
{% endif %}
{# ScheduleSearchCheckboxes.html.twig #}
{# render one set of check boxes as a table #}
{# Setting a class on the first item #}
<table border="1">
<tr><th colspan="30">{{ items.vars.label }}</th></tr>
<tr>
{% set itemFirst = true %}
{% for item in items %}
<td align="center">{{ form_label(item) }}<br />
{% if itemFirst %}
{{ form_widget(item, { 'attr': {'class': 'cerad-checkbox-all' }}) }}
{% set itemFirst = false %}
{% else %}
{{ form_widget(item) }}
{% endif %}
</td>
{% endfor %}
<tr>
</table>
// Grab all the cerad-checkbox-all elements and pass to Cerad.checkboxAll
{% block javascripts %}
<script type="text/javascript">
$(document).ready(function()
{
// checkbox all functionality
$('.cerad-checkbox-all').change(Cerad.checkboxAll);
});
</script>
{% endblock %}
set html class for checkboxes (in form builder set option attr['class'])
add button with other class
add event to catch click on button 2, and check checkoxes
http://www.sanwebe.com/2014/01/how-to-select-all-deselect-checkboxes-jquery