Rectangle 27 2

The reason is that the container is injected into controllers that implementContainerAwareInterface

Symfony\Bundle\FrameworkBundle\Controller\Controller

TLDR: setter-injection is performed after the object has been constructed.

As a result you aren't able to do ...

$service = $this->get('service');
// ... or ...
$service = $this->container->('service');

... inside the __construct() method because the setContainer() method wasn't called and $this->container is not set yet.

You can read more about the different types of injection in the documentation.

Have a look at the following code parts:

$this->DefaultService = $this->get("trollmaster.default_service");

yes, or even better: don't extend Controller but configure your controller class as a service explicitly - then inject the trollmaster.default_service among all the other service dependencies directly into the constructor. (as Markus suggested)

so, how should looks exampleController with exampleAction and exampleService with exampleMethod? I have got little problems to make it correctly :(

php - symfony2: service access in controller throws exception - "Error...

php symfony service dependency-injection
Rectangle 27 2

You could use the response component of Symfony to send specific response from your controller. Add

use Symfony\Component\HttpFoundation\Response;
return new Response($return,200,array('Content-Type'=>'application/json'));

Here, $return is a json entity. 200 is the status code of the response, and 'Content-Type'=>'application/json' has to match the type of $return.

EDIT FOR JS: you can't change your javascript via ajax using twig. You should define global variables in your javascript and follow through them whatever parameter you need. These global variables are accessible in your javascript when you treat the ajax response. For instance, you could do in twig:

<script>
var globalMonth = {{ month }}; // set up the starting month
...

And then when ajax send the response, you update globalMonth and use it for the next ajax call.

$return=$this->renderView('CDUserBundle:Default:prof_calendrier.html.twig', array( 			'next_cours' => $nextCours, 			'today' => date('D'), 			'nextWeek' => $nextWeek, 			'lastWeek' => $lastWeek, 			'datesWeek' => $datesWeek 		)); 		return new Response($return,200,array('Content-Type'=>'text/html'));

And firebug still does not show javascript in source code ... Why ?

Maybe you should try to use ids instead of classes for the nextWeek and lastWeek buttons. Also I see you are using a calendar class. Do you have more than one calendar in play?

php - Symfony2 Controller,View and JavaScript - Stack Overflow

php javascript symfony controller twig
Rectangle 27 1

The kernel.root_dir is the absolute path of the root dir of the symfony application so you don't need the __DIR__ . But you need to ask to the container the value of the params.

As example, you can do (in your controller):

$root_dir = $this->container->getParameter('kernel.root_dir');
$menu_yml = $root_dir.'/app/config/main_menu.yml';
$menu = Yaml::parse($menu_yml);

You can check the value of the parameters via command line with the command:

symfony - Call an .yml file located in app/config from inside a contro...

symfony
Rectangle 27 1

Don't know, which class you extended, but the symfony controller doesn't have a constructor. Thus it's exactly, like the message suggest

Fatal error: Cannot call constructor in
/Sites/src/DEMO/DemoBundle/Controller/Frontend/HomeController.php on line 11

Line 11 is "parent::__construct();"
public function __construct()
{
    $user = $this->get('security.context')->getToken()->getUser();
}

Worth to note, that you don't even need to extend any class, or implement any interface. A symfony2-controller can be a completely independent standalone class.

the Official Documentation is shockingly bad!

Where does the documentation suggest to call the parents constructor ;)

symfony - symfony2 - how override controller __construct - Stack Overf...

symfony controller php
Rectangle 27 1

This is because the constructor isn't aware of the container (like nifr explained.). But you can define your controller itself as a service. This would be best practice i guess, although I don't know what you are trying to achive.

php - symfony2: service access in controller throws exception - "Error...

php symfony service dependency-injection
Rectangle 27 6

When you call $this->get("your.service") you are asking the dependency injection container to load that service. You are requesting that it loads one of your controllers which extends Symfony's controller class which extends ContainerAware. The error you are getting is because the loaded controller is likely trying to access a service like "request" using $this->container->get("request") but $this->container is not set.

ContainerAware has a method setContainer which you can actually run when your service is setup by using the calls: argument in services.yml:

services:
   cj.businessbundle.purchase:
      class: CJ\BusinessBundle\Controller\PurchaseController
      calls:
        - [setContainer, [@service_container]]

Symfony2 does this for the loaded controller (PurchaseOrderController) but not if you just load a controller class yourself.

It would be much better practice to extract the newAction (or the required logic) from PurchaseController as a service itself rather than setting the whole controller as a service. This way both Purchase and PurchaseOrder controllers can call the service to create a new purchase (or whatever newAction does) and you are not loading a whole controller everytime. Check out the FOS user bundle user manager for a good example of a service or http://symfony.com/doc/2.1/book/service_container.html#what-is-a-service

@Luke Thanks a ton man. Hey can you point something that will have me build an ajax form. Like a purchase order form I want to have add option to add new items to it. like add new item button would add fields to form via ajax

The symfony2 docs have a section on collections and using jQuery (in their example) to add new tags to a task symfony.com/doc/2.1/cookbook/form/form_collections.html. Not sure if thats what you mean

php - Accessing Method Through Service --- Symfony2 - Stack Overflow

php symfony
Rectangle 27 1

In your second controller you didn't suffix the method name with Action then, it is not really an end point. your code for the second controller should be:

namespace MO\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

 class MetatagsController extends Controller {

  public function metatagsAction() {

      $vm = $this->get("vehicles_manager"); // SERVICE IN QUESTION

      $result = $vm->getVehicleDetail($idVehicle);

  }

}

symfony - Symfony2 "Fatal error: Call to a member function get() on a ...

symfony service controller
Rectangle 27 1

1) By accessing the '_controller' parameter of the request, you are delving into the internals of Symfony2. They rarely document anything related to this outside of routing. You should use controller actions more definitively, don't try to automate too much on this level.

2) Symfony2 can't account for highly dynamic controllers. You know it is possible to call ->forward more than once, and within the same controller action. This creates a nesting nightmare that the Symfony developers weren't prepared to deal with.

$request = $this->container->get('request');
$stack = $this->container->get('request_stack');

3) Also deprecated. Symfony2 best practices now discourages the use of @Template() with empty parameters because of the potentially volatile development of actions/templates. You are supposed to explicitly define which template to use, if you use one at all. This comes in handy when dealing with data-only responses. You wouldn't want your responses to use a template automatically as this would result in unexpected behaviour in your design.

Thx Flosculus, 1) sad that is is like that, i have to support old URLs and need such funtion, 2) than this do not work eihter => i have to to do it on myown 3) is ok 4) is simply bad programming than...

@Gizzmo While 4) may be a little inconsistent with the general design of symfony, it is not bad practice. The use of public properties is a paradigm of older OOP languages and has been incorporated into PHP. If ever true getters and setters are implemented to PHP, you would no longer consider it bad design.

wut;-) it is not bad practice? sure it is bad ihmo. But What you mean by "true getters and setters..."

@Gizzmo stackoverflow.com/a/17881367/1692906 These are ideal. Opposed to the current get* and set* methods we are used to creating.

php - How to solve some problems in symfony 2? - Stack Overflow

php symfony frameworks
Rectangle 27 1

1) By accessing the '_controller' parameter of the request, you are delving into the internals of Symfony2. They rarely document anything related to this outside of routing. You should use controller actions more definitively, don't try to automate too much on this level.

2) Symfony2 can't account for highly dynamic controllers. You know it is possible to call ->forward more than once, and within the same controller action. This creates a nesting nightmare that the Symfony developers weren't prepared to deal with.

$request = $this->container->get('request');
$stack = $this->container->get('request_stack');

3) Also deprecated. Symfony2 best practices now discourages the use of @Template() with empty parameters because of the potentially volatile development of actions/templates. You are supposed to explicitly define which template to use, if you use one at all. This comes in handy when dealing with data-only responses. You wouldn't want your responses to use a template automatically as this would result in unexpected behaviour in your design.

Thx Flosculus, 1) sad that is is like that, i have to support old URLs and need such funtion, 2) than this do not work eihter => i have to to do it on myown 3) is ok 4) is simply bad programming than...

@Gizzmo While 4) may be a little inconsistent with the general design of symfony, it is not bad practice. The use of public properties is a paradigm of older OOP languages and has been incorporated into PHP. If ever true getters and setters are implemented to PHP, you would no longer consider it bad design.

wut;-) it is not bad practice? sure it is bad ihmo. But What you mean by "true getters and setters..."

@Gizzmo stackoverflow.com/a/17881367/1692906 These are ideal. Opposed to the current get* and set* methods we are used to creating.

php - How to solve some problems in symfony 2? - Stack Overflow

php symfony frameworks
Rectangle 27 1

If I have understood, you want to create and store new clients in a Form "on fly", at the moment. I think that you have to do that using JavaScript and set an additional action in your controller.

  • JS -> Capture the event to add new client to you database (i.e. "Add new" button click event)
  • JS -> Inside this event, call via AJAX to your controller with the values of new client. (Using FOSJsRoutingBundle is easy to do)
  • Symfony2 -> Inside your new action, store the new client in your database.
  • JS -> OnSuccess event, in your AJAX call, add the new Client to your DropDownBox (ddb.append(new element tag)

Just doing that you have your new client stored in the database and added to your dropdownbox

The idea was to create a dropdown showing the existing clients, but also the ability to create a new client (if not present on the list) in the same form. And I decided indeed to use some js to achieve this behaviour.

symfony - Symfony2 Form : Select an entity or add a new one - Stack Ov...

forms symfony
Rectangle 27 0

To get the POST parameter, it's better to be explicit and use $request->request->get('type'). This will only get the POST parameter 'type' and not the GET parameter 'type'.

Next, a controller always returns a Response. This class can be seen as a PHP port of the real HTTP response. So you can tweak it to return XML.

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class YourController // ...
{
    function someAction(Request $request)
    {
        // ...

        $response = new Response(<<<EOX
<?xml version="1.0" ?>
<Loadinglist>
</Loadinglist>
EOX
        );
        $response->headers->set('Content-Type', 'text/xml');
    }
}

php - Ajax call to Controller and XML response Symfony2 - Stack Overfl...

php jquery ajax xml symfony2
Rectangle 27 0

Try create service number_format and then invoke it in twig extenstion. In this way you can use it in twig and other services :)

yeah, can we not directly call twig extension filter or function from anywhere outside twig template ?

symfony2 - How to call Twig extension filter or function from PHP (con...

php symfony2 twig
Rectangle 27 0

I don't know this can help you, and also it's not so clear how are you getting $request variable (would be better if you include your action to the question), but I think you doing something wrong here: .load() - loads data by POST if you provide object as data, so you're passing object, and POST request is being sent, but why are getting values as $request->get('start')?

I think you should follow Patt's answer, but instead of getting values by $request->get() you should use '$request->request->get('SOME_DATA')' (by POST), or $request->query->get('SOME_DATA') (by GET).

symfony2 - How to call a Symfony controller with post data in a jQuery...

jquery symfony2 post jquery-dialog
Rectangle 27 0

This is because the constructor isn't aware of the container (like nifr explained.). But you can define your controller itself as a service. This would be best practice i guess, although I don't know what you are trying to achive.

php - symfony2: service access in controller throws exception - "Error...

php symfony2 service dependency-injection
Rectangle 27 0

If by user action you mean executing a controller action (i.e. server side), what I would do is listen to the kernel.controller event: http://symfony.com/doc/current/book/internals.html

so you can load your script and execute it juste before the target controller is invoked

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

public function onKernelController(FilterControllerEvent $event)
{
    $controller = $event->getController();
    //...
    // call your php file here

    // the controller can be changed to any PHP callable
    $event->setController($controller);
}

I don't think you even need to modify the controller so you can remove the first and last line...

There is a more detailed description of this method here matt.drollette.com/2012/06/

php - Symfony2: Call a Controller /File on EVERY action - Stack Overfl...

php javascript service symfony2 controller
Rectangle 27 0

The best practise is to use the form_widget, because it takes the name of your form (LencoBundle\Form\NotificationType) and use it for the name of the inputs, in this case I imagine your form getName() function returns "notification" and it has a field named "type", otherwise it won't work. (Maybe a typo or the camelized name)

You should use form_widget directly, and I advice you to use form_rest to add the CSRF protection to your forms automaticaly. You can use it for a form field instead the full field, either using it by itself or the combination of form_label + form_widget + form_errors.

If you need to modify the template of how is renderer you can do it anyway with Twig, using form themes.

If I am using form_widget(edit_form) its showing all database fields. But I need to show some fields only. So I wrote like this but it cannot call controller. If I use form_widget it can call controller.

You can use form_widget for a single field of the field: form_widget(form.type)

symfony - Symfony2 twig edit form not calling the controller - Stack O...

symfony twig
Rectangle 27 0

If you've created the Form using your Entity Class, which seems to be the case according to your code, you don't need to edit the form widget.

if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($notification);
$em->flush();

return $this->redirectToRoute(//Your route to success);
}

@Bandana Answer should be more descriptive than just the link beacuse the link can be dead anytime

symfony - Symfony2 twig edit form not calling the controller - Stack O...

symfony twig
Rectangle 27 0

Every framework has it's own characteristics. To me, rough example below is the easiest way so you should be able to call it via http://www.my_app.com/dog/bark/loudly

namespace MyAppBundle\Controller\DogController;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route("/dog", service="my_application.dog_controller")
 */
class DogController extends Controller
{
    /**
     * @Route("/bark/{how}")
     */
    public function barkAction($how)
    {
        return new Response('Dog is barking '.$how);
    }
}
services:
    my_application.dog_controller:
        class: MyAppBundle\Controller\DogController

php - Symfony2 directly call actions of controllers without routing - ...

php symfony routing frameworks
Rectangle 27 0

The JsonResponse's constructor doesn't take the callback argument. You need to set it via a method call:

$response = new JsonResponse($result);
$response->setCallback($callback);

return $response;

json - Returning JSONP from Symfony2 controller using AJAX call - Stac...

json symfony jsonp
Rectangle 27 0

To return a json response in Symfony2, you have to return this from the controller called by the route defined for company/booth/2:

use Symfony\Component\HttpFoundation\Response;

class YourController
{
    public function YourAction()
    {
        $response = json_encode(array('message' => 'hello'));

        return new Response($response, 200, array(
            'Content-Type' => 'application/json'
        ));
    }
}

The 200 in the response is the Http Status Code. 200 means "the request was fulfilled".

Thanks for the reply! However, this did not work. I am still getting the same error.

I forgot the json_encode() part. Try this new version, it should work with this simple array. However, you will have to serialize your entity to deliver Json content about your Doctrine's Entity.

+1, it worked! Thank you! It turns out it was a problem with the routing. I had to remove the 2 from the path... and adjust the routing.yml/ controller accordingly. Question, what is the 200 for in the response?

@AnchovyLegend nice ;) - did you manage to deliver what you wanted in the end?

@AnchovyLegend 200 is http status code for "request fulfilled". Basically, it tells the browser that everything went ok in the delivery. 500 for instance (what you had previously) would be Internal Server Error.

jquery - Receiving a json response in Symfony 2 - Stack Overflow

jquery ajax json symfony2