Symfony 4, check if template is already loaded? - php

I have a template home.html.twig loaded and an ajax request as the code below shows. That works just fine.
But if I load my website with the route mywebsite.com/search/foo then I only have searchListing.html.twig displayed without any home.html.twig loaded so the site is broken
So is there a way in the controller, before the return, to check if my template home.html.twig is loaded and if not load it and insert searchListing.html.twig inside a block ?
my html:
<li>foo</li>
here is my ajax:
$(document).ready(function() {
$('.trigger').on('click', function(e) {
e.preventDefault();
const $link = $(e.currentTarget);
$.ajax({
url: $link.attr('href'),
type: 'get'
})
.done(function (data) {
$('#main-content').html(data)
})
});
});
my controller:
class Search extends AbstractController {
/**
* #Route("/search/{var}", name="search")
*/
public function search ($var) {
// CHECK HERE
// if home.html.twig is loaded > load searchListing.html.twig inside a given block
// if home.html.twig is not loaded > load home.html.twig then load searchListing.html.twig inside a given block
return $this->render('searchListing.html.twig',[
'var' => $var,
]);
}
}

If I understand correctly you need:
/**
* #Route("/search/{var}", name="search")
*/
public function search (Request $request, $var) {
// render only search results for ajax request
if ($request->isXmlHttpRequest()) {
return $this->render('searchListing.html.twig',[
'var' => $var,
]);
}
return $this->render('home.html.twig',[
'var' => $var,
]);
}

Related

Could not find constant name for search method

I made a search method that should allow me to search in a TWIG table, added custom repository method that would allow me to find the entity by specified attribute and called it in the controller function and also the script responsible for the search function with its input label in the twig file but I keep getting the "[Semantical Error] Couldn't find constant name, method App\Controller\InventaireContesController::searchConte() in C:\Users\maiez\Projet\config/routes../../src/Controller/ (which is being imported from "C:\Users\maiez\Projet\config/routes/annotations.yaml"). Make sure annotations are installed and enabled.
" error.
Please find below the script in the twig code containing the search function :
<script>
$(document).ready(function(){
$('#search').keyup(function(){
search_table($(this).val());
});
function search_table(value){
$('#sa tbody').each(function(){
var found = 'false';
$(this).each(function(){
if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0)
{
found = 'true';
}
});
if(found == 'true')
{
$(this).show();
}
else
{
$(this).hide();
}
});
}
});
</script>
This is the search input field :
<input id="search" class="form-control" type="text" name="search" placeholder="Rechercher..." aria-label="Search">
This is the custom method in the entity repository :
public function findContes($cnt){
return $this->createQueryBuilder('contes')
->where('contes.titre LIKE :titre')
->setParameter('titre', '%'.$cnt.'%')
->getQuery()
->getResult();
}
and this is the controller method that seems not to work :
/**
* #Route ("/invContes/search", name"searchInv")
* #param Request $request
* #param NormalizerInterface $Normalizer
* #return Response
* #throws \Symfony\Component\Serializer\Exception\ExceptionInterface
*/
public function searchConte(Request $request, NormalizerInterface $Normalizer)
{
$repository = $this->getDoctrine()->getRepository(Inventairecontes::class);
$requestString=$request->get('searchValue');
$conte=$repository->findContes($requestString);
$jsonContent=$Normalizer->normalize($conte,'json',['groups'=>'contes']);
$retour = json_encode($jsonContent);
return new JsonResponse($jsonContent);
}
Imports and twig IDs are correct.
Thank you in advance.

How to get ID from different controllers Yii2?

In the ActiveForm I have model button with Pjax render field after form from the modal button will created. Added a picture for an example. How can I get newly created id (not select added to the database, need to get the id that comes from this form).
I think I need to set get to button, than with ajax catch this and transfer to my Pjax rendered cell
I tried variations, but unsuccessfully, I cann't fully understand how to implement it. Can anyone help with the solution ?
//TwoController
public function actionCreate()
{
$model = new Formtwo();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
echo 1;
//maybe here I must to do query ?
} else {
echo 0;
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Index GridView
I hope I understood correct; you wish that when a user creates an instance of Form2, it is transferred then to create an instance of Form1, and the id of newly created record for Form2, is put in the Form1 _form.
If I did not understand correctly, please explain better :)
In TwoController create action, after creation, you would call the create action of OneContrller:
if ($model->save()) {
return \Yii::$app->runAction('/controller/action-name', ['form2_id'=>$model->id]);
}
On OneController actionCreate add parameter with default value:
public function actionCreate($form2_id=null) {
and make sure it is passed to the view (don't forget to make sure you pass it on create.php as well to the _form.
//TwoController
public function actionCreate()
{
$model = new Formtwo();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
echo $model->id;
//maybe here I must to do query ?
} else {
echo 0;
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
You don't need query. Just use $model->id. It has value after save().
Update
It doesn't matter in which controller you are. You get the id of the model saved after save(). Then you can use id attribute. So, you can open modal form with ajax load. On form2 you register script to ajax post form. Something like this:
$("#form :submit").click(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: $("#form").attr("action"),
data: $("#form").serialize(),
success: function (response) {
$("#modalid").modal("hide")
$.pjax.reload({
container: "#grid"
});
$('#Form2_id').val(response); //here you get the id
},
})
return false;
});

Post Data not working correctly Laravel

I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.
Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});
If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});

Resource index parameters

I've wrote a controller to have it's index to output the DataTables plugin data.
A excerpt:
public function index() {
return Datatable::collection(\App\Slip::where('paid', '=', false)->get())
...
->make();
}
and the route:
Route::resource('api/slip', 'SlipsController');
everything works fine, the problem is that this index return only items with paid = false that's right for one view, but for the other view I need all items/rows.
so what's the best practice to make index function cover both cases (all and those with paid = false)?
A post param is the first thing that comes to my mind, but the data is loaded by the DataTables plugin.
Why not?. You need detect your specified view and send some extra param in ajax-request. Like:
$('...').DataTable({
....
"ajax": {
'type': 'GET',
'url': "....",
'data': {paid: false},
},
....
});
Now in action:
public function index(Request $request) {
$paid = $request->input('paid');
$items = [];
if ($paid){
$items = \App\Slip::all()->get();
}else{
$items = \App\Slip::where('paid', '=', false)->get();
}
return Datatable::collection($items)
...
->make();
}

Laravel 4 routes going to wrong route

I've set up routes for a resource and added additional routes for the same controller. I've had this route working and don't think I've changed anything but now it's routing to the wrong method in the controller.
I'm aware of the first in and first out principle of the routes and have this set up at the moment:
Route::post('products/addItemToCart', array('uses' => 'ProductsController#addItemToCart'));
Route::post('products/editItemInCart', array('uses' => 'ProductsController#editItemInCart'));
//Product Related Routes
Route::get('products/saletotal/{id}', function ($id) {
return Product::groupedSales($id);
});
Route::get('products/itemValue/{id}', array('uses' => 'ProductsController#itemValue'));
Route::get('products/cartitem/{id}', array('uses' => 'ProductsController#getCartItem'));
Route::resource('products', 'ProductsController');
I have a form which POSTS to products/addItemToCart for some reason this no longer uses the method addItemToCart but is going to the controllers show method and treating the 2nd parameter as an ID of the record to find.
I placed a var_dump at the start of the show method to identify the value being passed to the show method which is addItemToCart
It's as if the routes file is ignoring the previous routes and skipping to the defaults in the resource route.
Any ideas what mistakes I've made?
Thanks
Update: additional code for fuller picture:
The POST is generated by javascript with this method:
if($('#rowId').val() !=="") {
postUrl = "/products/editItemInCart";
} else {
postUrl = "/products/addItemToCart";
}
$.ajax({
type: "POST",
url: postUrl,
data: item,
dataType: 'json',
success: function(result) {
//update the displayed Cart
var data = result;
updateCart();
}
});
item is an array
The method in Products controller are:
<?php
//updated 08-11-2013
class ProductsController extends BaseController {
/**
* Product Repository
*
* #var Product
*/
protected $product;
public function __construct(Product $product)
{
$this->product = $product;
}
public function addItemToCart() {
$product = Product::find( Input::get( 'id' ) );
//method code
}
**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
dd($id);
$product = $this->product->findOrFail($id);
return View::make('products.show', compact('product'));
}
the show method is being used instead of the expected addToCart method as specified in the URL and route
I can see the exected items in the POST from within firebug
You need to add the parameter expectation to the route string.
Route::post('products/addItemToCart/{id}', array('uses' => 'ProductsController#addItemToCart'));
Otherwise the resource controller interprets this as products/{param}/{param} hence why it goes to the default post implementation of the controller.

Categories