【问题标题】:cakePHP build a select box from custom arraycakePHP 从自定义数组构建一个选择框
【发布时间】:2012-05-05 23:02:44
【问题描述】:

所以我们有各种各样的搜索页面,每个页面都有不同的搜索条件,所以我决定编写一个组件,该组件将获取从控制器传递给它的参数,收集必要的数据并返回一个数组,然后我可以将其设置为在我的视图文件中用于填充下拉框以过滤条件。

我已经设法将所有内容写到我必须使用 cakePHP 帮助器构建动态选择框的地方。我确信我做错了什么,如果有更简单的方法可以做到这一点并且仍然保持动态,请尽可能提供帮助:

// COMPONENT METHOD:
 public function filterQueries($parameters) {

    // Get defaults from the user:
    $criteria = $parameters["custom"];
    $defaults = $parameters["defaults"];

    // Validate the defaults the user may want and assign them to the return array:
    if($defaults != "false") {
        foreach($defaults as $key => $value) {
            if(array_key_exists($value, $this->defaults)) {
                $this->returnArray["defaults"][$value] = $this->defaults[$value];
            }
        }
    }

    // Get all data for the custom requested form fields:
    if($criteria != false) {
        foreach($criteria as $model => $arguments) {
            $fields = $arguments["fields"];
            $conditions = $arguments["conditions"];
            $recursive = $arguments["recursive"];
            if(!in_array($model,$this->uses)) {
                $useModel = ClassRegistry::init($model);
            } else {
                $useModel = $this->$$model;
            }
            $array = $useModel->find("all",array("conditions" => $conditions, "fields" => $fields, "recursive" => $recursive));
            $this->returnArray["custom"][$model] = $array;
        }
    }

    return $this->returnArray;
}

上面的函数会得到一个数组,它可以分解自定义搜索或默认值(上面没有包含,但一切正常,它返回的数组完全符合我的预期。

 // The code within my action to get the content from above:
// Load the Filters component to search data:
        $search = $this->Components->load("Filter");

        // Tell search what you want:
        $searchBoxes = array(
            "defaults" => array("statuses", "survey_type"),
            "custom" => array(
              "User" => array(
                  "fields" => array("User.id","User.first_name", "User.last_name"),
                  "conditions" => array("User.user_group_id" => "4f847c63-1840-446e-88be-3e4d29566cf0"),
                  "recursive" => -1
              )  
            )
        );

       $filterResults = $search->filterQueries($searchBoxes);
       $this->set("filters",$filterResults);

所以现在我在我的视图文件中得到了这个多关联数组(一切都很好),但我现在想基于上面创建的数组构建一个用户下拉列表示例,但结果与什么不同我预计:

echo $this->Form->input('user_id',
                        array(
                            "type" => "select",
                            "options" => $filters["custom"]["User"]
                        )
                     );

HTML 输出被破坏并显示如下:

<option value="last_name">Doe</option>
<option value="first_name">Jihn</option>
<optgroup label="User"> </optgroup>
<optgroup label="1"> </optgroup>
<option value="last_name">Marilyn</option>
<option value="first_name">Monroe</option>

我承认我没有很多蛋糕经验,但不明白如何获得结果:

 <option value='USERID'>NAME</option> // Yes I know the names and surnames must be concatinated still

任何建议帮助或指导如何做到这一点,并以正确的方式做,将不胜感激:)

VARDUMP ON $filters['custom']['users']

  array
   0 => 
     array
       'User' => 
         array
            'id' => string '4f84840e-cda8-4704-8fdf-210729566cf0' (length=36)
            'first_name' => string 'Name' (length=4)
            'last_name' => string 'Surname' (length=11)
    1 => 
      array
        'User' => 
          array
            'id' => string '4f8488cb-53e0-4f72-af73-3de229566cf0' (length=36)
            'first_name' => string 'Name' (length=6)
            'last_name' => string 'Surname' (length=6)

【问题讨论】:

  • var_dump($filters["custom"]["User"]) 是什么样的?
  • 数组 0 => 数组 'User' => 数组 'id' => 字符串 '4f84840e-cda8-4704-8fdf-210729566cf0' (length=36) 'first_name' => 字符串 'NAME' (长度=4)'姓氏'=>字符串'SURNAME'(长度=11)1 =>数组'用户'=>数组'id'=>字符串'4f8488cb-53e0-4f72-af73-3de229566cf0'(长度=36 ) 'first_name' => string 'NAME' (length=6) 'last_name' => string 'SURNAME' (length=6) ..... 它也返回所有其他用户
  • 哦,你能编辑你的问题,然后把它贴在那里。没有格式的 cmets 很难阅读。

标签: php cakephp controller components formhelper


【解决方案1】:

在 cakePHP 3 上,我还不能使用“virtualFields”,但可以如下使用:

//In PostsController
$users = $this->Posts->Users->find('list', 
['keyField'   => 'id', 
 'valueField' => 'full_name', //Don't forget to call concatened field here
 'conditions' => $conditions, 
 'order'      => $orderBy 
]);

//here the magic happens
$concat = $users->func()->concat(
['Users.first_name' => 'identifier', 
 ' ', 
 'Users.last_name' => 'identifier'
]);

//selecting fields
$users->select(['id', 'full_name' => $concat]);

//sending to view
$this->set('users', $users->toArray());

我希望这对 CakePHP 3 开发者有所帮助

【讨论】:

    【解决方案2】:

    $this->form->input('inputname', array('label' => false, 'options' => array('Select optionstype','a','b'), 'class'= >array('form-a', 'b'), 'id' => 'bacid', 'style' => 'width:280px;','value'=>$abc['model']['array_attribute ']));

    【讨论】:

      【解决方案3】:

      您可以通过执行以下操作来增强您的输出:

      1) 组合一个表的两个字段,可以在模型中使用"virtualfields",如下:例如如果你有用户模型,可以定义如下:

       public $virtualFields = array(
        'full_name' => 'CONCAT(first_name, " ",last_name)'
       );
      

      所以现在每当你调用 User 模型的 find 方法时都会得到“full_name”字段。

      2) 要从表中获取选择框的数据,您可以使用find('list') 方法。例如对于 User 模型,如果你需要表的id,full_name (last and first name combined using the virtual fields),可以这样做:

      $this->User->find('list',array('fields'=>array('id','full_name'),'conditions'=>$conditions))
      

      我希望这会有所帮助..

      【讨论】:

      • 关键是find 方法的list 参数。这有助于表单助手确定值应该是什么以及应该显示什么。
      • 非常感谢。
      【解决方案4】:

      我认为你需要这样的东西:

      $result = Set::combine($filters["custom"]["User"], 
      
                             '{n}.User.id', // this is the value of select box
      
                               array(
                                     '{0} {1}', 
                                     '{n}.User.first_name', 
                                     '{n}.User.last_name'
                                    ) // this is the text of select box
                            );
      
      pr($result);
      

      【讨论】:

        【解决方案5】:

        我猜你想要做的实际上是创建另一个带有格式化选项的数组。

        foreach ($filters["custom"]["User"] as $arr)
        {
            $options[$arr['id']] = $arr['first_name'] . ' ' . $arr['last_name'];
        }
        

        然后

        echo $this->Form->select('user_id', $options);
        

        【讨论】:

        • 嘿,杰克,我知道你打算这样做,我很高兴这样做,但你会建议我这样做还是有更有效的方法我想在上面实现什么?
        • 我不相信有任何其他方式,因为您需要以特定方式格式化选项。 CakePHP form->select 使用数组键作为name="value",使用数组值作为表单文本。 book.cakephp.org/1.3/view/1430/select 但 find 查询中的 $results 数组返回一个多维数组。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 2013-04-12
        • 2021-10-09
        • 2020-09-07
        相关资源
        最近更新 更多