true decision with findOneBy in symfony - symfony

I create a function like that :
public function getBookTitle(string $page){
return $this->entityManager->getRepository(BookContent::class)?
->findOneBy(["page"=>$page])?->getTitle();
}
I get this error : Impossible to access an attribute ("title") on a null variable.
When I use the same code with $id it work fine :
$this->entityManager->getRepository(BookContent::class)-
>findOneBy(["id"=>$id])?->getTitle();
Any Idea?

Related

Entity object to array

I'm trying to convert an entity to a associative array.
It seems that the method toArray() is not available for entity objects.
Reading Symfony doc, it seems I should use the SerializerInterface.
After enabling it, I can't seems to find the right syntax to convert my entity into an associative array.
Can someone correct my code please?
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
// -----------------------
public function salleAction(Request $request, Projet $projet, SerializerInterface $serializer) {
return this->json(array(
'projet'=>$serializer->serialize($projet, new ObjectNormalizer())
));
}
With the code above, I'm getting this error message
Warning: Illegal offset type in isset or empty
If I replace new ObjectNormalizer() by 'jsons', I'm getting the next error message:
A circular reference has been detected when serializing the object of class "AppBundle\Entity\Projet" (configured limit: 1)
I suggest you to add the following method to an object, that needs to be converted
public function toArray()
{
return get_object_vars($this);
}
and use it everywhere $array = $projet->toArray();

using google analytics in laravel project

hey guys i'm trying to use google analytics in my project but i always get an error : Argument 1 passed to Spatie\LaravelAnalytics\LaravelAnalytics::__construct() must be an instance of Spatie\LaravelAnalytics\GoogleApiHelper, none given
actually i don't know how to deal with that error as it's my first time to use it .
that's simply the code i've written :
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Product;
use App\ProductTrans;
use App\Service;
use Spatie\LaravelAnalytics\LaravelAnalytics;
class HomeController extends Controller {
//
public function getIndex() {
$services = Service::get();
$products = Product::get();
$analyticsData =new LaravelAnalytics();
$analyticsData->getVisitorsAndPageViews();
dd($analyticsData);
return view('admin.pages.home',compact('services','products'));
}
so can anyone help me ?

How to use the User value resolver in Symfony 3.2?

I'm building a small website using symfony 3.2.
There is a page in which the user can change its profile data with a form. I used the structure seen in the official tutorial. Here is the declaration of my controller :
/** #Route("/profil", name="profil_show_user") */
public function userProfileAction(Request $request, UserInterface $user) {
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
throw $this->createAccessDeniedException();
}
//...
$user->getProfile();//and do stuff
//...
}
My problem is that if the user is disconnected for being inactive for too long, or if someone bookmark the page but is not connected, I have this ugly error coming :
Controller
"AppBundle\Controller\ProfilController::userProfileAction()" requires
that you provide a value for the "$user" argument. Either the argument
is nullable and no null value has been provided, no default value has
been provided or because there is a non optional argument after this
one. 500 Internal Server Error - RuntimeException
In the New in Symfony 3.2 changelog, there is something about the new User value resolver. I tried to change to UserInterface $user = null, and it make the page redirect to the path I set in failure_path of security.yml, which is the good behaviour.
But then if I'm connected and go to profil_show_user, I get that other error :
Error: Call to a member function getProfile() on null
I search thoroughly the symfony documentation but couldn't find anything.
Could someone explain to me what goes wrong, what I misunderstood and how can I make this work ?
EDIT :
I thought I might say that if I don't use te value resolver, everything works fine. This is an educationnal and curiosity question about a new feature which I don't manage to use. This code works :
/** #Route("/profil", name="profil_show_user") */
public function userProfileAction(Request $request) {
$user = $this->getUser();
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
throw $this->createAccessDeniedException();
}
//...
$user->getProfile();//and do stuff
//...
}

Symfony3 get parameters from URL

I discovering symfony3, but im stuck at getting the parameters passed with a link from an action.
In my twig file, im redirecting the user to an action:
<td>go to</td>
And im my action, i'm trying to get the id with:
/**
* #Route("/AfficheDetail", name="esprit_park_affiche")
*/
public function afficheAction()
{
$id = $this->getParameter("id");
return $this->render("#EspritPark/Voiture/affiche.html.twig", array("id" => $id));
}
but each time i get: The parameter "id" must be defined.
like the getParameter isnt returning anything.
I even tried with:
$id = $this->get("request")->get("id");
but i get: You have requested a non-existent service "request". Did you mean one of these: "monolog.logger.request", "request_stack", "router.request_context", "data_collector.request"?
The getParameter() method from the base Controller class is looking up parameters from the service container.
I would make the parameters part of your route. You can then retrieve the values through the action method's parameters:
/**
* #Route("/AfficheDetail/{id}/{serie}/{dateMise}/{marque}", name="esprit_park_affiche")
*/
public function afficheAction($id, $serie, $dateMise, $marque)
{
// ...
}
If you do not add them to the route pattern, they will be accessible through the URL parameters (the current request will be injected automatically if you type hint an argument with the Request class):
public function afficheAction(Request $request)
{
$id = $request->query->get('id');
$serie = $request->query->get('serie');
$dateMise = $request->query->get('dateMise');
$marque = $request->query->get('marque');
// ...
}

Class not found when trying to index documents using Solr with Symfony2

I am very new to Solr and I am probably missing something simple however, having followed Xavier Briand's presentation I have set up Symfony2, Solarium and Nelmio\SolariumBundle.
"nelmio/solarium-bundle": "2.0.*#dev",
"solarium/solarium": "3.0.*"
Having implemented a toSolrDocument method for my doctrine php object.
public function toSolrDocument(\Solarium_Document_ReadWrite $doc)
{
$doc->id = $this->getId();
$doc->description = $this->getTitle();
$doc->path = "path";
return $doc;
}
I am faced with the following error.
Catchable Fatal Error: Argument 1 passed to ::toSolrDocument() must be an instance of Solarium_Document_ReadWrite, instance of Solarium\QueryType\Update\Query\Document given, called in Controller.php
The controller calling this toSolrDocument method has the following function
public function indexItems(){
$client = $this->get('solarium.client');
// get an update query instance
$update = $client->createUpdate();
// create documents
$documents = array();
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('<Bundle>:<Object>');
$items = $repo->findAll();
foreach ($items as $item) {
$documents[] = $item->toSolrDocument($update->createDocument());
}
// add the documents and a commit command to the update query
$update->addDocuments($documents);
$update->addCommit();
// this executes the query and returns the result
$result = $client->update($update);
}
Most of this method again comes directly from Xavier's presentation and it is clear to see that the method $update->createDocument() does not return the correct type. In fact it returns an instance of the my php object. Does anyone know where I am going wrong here? Another thing that might be of help is that even when I try to pass a Solarium Document directly I get an exception.
foreach ($items as $item) {
$rw_item = new \Solarium_Document_ReadWrite();
$documents[] = $item->toSolrDocument($rw_item);
}
The exception is
FatalErrorException: Error: Class 'Solarium_Document_ReadWrite' not found in
I can't seem to find this class in any of the bundles and I am wondering if my setup might be causing the issues. Any help would be very much appreciated.
One additional point to note is that when I am running the solr jar I see the query requests come in from my symfony2 page it is only this indexing action that I can not work out so the config may be alright and I am miss understanding the use of the bundle.
You just need to use the correct class for the argument.
use Solarium\QueryType\Select\Result\AbstractDocument;
...
public function toSolrDocument(AbstractDocument $doc)
{
You could also not type hint it:
public function toSolrDocument($doc)
{

Resources