We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Arrays are not showing on website - Phalcon Translation with volt template

Hey guys I need help because I am with difficulties on showing the arrays in my website screen.

Here it is my UserController.php where I call the translation:

<?php

    class UserController extends \Phalcon\Mvc\Controller
    {

    protected function _getTranslation()
    {

    //Ask browser what is the best language
    $language = $this->request->getBestLanguage();

    //Check if we have a translation file for that lang
    if (file_exists("app/messages/".$language.".php")) {
       require "app/messages/".$language.".php";
    } else {
       // fallback to some default
       require "app/messages/en-US.php";
    }

    //Return a translation object
    return new \Phalcon\Translate\Adapter\NativeArray(array(
       "content" => $messages
    ));

        }

        public function indexAction() {
      $this->view->setVar("t", $this->_getTranslation());
        }
    }

?>

Here it is the index.volt where it is the content:

<div class="introduction-section" id="page-top">
  <h1><span class="glyphicon glyphicon-shopping-cart"></span>{{ t['Do-you-shop-a-lot']  }}?</h1>
  <br clear="all">
  <ul class="explore btn-explore">
    <li><a href="/shop">{{  t['Shop-Now'] }}</a></li>
  </ul>
</div>
<div class="about-section" id="about">
  <h1>{{ t['About'] }}</h1>
  <br clear="all">
  <p>{{ t['AboutDesc']  }}</p>
  <br clear="all">
  <br clear="all">
  <blockquote>{{  t['blockquote']  }}</blockquote>
</div>
<div class="partners-section" id="partners">
  <h1>Partners</h1>
  <br clear="all">
  <p>Still looking for partners :(</p>
</div>
<div class="services-section" id="services">
  <h1>Services</h1>
  <br clear="all">
  <br clear="all">
  <br clear="all">
  <div class="shop-cart-service">
    <figure>
      <img src="https://mashop.com/img/shop-cart.png" width="35%" />
      <h1>Online Shopping</h1>
      <figcaption>A easy way to shop with a better UI/UX for our clients</figcaption>
    </figure>
  </div>
  <div class="daizpay-service">
    <figure>
      <img src="https://mashop.com/img/dayz-pay.png" width="35%" />
      <h1>Daiz Payment's Gateway</h1>
      <figcaption>A better way to do payments through our online shop</figcaption>
    </figure>
  </div>
</div>
<div class="contact-section" id="contact">
  <h1>Contacts</h1>
  <br clear="all">
  <br clear="all">
  <div class="contacts-form">
    <div class="form-message"></div>
    <form action="" method="POST" class="ajax">
      <label for="nome" class="name-label">Name:</label><br clear="all" />
      <input type="text" name="name" id="name" /><br clear="all" />
      <br clear="all" />
      <label for="email" class="email-label">Email:</label><br clear="all" />
      <input type="email" name="email" id="email" /><br clear="all" />
      <br clear="all" />
      <label for="subject">Subject:</label><br clear="all" />
      <input type="text" name="subject" id="subject" /><br clear="all" />
      <br clear="all" />
      <label for="message">Message:</label><br clear="all" />
      <textarea rows="4" cols="49" name="message" id="message"></textarea><br clear="all" />
      <br clear="all" />
      <input type="submit" value="Send" id="submit" />
      <input type="reset" value="Reset" />
    </form>
  </div>
</div>

And here the en-US.php which is inside of app/messages folder where I have the arrays:

<?php

$messages = array(
  "AboutDesc" => "DaizGroup was thought and createad in 30th October 2016 in Braga. The CEO thought about this to give a easy way to people buy with a better gateway security.
  He thought it wouldn't be worst if our company just do payments of shopping retailing with secure gateways.
  Also we developed a gateway payment, easy and secure, and it works on this website. Our company sells everything from books to anything of technology. This website is also done with the heart of our own CEO and his team for our clients.",
  "Do-you-shop-a-lot" => "Do you shop a lot",
  "Shop-Now" => "Shop Now",
  "About-Us" => "About Us",
  "Partners" => "Partners",
  "Services" => "Services",
  "blockquote" => "Will not be possible if you don't have determination, passion, warrior spirit and never give up. Follow your dreams and wait for the right moment.",
  "SadPartners" => "Still looking for partners",
  "OnlineShopping" => "Online Shopping",
  "DaizGateway" => "Daiz Payment's Gateway",
  "OnlineShoppingDesc" => "A easy way to shop with a better UI/UX for our clients",
  "DaizGatewayDesc" => "A better way to do payments through our online shop",
  "Name" => "Name",
  "Email" => "Email",
  "Subject" => "Subject",
  "Message" => "Message",
  "Send" => "Send",
  "Reset" => "Reset",
  "About" => "About"
);

?>

Any of help would be appreciated.

Thank you.

Have you tried calling it like:

{{ t._('Do-you-shop-a-lot') }}
edited Nov '16

Yes, it appears as white the page. Do I have to do something, like the GetText() ? Or it's not necessary that?

Please check error.log. Blank page is result of fatal error.

Here it's the problem, can you help me?

Change from:

$this->view->setVar("t", $this->_getTranslation());

to:

$this->view->t = $this->_getTranslation();

make any difference?

Take a look at what you get back from $this->_getTranslation() before you pass it to the view and see if you can call the $t->_('Do-you-shop-a-lot'); in the indexAction directly.

edited Nov '16

Piotr: Did not make any difference at all.

BadLuckBurt: Doesn't do anything as well.

Calling $t->_('Do-you-shop-a-lot'); definitely did 'something'. You either got the error again, this time from the controller or it went through.

Looking at your error screenshot, there are multiple calls to ->render() so are you sure you're passing the translations array to the correct view?

Well I guess so. Where can I see that, if it's correct or not? I am kind of newbie on this, so I would appreciate your help.

Thanks to the forum blocking my post because of CSRF 'protection', I'm retyping this, note to self, copy and paste before posting :)

Anyway:

If you var_dump the return value of getTranslation, you can verify if you're actually getting a translation object or something else.

public function indexAction() {
    $t = $this->_getTranslation();
    var_dump($t);
    die;
}

If it's not a translation object, make sure the files in messages/ are readable for the OS user account running your website. If it is a translation object, you can use $this->view->getActionName(); to figure out what view it will render.

It might help to list your server's OS, server software (Apache , Nginx), Phalcon version and the Phalcon example project you have used as a base. Knowing how your view object has been configured might also shed some light on things.

It did not work anything of that in this controller .........

If the call to var_dump is never reached, that means there's another controller handling your request.

So, just a few questions if you don't mind:

  1. What does the folder structure of your application look like?
  2. What does the URL that you are using to access this controller + action look like?
  3. Which Phalcon example have you used as a base (for example INVO)?
  4. Can you post the configuration of your Router object?

The more information you can supply, the better chance you'll have of someone helping out to fix it :)

edited Nov '16
  1. The structure is
/app
 /controllers
    /IndexController.php
    /LoginController.php
    /UserController.php
 /messages
    /en-US.php
    /pt-PT.php
 /models
 /views
    /index
       /index.volt
    /login
       /index.volt
    /index.volt
/public
    /css
    /fonts
    /img
    /js
    /media
    /.htaccess
    /index.php
  1. I don't know, I create only this controller because I can't use it on IndexController.php
  2. What do you mean Phalcon examples?
  3. I don't have Router Configuration ....

The Phalcon examples I'm talking about are the examples you can find here: https://docs.phalcon.io/en/latest/reference/samples.html

Most people who start out with Phalcon take one of these applications and modify it to suit their needs.

If you are not using a Router Configuration to tell your site which controller to use, it's probably defaulting to your IndexController. You can test that by modifying the indexAction function in your IndexController to assign the translation object to the view like you do in your UsersController's indexAction. If the error goes away, you'll know you're in the IndexController.

The Router is the component you can use to tell Phalcon which controller and action should be executed based on the URL. You can find more info about it here: https://docs.phalcon.io/en/latest/reference/routing.html

We'll worry about the URLs later, I think you'll need to add a Router object to your application configuration first.

What does your /public/index.php look like? I don't see a config in your folder structure so if it contains any passwords or other stuff you want to keep private, strip those out before you post it here :)

edited Nov '16

this is my public/index.php:

<?php

      try {

          //Register an autoloader
          $loader = new \Phalcon\Loader();
          $loader->registerDirs(array(
              '../app/controllers/',
              '../app/models/'
          ))->register();

          //Create a DI
          $di = new Phalcon\DI\FactoryDefault();

          //Setup the view component
          /*$di->set('view', function(){
              $view = new \Phalcon\Mvc\View();
              $view->setViewsDir('../app/views/');
              return $view;
          });*/
          // registering volt as a template engine
          $di->set('view', function() {
              $view = new \Phalcon\Mvc\View();

              $view->setViewsDir('../app/views/');

              $view->registerEngines(array(
                  ".volt" => 'Phalcon\Mvc\View\Engine\Volt'
              )
              );

              return $view;
          });

          //Setup a base URI so that all generated URIs include the "tutorial" folder
          $di->set('url', function(){
              $url = new \Phalcon\Mvc\Url();
              $url->setBaseUri('/');
              return $url;
          });

          // Setup database connection
          $di->set('db', function() {
              return new Phalcon\Db\Adapter\Pdo\Mysql(array(
                  "host" => "my_host_domain",
                  "username" => "my_database_username",
                  "password" => "database_password",
                  "dbname" => "my_database"
              ));
          });

          //Handle the request
          $application = new \Phalcon\Mvc\Application($di);
          echo $application->handle()->getContent();
          } 
          catch(\Phalcon\Exception $e) {
           echo "PhalconException: ", $e->getMessage();
       }


43.9k

Hi,

in controller, try a

var_dump($this->_getTranslation())

to see if you get a valid translate object.

Because you may have path troubles for loading language file with that instruction

require "app/messages/".$language.".php";

Also, as said above, blank page is usually a server error. See http response header and webserver log).

Still not working...



43.9k

hey,

what doesn't work ?

what does var_dump($this->getTranslation()) output ?

There is no output...

You don't break execution.

var_dump($this->getTranslation()); die();

Still not working yet. May I suggest if some one of you can help me with the project (translation part) coding and I credit you? If not possible, I would like to post in github my project so you guys could help me in there. Is that possible?

Show project on github. I check it in the evening for free. ;-)

Akagiharu, it would help if you avoid the 'still not working' mantra without giving more information on what you have tried.

Try adding this to your public/index.php after you set the database connection.

    // Create the router
    $router = new Router();

    $router->add('/:params',[
        'controller' => 'index',
        'action' => 'index',
        'params' => 1
    ])->setName('default');

    $router->add('/:controller/:action/:params',[
        'controller' => 1,
        'action' => 2,
        'params'=> 3
    ])->setName('controllers');

    $router->removeExtraSlashes(true);
    $di->set('router', $router);

This router should allow you to visit /user/index/

I posted in github today because yesterday went to the websummit, so I just got it today on github, if you want to check it's the project "MyRealProject" beware that I am using a virtual machine and somethings like videos or pictures may not work for you.

Show project on github. I check it in the evening for free. ;-)

Check this... https://github.com/akagiharu/MyRealProject/pull/1

You took a few little bugs.

You should read about PSR. ;-)

I try like you said but doesn't show neither the $t echo or other thing :/ and if I post what's inside of UserController.php inside of IndexController it will appear a blank website

Check this... https://github.com/akagiharu/MyRealProject/pull/1

You took a few little bugs.

You should read about PSR. ;-)

It's working in my instance. Which version of PHP and Phalcon you use?

Phalcon Version: 2.0 PHP: 5x

It's working in my instance. Which version of PHP and Phalcon you use?

I use PHP 7 and Phalcon 3.0.1. Try this combination.

How do I install it in Vagrant?

I use PHP 7 and Phalcon 3.0.1. Try this combination.

I don't know. I'm using custom made virtual machine.

I forgot to extends to UserController from IndexController but after that I don't know what to do.

I don't know. I'm using custom made virtual machine.