2016-12-26 32 views
0

我試圖獲取登錄頁面中添加的新字段的數據。我做了什麼:在樹枝中添加新的全局變量

  1. 修改AccountController.php登錄功能,增加新的參數:$this->_app->login($user, $client, !empty($data['rememberme']))
  2. Userfrosting.php登錄功能我已經把它應用:$this->client = $client;
  3. setupTwigUserVariables funtion添加樹枝全球:$twig->addGlobal("client", $this->client);

問題是,在模板中,{{client.id}}什麼也沒有返回。任何幫助將不勝感激。

+0

當你將它傳遞給'$ this - > _ app-> login()'時,你最初如何設置'$ client'的值? – alexw

+0

'$ client = Client :: where('client_id',$ data ['client_id']) - > where('userid',$ user-> id) - > first();' –

+0

您能否確認那實際上是加載一個'Client'對象?也許使用'error_log($ client-> id)'? – alexw

回答

0

在UserFrosting 4中,您應該在Sprinkle的src/Twig/目錄中創建一個Twig擴展名,並將該變量添加到getGlobals的返回值中。

您的情況有點棘手,因爲我不確定client可以是一個全局變量,但同時取決於$data['client_id'] - 這似乎是一個請求參數。現在,我假設你提交這個參數的請求需要變量client

<?php 
/** 
* Stack Overflow 
* 
* @link  https://stackoverflow.com 
*/ 
namespace UserFrosting\Sprinkle\Site\Twig; 

use Interop\Container\ContainerInterface; 
use UserFrosting\Sprinkle\Site\Database\Models\Client; 

/** 
* Extends Twig functionality for the Site sprinkle. 
* 
* @author Jose Luis 
*/ 
class Extension extends \Twig_Extension 
{ 

    protected $services; 
    protected $config; 

    public function __construct(ContainerInterface $services) 
    { 
     $this->services = $services; 
     $this->config = $services->config; 
    } 

    public function getName() 
    { 
     return 'myproject'; 
    } 

    public function getGlobals() 
    { 
     try { 
      $currentUser = $this->services->currentUser; 

      // Assumes the client_id is being submitted as a query string (url) parameter 
      $clientId = $this->services->request->getQueryParam('client_id'); 

      $client = Client::where('client_id', clientId)->where('userid', $currentUser->id)->first(); 
     } catch (\Exception $e) { 
      $client = null; 
     } 

     return [ 
      'client' => $client 
     ]; 
    } 
} 

然後,您將需要註冊這個擴展在你灑的service provider class

​​

是的,我知道有很多樣板這裏。但是,一旦你第一次設置了這些,很容易在Twig環境中添加新的變量/函數/過濾器,以及將來爲Sprinkle添加新的服務。