1

what i need

  • i just want to implement session in symfony.

here is what i tried

  • /src/Acme/bundlename/Twig

    Acmeextension.php

    public function getFunctions()
    {
      return array(
    'count'  => new \Twig_Function_Method($this, 'count'),
     );
     }   
    
    public function count()
    {
        session_start();
        if(isset($_SESSION["count"]))
        {
            $accesses = $_SESSION["count"] + 1;
        }
        else
        {
            $accesses = 1;
        }
        $_SESSION["count"] = $accesses;
        return $accesses;
    }
    

    here is the code of twig:

    function callback()
    {
        var page = {{ count}};
        if (page >4)
        {
            alert("limit exceeded");            
        }
        else
        {
          alert("ok");                 
        }
    }
    callback();
    
    calling in twig 
    {{ count }}
    

Problem

  • im not Gettig any alert in when i reload the page.
  • please tell me where im wrong , any suggestion are most welcome.
1
  • i have try debug code but still alert not working {% block myJavascript %} <script type="text/javascript"> alert("test"); </script> {% endblock %} Commented Sep 17, 2014 at 11:20

2 Answers 2

1

If you are looking to inject sessions outside of the scope meaning into your custom extension.

I would do this.

     //AppKernel +add
      protected function initializeContainer() {
          parent::initializeContainer();
          if (PHP_SAPI == 'cli') {
              $this->getContainer()->enterScope('request');
              $this->getContainer()->set('request', new \Symfony\Component\HttpFoundation\Request(), 'request');
          }
      }

Then in your services container

      <!-- Custom Twig Extensions -->
      <service id="yourid" class="yourclasspath">
        <argument type="service" id="service_container" />
        <tag name="twig.extension" />
    </service>

Then in your twig.php

     class Twig extends \Twig_extension {
         private $request;

         public function __construct(Container $container) {
              $this->request = $container->get('request');
         }

         public function getFunctions() {
           return array(
            'count'  => new \Twig_Function_Method($this, 'count'),
           );
         }    

         public function count() {
         $session = $this->request->getSession();

         if(session->has('count')) {
             $session->set('count') += 1;
         } else {
             $session->set('count') = 1;
         }

         return $session->get('count');
      }
   }

Then the same in your twig

Sign up to request clarification or add additional context in comments.

6 Comments

syntax error unexpected ->(T_OBJECT_OPERATOR) ON THIS LINE if(session->has('count')) {
@Matthew: I think you are overcomplicating it with service_container. See my answer based on yours but a bit simplified ;)
@user3785613 that is what you get for copying and pasting i left out the $ sign lol
how to solve alert issue function callback() { var page = {{ count}}; if (page >4) { alert("limit exceeded"); } else { alert("ok"); } } callback(); calling in twig {{ count }}
Whoa, slow down. You're going from one error to another without even paying attention. First thing, you cannot just use {{ count }} because Twig will think that is a variable. Instead, use {{ count() }}. As for the AcmeExtension (woot?!) please edit you question with changes you applied - only then we shall be able to help you...
|
1

Are you using some older version of Twig? Usage of Twig_Function_Method is deprecated.

If we ignore the subtle differences between older and new versions of Twig I would do it like this.

Note: This is actually @Matthew's solution and but I took liberty to simplify it a bit :)

Twig service definition

<!-- Custom Twig Extensions -->
<service id="yourid" class="yourclasspath">
    <argument type="service" id="session" />
    <tag name="twig.extension" />
</service>

Twig extension file

class Twig extends \Twig_extension {
     private $session;

     public function __construct(Session $session) {
         $this->session = $session
     }

     public function getFunctions() {
         return array(
             new \Twig_SimpleFunction('count', array($this, 'count') ),
         );
     }    

     public function count() {
         if($this->session->has('count')) {
             $this->session->set('count') += 1;
         } else {
             $this->session->set('count') = 1;
         }

         return $this->session->get('count');
     }
}

3 Comments

i have tried call count function using javascript but still there is the problem no alert works when page reload so where is the issue
Try it first without any JS. Just print: <h1>THIS IS MY CONTER {{ count() }}. Then we can trace back the error...
its now been fixed thank jperovic sol i have placed script code after body beacause of might script might collapse in page now its working fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.