CakePHP manual 中文翻译7

第九章 Helpers

  1. Helpers设计的目的是提供一些方法,views通过使用这些方法能够更好的规范和显示数据。
  2. 1.1 HTML
  3. 1.1.1 介绍
  4.        HTML helper是Cake里快速开发,减少单调工作的一种途径。HTML helper有两个目的:为在HTML代码插入经常使用的代码提供帮助,为快速创建web form标单提供帮助。下面的这一节将会着重介绍这些方法,更多内容请参考http://api.cakephp.org
  5.  
  6.        在HTML helper中许多方法都使用的HTML tag都是定义在 tags.ini.php。Cake的核心库中包含了一个tags.ini.php,但是如果你想做些改动,请在/app/conifg下面创建一份 /cake/config/tags.ini.php. HTML helper将会使用这个文件中的tag定义来生成你需要的tags。使用HTML helper来创建自己的view代码将会非常有用,因为tags.ini.php文件中的改动将会在整个站点上都有显示。
  7.  
  8.        另外,如果核心库文件(/app/config/core.php)中AUTO_OUTPUT被设置成true。hepler将会自动输出这些tag,而不是返回这些值。这样做是为了满足那些不喜欢在view中使用短标签(<?= ?>)或者许多echo()调用。包含$return参数的方法允许你该写自己的核心库配置。如果不考虑AUTO_OUTPUT的设置,你可以将$ return设置为true这样html helper将会返回HTML代码。
  9. <span id="more-23"></span>
  10.        HTML helper方法同样包含了$htmlAttibutes参数,这个参数是的你可以将其他的属性粘贴在标签上。比如,你想给一个标签添加一个class属性,你可以把下面这个作为$htmlAttribute的属性。
  11.  
  12. <coolcode lang="php">
  13. array('class'=>'someClass')</coolcode>
  14.  
  15. 1.1.2 插入正确组织的元素(well-formatted elements)
  16.  
  17.        如果你想要在你的HTMl代码中插入正确组织的、经常使用的元素,HTML helper起到很大的作用。这里有四个方法可以插入media,协助tables,甚至用可视化的列表树创建基于PHP数组的未排序的列表。
  18. <coolcode lang="php">
  19. charset($charset,$return)</coolcode>
  20.  
  21.     ○这个方法可以创建一个charset的meta标签(META-tag)
  22. <coolcode lang="php">
  23. css($path ,$rel =’stylesheet’ , $htmlAttriutes= null , $return =false)</coolcode>
  24.  
  25.        ○创建一个css模版页(stylesheet),$rel参数允许用户提供一个 rel=value作为标签(原文:The $rel parameter allows you to provide a rel= value for the tag.)
  26. <coolcode lang="php">
  27. image($path, $htmlAttributes =null, $return=false)</coolcode>
  28.  
  29.     ○显示一个图片的标签。返回的代码可以用做link()方法的输入,这样就可以自动的产生一个linked images(liuchen注:我的理解就是创建了一个可以点击的图片,链接到别处)
  30.  
  31. <coolcode lang="php">●link($title,$url=null,$htmlAttributes=null,$confirmMessage=false,
  32.  
  33. $escapeTitle=True, $return=false)</coolcode>
  34.  
  35. ○使用这个方法可以在view里面创建一个链接,$confirmMessage可以在你需要一条javascript的确认信息的时候使用,这样,点击这个链接则跳出这个确认信息,一条删除对象的链接经常需要一条“你确定么?”的确认信息,这样在删除之前要求用户的确认。如果你想让HTML helper不用管理你的数据(保存在$title变量中),可以将$escapeTitle设置成为true
  36. <coolcode lang="php">
  37. tableHeaders($names,$tr_options=null,$th_options=null)</coolcode>
  38.  
  39.     ○用来创建格式化的表格头
  40. <coolcode lang="php">
  41. tableCells($data,$odd_tr_options=null,$even_tr_options=null)</coolcode>
  42.  
  43.     ○用来创建格式化的表格单元
  44.  
  45. <coolcode lang="php">●guiListTree($data,$htmlAttributes=null,$bodyKey=’body’,$childrenKey=’children’,$return=false)</coolcode>
  46.  
  47.        ○根据一个数组创建一个未排序的整齐的列表
  48.  
  49. 1.1.3 表格和正确性 (Forms and Validation)
  50.  
  51. Cake在view中快速编写html代码时候确实非常有效,它自动生成form标签,如果有错误还能自动填入值和错误消息。下面我们举个例子来实现。假设,你的程序有了一个Note model,你想创建一个controller逻辑和一个view来add和edit Note的对象。在你的NotesController中,你可以有一个edit action,这个action可以像下面这样:
  52.  
  53.  
  54. <coolcode lang="php">function edit($id)
  55.    {
  56.       //First, let's check to see if any form data has been submitted to the action.    
  57.       if (isset($this->params['form']['data']['note']))
  58.       {
  59.          //Here's where we try to validate the form data (see Chap. 10) and save it
  60.          if ($this->note->save($this->params['data']))
  61.          {
  62.             //If we've successfully saved, take the user to the appropriate place
  63.             $this->flash('Your information has been saved.', '/notes/edit/' . $id);
  64.             exit();
  65.          }
  66.          else
  67.          {
  68.             //If the data didn't validate, hand the form data back to the view
  69.             $this->set('form', $this->params['data']);          
  70.             //Generate the error messages for the appropriate fields
  71.             $this->validateErrors($this->note);
  72.             //And render the edit view code
  73.             $this->render();
  74.          }    
  75.       }    
  76.       // If we haven't received any form data, get the note we want to edit, and hand
  77.       // its information to the view
  78.       $this->set('note', $this->note->find("id = $id"));
  79.       $this->render();
  80.    }</coolcode>
  81.  
  82.  
  83. 一旦我们的controller建立,我们来看一下view的代码(位于app/views/notes/edit.thtml)。我们的 Note model是非常简单的。而且仅仅包含了一个id,一个提交着的id和body。这个view 的代码意思是显示Note的数据并且让用户输入新的值并将提交的新值输到model中。
  84.  
  85.        任何views默认情况下都可以得到HTML helper,使用$html就可以了。
  86.  
  87.        特别的,可以看下面的table
  88.  
  89.  
  90.  
  91. 例9.2 Edit View code(edit.thtml)
  92.  
  93.  
  94.  
  95. <!-- This tag creates our form tag -->
  96. <?php echo $html->formTag('/notes/edit/' . $note['note']['id'])?>
  97. <table cellpadding="10" cellspacing="0">
  98. <tr>
  99.    <td align="right">Body: </td>
  100.    <td>
  101.       <!-- Here's where we use the HTML helper to render the text area tag and its possible error message the $note variable was created by the controller, and contains the data for the note we're editing. -->
  102.       <?php echo
  103.       $html->textarea('note/body', array('cols'=>'60', 'rows'=>'10',
  104.            'value' => $note['note']['body']))
  105.       ?>
  106.       <?php echo $html->tagErrorMsg('note/body', 'Please enter in a body for this note.') ?>
  107.    </td>
  108. </tr>
  109. <tr>
  110.    <td></td>
  111.    <td>
  112.       <!-- We can also use the HTML helper to include hidden tags inside our table -->
  113.       <?php echo $html->hiddenTag('note/id', $note['note']['id'])?>
  114.       <?php echo $html->hiddenTag('note/submitter_id', $_SESSION['user_id'])?>
  115.    </td>
  116. </tr>
  117. </table>
  118. <!-- And finally, the submit button-->
  119. <?php echo $html->submit()?>
  120. </form>

大多数的表单标签生成方法(包括tagErrorMsg)都需要你提供一个$fieldName。这个$fieldName可以让 Cakezhidao你想要传递什么数据,进而检查这个数据并保存。$fieldName参数传递的字符串要满足这种形式 “modelname/fieldname”,如果你想要添加一个title field进入Note,你需要向view中添加下面这些代码

  1. <?php echo $html->input('note/title', $note['note']['title']) ?>
  2. <?php echo $html->tagErrorMsg('note/title', 'Please supply a title for this note.')?>

错误信息将会有tagErrorMsg()方法显示在

这个标签中,使用简单的CSS模式

下面是一些HTML helper可以创建的form tags(大多数都是直接创建)。

  1. formTag($target=null, $type=’post’,$htmlAttributes=null)

○创建一个打开的表单标签,使用$target来确定表单的action。记住,如果你要提交一个文件,你需要向$hatmAttrbutes参数提供合适的字符编码信息(?enctype infomation)

  1. submit($caption=’Submit’, $htmlAttributes=null, $return= false)

○通过$caption参数可以修改按钮名

  1. password($fieldName, $htmlAttributes=null, $return=false)
  1. textarea($fieldName, $htmlAttributes=null, $return = false)
  1. checkbox($fieldName, $title=null, $htmlAttributes=null, $return=false)
  1. file($fieldName, $htmlAttributes = null, $return=false)
  1. hidden($fieldName, $htmlAttributes=null, $return=false)
  1. input($fieldName, $htmlAttributes=null, $return=false)
  1. radio($fieldName,$options,$inbetween=null,$htmlAttributes=null,$return=false)
  1. tagErrorMsg($field, $text)

HTML helper也包含了一系列方法来帮助创建数据库相关的tag。$tagName参数应该像$filedName参数一样处理。基金提供date option tag相关的field name.处理数据时,你可以在controller里面使用则各数据一直到该field的结尾。举例来说,如果我的Note有个deadline列(作为data),我的dayOptionTag $tagName参数被设置成‘note/deadline’,一旦表单被提交,day数据将作为$params变量显示出来

  1. $this->params['form']['data']['note']['deadline_day']

你可以使用这个来连接你的时间数据到跟你当前数据库配置相符合的形式。这段代码可以放在你尝试保存数据之前,保存到$data数组,这个数组可以用来保存信息到model中

例9.3 Concatenating time data before saving a mode(excerpt from NotesController)

  1. function edit($id)
  2.    {
  3.       //First, let's check to see if any form data has been submitted to the action.    
  4.       if (isset($this->params['form']['data']['note']))
  5.       {
  6.          //Concatenate time data for storage
  7.          $this->params['data']['note']['deadline'] =
  8.             $this->params['form']['data']['note']['deadline_year'] . "-" .
  9.             $this->params['form']['data']['note']['deadline_month'] . "-" .
  10.             $this->params['form']['data']['note']['deadline_day'];                         
  11.          //Here's where we try to validate the form data (see Chap. 10) and save it
  12.          if ($this->note->save($this->params['data']))
  13.          {
  1. dayOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)
  1. yearOptionTag ($tagName, $value=null, $minYear=null, $maxYear=null,$selected=null, $optionAttr=null)
  1. monthOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)
  1. hourOptionTag ($tagName, $value=null, $format24Hours=false,$selected=null, $optionAttr=null)
  1. minuteOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)
  1. meridianOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)
  1. dateTimeOptionTag ($tagName, $dateFormat= 'DMY', $timeFormat= '12',$selected=null, $optionAttr=null)

1.2 AJAX

Cake Ajax helper实现了更加popular的Prototype和script.aculo.us库赖提供Ajax操作和客户端效果。如果想使用这些helper,你必须有从http://script.aculo.us下载一份JavaScript libraries到/app/webroot/js目录下

这个helper里面的削夺方法多扩展了特殊的$options数组作为参数。这个数组用来确定你的Ajax操作中的各种东西

(liuchen:Ajax暂且略过,以后补充)

1.3 JavaScript

JavaScript helper用来帮助开发者输出标准的tag和数据

  1. codeBlock($script)

○用来返回$script,变量$script已经包含了

原文地址:https://www.cnblogs.com/kuyuecs/p/1330415.html