2016-10-03 7 views
2

Laravel/Symfonyがコンソールの一部として提供する「選択」機能を使用しようとしています。数値インデックスに関しては問題があります。Laravel choiceコマンドの数値キー

私は文字列の値を表示するが実際に文字列ではなく関連付けられたIDを返すという意味で、HTML select要素の動作をシミュレートしようとしています。

例 - 残念ながら$選択肢は常に名前ですが、私はID

<?php 

namespace App\Console\Commands; 

use App\User; 
use Illuminate\Console\Command; 

class DoSomethingCommand extends Command 
{ 
    protected $signature = 'company:dosomething'; 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function handle() 
    { 
     $choice = $this->choice("Choose person", [ 
      1 => 'Dave', 
      2 => 'John', 
      3 => 'Roy' 
     ]); 
    } 
} 

回避策たい - 私は人のIDの前に付ける場合、それは動作しますが、そこに期待していたが、別の方法であるか、これはただの制限でありますライブラリの?

<?php 

namespace App\Console\Commands; 

use App\User; 
use Illuminate\Console\Command; 

class DoSomethingCommand extends Command 
{ 
    protected $signature = 'company:dosomething'; 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function handle() 
    { 
     $choice = $this->choice("Choose person", [ 
      "partner-1" => 'Dave', 
      "partner-2" => 'John', 
      "partner-3" => 'Roy' 
     ]); 
    } 
} 
+0

「$ this」とは何ですか? –

答えて

2

私は同じ質問がありました。エンティティを選択肢としてリストしています.IDはキー、ラベルは値です。私はこれが非常に一般的なケースだと思ったので、この制限に関する多くの情報を見つけることは驚きでした。

$choices配列が連想配列の場合、コンソールはキーを値として使用するかどうかを決定します。これは、choices配列に少なくとも1つの文字列キーがあるかどうかを調べることで判断します。つまり、1つの偽の選択肢を投げることが戦略の1つです。

$choices = [ 
    1 => 'Dave', 
    2 => 'John', 
    3 => 'Roy', 
    '_' => 'bogus' 
]; 

注:として使用した場合、PHPは常にtrue intにint型の文字列表現をキャストしますのであなたは(つまり、代わりに1"1"を使用)文字列に鍵をキャストすることはできません配列キー私が採用しているの周りに


仕事はChoiceQuestionクラスを拡張し、それにプロパティを追加し、$useKeyAsValue、キーを値として使用することがあれば強制的にして、これを称えるためにChoiceQuestion::isAssoc()メソッドをオーバーライドすることですプロパティ。

class ChoiceQuestion extends \Symfony\Component\Console\Question\ChoiceQuestion 
{ 
    /** 
    * @var bool|null 
    */ 
    private $useKeyAsValue; 

    public function __construct($question, array $choices, $useKeyAsValue = null, $default = null) 
    { 
     $this->useKeyAsValue = $useKeyAsValue; 
     parent::__construct($question, $choices, $default); 
    } 

    protected function isAssoc($array) 
    { 
     return $this->useKeyAsValue !== null ? (bool)$this->useKeyAsValue : parent::isAssoc($array); 
    } 
} 

このソリューションは少し危険です。 Question::isAssoc()は、選択肢の配列の処理方法を決定するためだけに使用されることを前提としています。

関連する問題