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.
Related
I am debugging a piece of code one of my team members has submitted, I am not too familiar with Laravel so bear with me if I've missed anything, but basically the form will submit and be redirected to the correct update controller, but when I try to get the result of one of the changed fields in the form, it is just blank.
Index Form Data
<form method="POST" action= "{{ route('apparatus_codes.update' , $apparatusCode->id )}}" class="is-readonly" >
#csrf
#method('PUT')
<tr id="table{{ $apparatusCode->id}}" data-target=".table{{ $apparatusCode->id}}">
<td class="main-bg"> {{ $apparatusCode->id}} </td>
<td class="data main-bg"><input name ="rent" id="rent" value = "{{ $apparatusCode->rent}}"/></td>
<input type="submit" id="save-button" class="save"><img class="mb-1 duration-300 ml-4 inset-0 h-6 w-6" src="/../../img/save-icon.svg" alt="save icon">
</form>
Controller
public function update(ApparatusCodesRequest $request, $id)
{
// find selected apparatus code details
$apparatusCodes = ApparatusCodes::find($id);
$test = $request->input('rent');
echo "TEST".$test;
}
If I echo the $apparatusCodes variable, this will display the correct data from the form on page load. However, I have an input field on the rent field, and the changed value for this field will not come through onto the controller. Also if I echo $request->all or dd($request->all()) there will be no data coming through. I can't tell why nothing is coming through when my form looks to be similar to others I have seen?
There are no errors appearing, it is reaching the intended controller ok it seems, but just not able to retrieve any of the inputted data. Any help would be great. Thanks.
Routes file
Route::post('/apparatus_codes/{id}', [App\Http\Controllers\ApparatusCodesController::class, 'update'] )->name('apparatus_codes.update');
ApparatusCodesRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use App\Models\ApparatusCodes;
class ApparatusCodesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// initalising so that memo rule doesn't throw error when creating new apparatus code
$stored_memo = '';
// this is returning id of current apparatusCode
$apparatusCodes_id = $this->route('apparatusCodes');
// this request is used for both create, and update
// we don't want to check for a stored memo when validating a create request
if(!$apparatusCodes_id == null){
// getting the current memo for grantor
// used to check that memo has been updated
$stored_memo = ApparatusCodes::where('id', $apparatusCodes_id)->pluck('memo')->firstOrFail();
}
return [
];
}
public function messages()
{
return [
'memo.not_in' => 'An update to the memo field is required'
];
}
}
I'm working on an upload system based on Symfony 4 and PHPSpreadsheet.
My user uploads the excel file. I then create the products/categories... At the end I want to get all categories created. The following Doctrine query :
/**
* #param $user_id
* #return array
* #throws \Doctrine\ORM\NonUniqueResultException
*/
public function checkIfNew($user_id): ?array {
return $this->createQueryBuilder('c')
->andWhere('c.categorie_parent_id is NULL')
->andWhere('c.created_by = :val')
->setParameter('val', $user_id)
->getQuery()
->getResult()
;
}
gets all my categories where created_by is by the user ID, and where Parent is null.
What I want to do is to get an array of all those categories and then redirect the user to a rendered Twig template page where he can make the link.
But I don't really understand how to use the parameters...
In my Upload I've set this :
$isNew = $this->getDoctrine()
->getRepository(Categorie::class)
->checkIfNew($this->getUser()->getId());
if (!is_null($isNew)){
$this->addFlash('success', 'Catalogue crée avec succès');
return $this->redirectToRoute('admin.categorie.link', $this->getUser()->getId());
}
I don't understand how I can use the request to redirect the user correctly using the route :
/**
* #Route("/admin/categories/import", name="admin.categorie.link", methods={"GET|POST"})
* #param Categorie $categories
*/
public function linkImport()
{
// What TODO here ?
return $this->render('admin/categories/link.html.twig', compact('categories'));
}
Well I suppose I have to add $isNew as a parameter for my request ? But did I reuse the array after to use this in my twig, and display the element from this array inside my twig.
There is a small error:
If your route is "/admin/categories/import" and you want to transfer a value like "$this->getUser()->getId()" then this should be like
Route "/admin/categories/import/{userId}" and your return would be:
return $this->redirectToRoute('admin.categorie.link', ['userId' => $this->getUser()->getId()]);
and your controller could take the userId as var:
/**
* #Route("/admin/categories/import/{userId}", name="admin.categorie.link", methods={"GET|POST"})
*/
public function linkImport(int $userId, EntityManagerInterface $em) // var name must be the same as in the route
{
// What TODO here ?
$categories = $em->getRepository(Categories::class)->findByUserId($userId);
return $this->render('admin/categories/link.html.twig', ['categories' => $categories]);
}
Now you can access your categories in twig with {{categories}}
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,
]);
}
I am building an application that uses the repository pattern. Now what I have done is reuse functionality but I have hit a bit of a hiccup. I have one view that shows several different models on it. These models are related through a one-to-one relationship (MovieBasic to MovieDetail) and one-to-many relationship (MovieBasic to MoviePersonnel). The issue I am having is that I have two different request to validate my forms. They are MovieBasicRequest, which validates my movie's basic information (Title, synopsis) and MovieDetailRequest, which validates my movie's detail information (price, screen type, runtime, etc). So to distinguish between which request to use I have added a parameter to my url as follows:
movie_basic.blade.php
<?php $params = ['id' => $movie->id, 'type' => 'movie_basic']; ?>
<h4>Movie Baiscs <span class="pull-right">Edit</span></h4>
<hr>
<table class="table table-bordered">
<tbody>
<tr>
<td>{{ $movie->movie_title}}</td>
</tr>
<tr>
<td>{{ $movie->movie_synopsis }}</td>
</tr>
</tbody>
</table>
I know that using the <?php ?> tags is not best practice but I will clean that up later. So because of my $params the URL will look like so
www.moviesite.dev/1/edit?movie_basic
Which will call the edit function in the controller like so
MovieController.php
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$movie = $this->movieBasic->find($id);
return view('cms.edit', compact('movie', 'type'));
}
In this case the type does not really play a role because of the relationship between MovieBasic and MovieDetail models. However it does play a role in my update function below:
MovieController.php
/**
* Update the specified resource in storage.
*
* #param int $id, MovieBasicRequest $request
* #return Response
*/
public function update($id)
{
if(strcmp($_GET['type'], 'movie_basic') == 0)
{
$movie = $this->movieBasic->find($id);
$this->request = new MovieBasicRequest;
$this->movieBasic->update($id, $this->request);
}
elseif(strcmp($_GET['type'], 'movie_detail') == 0)
{
$movie = $this->movieBasic->find($id);
$this->request = new MovieDetailRequest;
$this->movieDetail->update($id, $this->request);
}
return redirect()->action('MovieController#show', compact('movie'));
}
Essentially what this function does is determine what is being passed in and from there call the correct request. However the way I have it now it just creates an empty array and thus validates nothing. Is there any way to uses these requests to validate information passed in? Or to validate input before I pass it to the update function of the repository?
PS. I have also tried this:
$this->movieBasic->update($id, MovieBasicRequest $request);
but I get an "Undefined variable $request" error.
You should better combine them. And you can use sometimes on your form validation for handling both where you will only validate present fields. So that your MovieRequest can be like below
class MovieRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'movie_title' => 'sometimes|required|min:3',
'price' => 'sometimes|required|integer'
// and so on
];
}
}
So you can update your controller as below and use for the both pages. For instance, if the price is not set within the request, then it will skip validating it, but if it's present and empty, then it will throw an error message as it's required.
public function update($id, MovieRequest $request)
{
$movie = $this->Movie->find($id);
$movie->fill($request->all());
$movie->save();
return redirect()->action('MovieController#show', compact('movie'));
}
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.