override symfony2 bundle controller actions - symfony

/src/Vendor/JobQueueBundle/Controller/DefaultController.php
namespace Vendor\JobQueueBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\JobQueueBundle\Controller\JobController;
/**
* #Route("/jobs")
*/
class DefaultController extends JobController
{
/**
* #Route("/index")
*/
public function indexAction()
{
die();
}
}
/app/config/routing.yml
vendor_api_job_queue:
resource: "#VendorJobQueueBundle/Controller/"
type: annotation
prefix: /
JMSJobQueueBundle:
resource: "#JMSJobQueueBundle/Controller/"
type: annotation
/src/Syntetik/API/JobQueueBundle/SyntetikAPIJobQueueBundle.php
namespace Vendor\JobQueueBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class VendorJobQueueBundle extends Bundle
{
public function getParent()
{
return 'JMSJobQueueBundle';
}
}
When I try to call /jobs/index I get:
Method "JMS\JobQueueBundle\Controller\JobController::indexAction" does not exist.
DefaultController is completely ignored and not sure why?
Thanks!

It's known and opened issue of JMSDiExtraBundle https://github.com/schmittjoh/JMSDiExtraBundle/issues/39 so problem is that DiExtarBundle doesn't lookup parent class for annotations if child class has not at least one JMS annotation, so proxy class isn't generate at the metadata cache (look app/cache/dev/jms_diextra/metadata/)
The quickest solution is leave at least on annotation:
Parent Controller >>
<?php
namespace Namespace\SiteBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\DiExtraBundle\Annotation as DI;
class IndexController extends Controller
{
/**
* #DI\Inject("doctrine.orm.entity_manager")
* #var \Doctrine\ORM\EntityManager $em
*/
protected $em;
/**
* #DI\Inject("namespace.search.manager")
* #var Namespace\SearchBundle\Services\SearchManager $searchManager
*/
protected $searchManager;
/**
* #DI\Inject("namespace.product.manager")
* #var Namespace\ProductBundle\Services\ProductManager $productManager
*/
protected $productManager;
/**
* #Route("/", name="homepage")
* #Template()
*/
public function indexAction() {
echo "parent!";
$defaultCategory = $this->searchManager->getDefaultCategory();
....
return $result;
}
}
Child controller >>
<?php
namespace OtherSpace\SiteBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\DiExtraBundle\Annotation as DI;
use Namespace\SiteBundle\Controller\IndexController as BaseIndexController;
class IndexController extends BaseIndexController
{
/**
* The temprary solution base on known JMS/DiExtraBundle open issue https://github.com/schmittjoh/JMSDiExtraBundle/issues/39
* **We need to leave at leat one Inject in child class to get a proxy generated**
*
* #DI\Inject("doctrine.orm.entity_manager")
* #var \Doctrine\ORM\EntityManager $em
*/
protected $em;
/**
* #Route("/", name="homepage")
* #Template()
*/
public function indexAction() {
echo "child!";
$result = parent::indexAction();
return $result;
}
}
So this way proxy class will be generated for SpaceOther-IndexController and annotations will work
I also worked around fix this issue, you can look to my pull request https://github.com/schmittjoh/JMSDiExtraBundle/pull/153

Figured out the problem with this. It seems it's not symfony2 specific.
The problem is JMS\DiExtraBundle\JMSDiExtraBundle which mess the things around. Just removing that bundle makes everything works by the book.
Thanks!

Related

Class "Symfony\Bundle\FrameworkBundle\Controller\Controller" not found while loading "App\Controller\StudentController"

Hi I'm fresher for symfony . when i execute the below code it will show error.i installed all the assets of symfony.help me to clear this..!
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class StudentController extends Controller
{
/**
* #Route("/")
* #Method({"GET"})
*/
public function index()
{
// return new Response(
// '<html><body><h1>HI,Welcome to Tamilnadu</h1></body></html>'
// );
return $this->render('student/index.html.twig');
}
}
I just put "hello" in (student/index.html.twig),and i commented the basic response function and want to run the return this function.
Try this:
/**
* #Route("/", name="index")
* #return Response
*/
public function index():Response{
return $this->render('student/index.html.twig');
}

Symfony Route. Can't set annotations

I can't understand, if i create crud controller with
bin/console make:crud all routes work from controller
like
/**
* #Route("/", name="product_index", methods="GET")
*/
public function index(ProductRepository $productRepository): Response
{
return $this->render('product/index.html.twig', ['products' => $productRepository->findAll()]);
}
.
If i create controller with bin/console make:controller
and define controller with annotation by myself they don't work
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializerBuilder;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Product;
use App\Repository\ProductRepository;
use JMS\Serializer\SerializationContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class FirstApiController extends AbstractController
{
/**
*
* #Route("/first_api", name="first_api")
*/
public function index(ProductRepository $productRepository)
{
$data = $productRepository->findAll();
$serializer = SerializerBuilder::create()->build();
# $jsonContent = $serializer->serialize($data, 'json');
$jsonContent = $serializer->serialize($data, 'json', SerializationContext::create()->setGroups(array('details')));
$response = JsonResponse::fromJsonString($jsonContent);
return $response;
}
/*
* #Route("/first_api/send", name="send")
*
*/
public function send()
{
$a = "text";
return $a;
}
}
Why that route doesn't work
#Route("/first_api/send", name="send") ?
In routes.yaml i wrote nothing, just empty file.
I used wrong syntax !I used
/* <-- the error is here
* #Route("/first_api/send", name="send")
*
*/
I need to use
/** <-- i nee two "*"
* #Route("/first_api/send", name="send")
*
*/
public

Can disabling autowiring and using annotation instead for services in Symfony 3?

In the DI there is Autowiring, annotation definition and PHP definition.
In Symfony 3.3 the autowiring is enabled by default. So if I disable the autowiring, can I use the annotation to define a service?
class Foo
{
/**
* #Inject({"my.specific.service"})
*/
public function __construct(Bar $param1)
{
}
}
Update : Use JMSDiExtraBundle
namespace MediaBundle\Net;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;
/**
* #Service("some.service.id", public=false, environments = {"prod", "test", "dev"})
*/
class Foo
{
private $em;
private $session;
/**
* #InjectParams({
* "em" = #Inject("doctrine.orm.entity_manager"),
* "session" = #Inject("session")
* })
*/
public function __construct($em, $session)
{
$this->em = $em;
$this->session = $session;
}
}
Calling the service in the controller:
namespace MediaBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DefaultController extends Controller
{
/**
* #Route("/media")
*/
public function indexAction()
{
$someService = $this->get('some.service.id');
return $this->render('MediaBundle:Default:index.html.twig');
}
}
Result : You have requested a non-existent service "some.service.id".
Is your service injected somewhere? If not, it will be dropped from the container due to public=false, see http://symfony.com/blog/new-in-symfony-3-2-improved-private-services

Resources are not supported in serialized data

Hello everyone m working on a project there is a bundle CustomerBundle when i call a function following errors are display can anyone tell me why this error coccured..
message": "Resources are not supported in serialized data. Path:
Monolog\Handler\StreamHandler -> Symfony\Bridge\Monolog\Logger ->
Symfony\Component\Cache\Adapter\FilesystemAdapter ->
Symfony\Component\Cache\Adapter\TraceableAdapter ->
Symfony\Component\Cache\DoctrineProvider ->
Doctrine\Common\Annotations\CachedReader ->
Doctrine\ORM\Mapping\Driver\AnnotationDriver ->
Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain ->
Doctrine\ORM\Configuration -> Doctrine\ORM\EntityManager ->
CustomerBundle\Repository\CustomerRepository",
"class": "JMS\Serializer\Exception\RuntimeException",
this is my Customer entity page
/**
* #ORM\ManyToOne(targetEntity="CompanyBundle\Entity\Company", inversedBy="company_customer")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
*/
private $companyId;
/**
* #var \DateTime
*
* #ORM\Column(name="created_time", type="datetimetz")
*/
private $createdTime;
/**
* #var \DateTime
*
* #ORM\Column(name="modified_time", type="datetime")
*/
private $modifiedTime;
/**
* #ORM\OneToMany(targetEntity="SalesBundle\Entity\SalesAccount", mappedBy="customerId" )
*/
private $sales_customer_id;
CustomerApiController controller
namespace CustomerBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use CustomerBundle\Entity\Customer;
class CustomerapiController extends FOSRestController
{
/**
* #Rest\Post("/api/customer")
*/
public function customerAction(Request $request)
{
$data = $this->getDoctrine()->getRepository(Customer::class);
$data->find(1);
return $data;
}
}
I think you should have a look at this post. Similar problem can be solved in the same way.
Write a custom repository function and do the following instead of your "find(1)" :
public function findFirstElement()
{
$qb = $this->createQueryBuilder('e');
$qb->where('e.id = 1');
return $qb->getQuery()->getArrayResult();
}

Symfony2 custom validator annotation not working

I have a custom validator in src/VNN/PressboxBundle/Component/Validator/CurrentPasswordValidator.php:
<?php
namespace VNN\PressboxBundle\Component\Validator\Constraints;
use Symfony\Component\Validator\ConstraintValidator,
Symfony\Component\Validator\Constraint,
Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface,
Symfony\Component\Security\Core\SecurityContextInterface,
JMS\DiExtraBundle\Annotation\Validator,
JMS\DiExtraBundle\Annotation\InjectParams,
JMS\DiExtraBundle\Annotation\Inject;
/**
* #Validator("user.validator.current_password")
*/
class CurrentPasswordValidator extends ConstraintValidator
{
// ...
}
And then I have this at src/VNN/PressboxBundle/Component/Validator/Contraints/CurrentPassword.php:
<?php
namespace VNN\PressboxBundle\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* #Annotation
*/
class CurrentPassword extends Constraint
{
public $message = "Your current password is not valid";
/**
* #return string
*/
public function validatedBy()
{
return 'user.validator.current_password';
}
}
For some reason, when I try to add an annotation that uses this validator, I get an error. Here's my entity/annotation:
<?php
namespace VNN\PressboxBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinTable as JoinTable;
use Doctrine\ORM\Mapping\JoinColumn as JoinColumn;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\MaxLength;
use Symfony\Component\Validator\Constraints\Email;
use VNN\PressboxBundle\Component\Validator\Constraints\CurrentPassword;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* VNN\PressboxBundle\Entity\User
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User implements UserInterface, \Serializable
{
/**
* #var string $password
* #Assert\NotBlank()
* #CurrentPassword()
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
}
The error I'm getting is:
AnnotationException: [Semantical Error] The annotation
"#VNN\PressboxBundle\Component\Validator\Constraints\CurrentPassword"
in property VNN\PressboxBundle\Entity\User::$password does not exist,
or could not be auto-loaded.
What am I doing wrong?
Check that VNN\PressboxBundle\VNNPressboxBundle() is correctly registered with the kernel in AppKernel.php.
Update: If it is correctly registered, and src/ is registered as a fallback with the autoloader (assuming VNN/ is under src/), you may want to try and load the service yourself manually and check the stack trace if/when it fails:
$validator = $container->get('user.validator.current_password');
// Pretending this is a unit test:
// $this->assertInstanceOf('VNN\PressboxBundle\Component\Validator\Constraints\CurrentPasswordValidator', $validator);
Also, make sure you have cleared the cache (if not testing in dev environment).
Side note (but unrelated to your problem) - if you start to add more validators, it will be more useful to use this syntax:
<?php
namespace VNN\PressboxBundle\Entity;
use VNN\PressboxBundle\Component\Validator\Constraints as VNN;
class User implements UserInterface, \Serializable
{
/**
* #VNN\CurrentPassword
*/
private $password;
}

Resources