欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

覆写视图字段输出(不使用views模板主题文件) hook_view override views fields output drupal 6 有大用 有大大用

使用  hook_views_pre_render()  这个钩子 有大用



function shipingzhongcustom_views_pre_render(&$view)
{
  $arr = get_object_vars($view);
  var_dump(array_keys($arr));
  $result = kprint_r($view,TRUE);
  print $result;
  if ($view->name == 'allcontentview' && $view->current_display=='page_3') {
     $results = $view->result;
     global $user;
     //有定金量的时候,吴中的接待只能看吴中的定金量
     if(in_array('吴中接待只看吴中不看华东定金量',$user->roles)) {

        foreach($results as $key=>$result){
           if($result->node_data_field_is_dingjing_field_is_dingjing_value=='是'){
              $account = null;
              $account = user_load(array('name' => check_plain($result->node_data_field_dingjing_writer_field_dingjing_writer_value)));
              //假如定金量填写人 是华东的话 就移除它
              if(in_array('华东接待只看华东不看吴中定金量',$account->roles)){
                 unset($results[$key]);
              }
           }
        }
        $view->result = $results;
     }
     //有定金量的时候,华东的接待只能看华东的定金量
     if(in_array('华东接待只看华东不看吴中定金量',$user->roles)) {
        foreach($results as $key=>$result){
           if($result->node_data_field_is_dingjing_field_is_dingjing_value=='是'){
              $account = null;
              $account = user_load(array('name' => check_plain($result->node_data_field_dingjing_writer_field_dingjing_writer_value)));
              //假如定金量填写人 是吴中的话 就移除它
              if(in_array('吴中接待只看吴中不看华东定金量',$account->roles)){
                 unset($results[$key]);
              }
           }
        }
        $view->result = $results;
     }
  }
  else if ($view->name == 'allcontentview' && $view->current_display=='page_33') {
     $results = $view->result;
     foreach($results as $key=>$result){
        $node=(object)null;
        $node = node_load($result->nid);
        $next_times = $node->field_genzong_next_time;
        //这里移除掉 最后一个 下次跟踪时间不为空的 node (如果为下次跟踪时间为空的话 就表示已经是转向上门的了)
        if(!empty($next_times[count($next_times)-1]['value'])){
           unset($results[$key]);
        }
     }
     $view->result = $results;
  }




}


如何以编程方式更改视图字段输出

 - Thu,01 / 19 / 2012 - 05:03 / 11评论

修改视图输出不再是一项繁琐的工作。特别是通过利用Views 3.x中可用的设置,例如从显示中排除,样式设置,重写结果及其子设置。改变可以是任何简单的添加<跨度>用于CSS样式的包装器以复杂的令牌替换(感谢令牌模块使得视图模块更加精彩)。

 

[[{ “类型”: “媒体”, “view_mode”: “media_original”, “FID”: “82”, “属性”:{ “ALT”: “”, “类”: “媒体图像”,” typeof运算 “:” 的foaf:图像“}}]]

 

嗯,这在大多数情况下都很有用,但是有些情况下你需要几行PHP代码才能使输出更接近项目的要求。我在最近的项目中遇到了这样的情况。我的要求是显示与到期日期(unixtimestamp)字段的时差。类似于什么的东西format_interval() API会以不同的方式返回,但它会返回。

 

最快和最诱人的解决方案是启用Drupal core的PHP过滤器模块,并从Views管理界面添加代码片段。初看起来这可能看起来简单而且没有麻烦,因为你不需要编写任何模块,但严重的是这不是Drupal的做法。要深入了解为什么要避免使用PHP过滤器,请参阅  http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-意见-ARGS

 

我用谷歌搜索视图API文档并遇到了 hook_views_pre_render()经过几次失败尝试后,我想出了它的工作方式。我有一个具有到期字段的产品节点。在视图输出中,我需要在到期前剩余的天数,小时数,分钟数和秒数显示剩余时间。 

 

实现的快速模块 hook_views_pre_render()做了伎俩。它只需要几行代码,如下所示,

  1. / **

  2.  *实现hook_views_pre_render()。

  3.  * /

  4. function kf_products_views_pre_render $ view  {

  5.   $ products_view = array 'products''expired_products'  ;  

  6.   $ results = $ view - result ;

  7.   foreach $ results as $ key = $ result  {

  8.     if $ view - name == 'products'  {

  9.       $ field_expiry_date = $ result - > _field_data 'nid' 'entity' ] - field_deal_expire ;

  10.       $ expiry_date = _kf_products_get_remaining_time $ field_expiry_date 'und' 'value'  ;

  11.       $ results $ key ] - field_field_deal_expire 'rendered' '#markup' ] = $ expiry_date ;

  12.     }    

  13.   }

  14. }

 

理想情况下,上面的代码循环遍历视图的结果项并覆盖 field_deal_expire 值与自定义函数返回的值 _kf_products_get_remaining_time()。

 

函数  _kf_products_get_remaining_time() 返回一个字符串值,它如下所示,

  1. function _kf_products_get_remaining_time $ expiry_date  {

  2.   $ remaining = '' ;

  3.   $ diff = $ expiry_date - REQUEST_TIME;

  4.   $ days = floor $ diff / 86400  ;

  5.   $ hours = floor $ diff - $ days * 86400  / 3600  ;

  6.   $ minutes = floor $ diff - $ days * 86400  - $ hours * 3600  / 60  ;

  7.   $ seconds = floor $ diff - $ days * 86400  - $ hours * 3600  - $ minutes * 60  ;

  8.   if $ diff > 86400  {

  9.     $ remaining。= $天'd' ;

  10.   }

  11.   if $ hours > 0  {

  12.     $ remaining。= $小时'h' ;

  13.   }

  14.   if $ minutes > 0  {

  15.     $ remaining。= $分钟'm' ;

  16.   }

  17.   if $ diff < 86400  {

  18.     $ remaining。= $秒's' ;

  19.   }

  20.   返还 $剩余 ;

  21. }

除了页面和块显示外,此技巧还适用于其他模块,如视图数据导出等其他模块的其他显示,如CSV和XLS文件导出

分享FacebookTwitterGoogle+LinkedInPinterest

评论

Knackforge

比尔(未经核实)

星期四,01/26/2012 - 11:35

永久链接

感谢您对这篇文章

谢谢你这篇帖子sivaji!它实际上帮助我克服了一个障碍,试图了解如何用计算值替换视图中字段的值。除了创建一个应该可以从视图中表示的所有节点获得的变量($ interest_rate)之外,我已经能够使用我的用例。内容类型中指定的变量是field_mortgage_rate。速率值显示在视图本身中,因此我确信数据存在。但所有这些似乎都在回归$ interest_rate值= 0。

您可以提供任何建议或信息,以使其正常工作?

<代码>

 

function home_finance_views_pre_render(&$ view){// $ products_view = array('home_lending','expired_products');    $ results =&$ view-> result;  foreach($ results as $ key => $ result){    if($ view-> name =='home_lending'){      $ interest_rate = $ result - > _ field_data ['nid'] ['entity'] - > field_field_mortgage_rate;      $ results [$ key] - > field_field_mortgage_monthly_payment [0] ['rendered'] ['#markup'] = 1000 *($ interest_rate + 1);</代码>

$ INTEREST_RATE可能是一个

$ interest_rate可以是一个数组。这应该工作。

  1. $ interest_rate = $ result - > _field_data 'nid' 'entity' ] - >field_field_mortgage_rate ;

  2. $ interest_value = $ interest_rate 'und' 'value' ] ;

  3. $ results $ key ] - field_field_mortgage_monthly_payment 'rendered' ['#markup' ] = 1000 $ interest_value + 1  ;

http://drupalbin.com/20725

谢谢SIVAJI!它没有

谢谢sivaji!它起初不起作用,但后来我尝试了field_mortgage_rate而不是field_field_mortgage_rate,它就像一个魅力!感谢您的帮助!我的下一个挑战是从Views暴露过滤器中获取输入值。你有没有做过这些事情?

Knackforge

JIBUS(未经验证)

星期二,10/02/2012 - 10:41

永久链接

非常感谢这篇文章

非常感谢这篇帖子sivaji!我搜索了几个小时如何使用hook_views_pre_render获取字段值。你的帖子真有帮助!谢谢!

Knackforge

布拉德(未经核实)

星期二,04/30/2013 - 22:41

永久链接

感谢您的提醒

感谢关于pre_render如何工作的提醒。如果在循环遍历值之前检查它是哪个视图,则此函数将更有效。
<code> 
function kf_products_views_pre_render(&$ view){ 
if($ view-> name =='products'){ 
foreach($ view-> result as $ key =>&$ result){ 
$ field_expiry_date = $ result - > _ field_data [ 'NID'] [ '实体'] - > field_deal_expire; 
$ expiry_date = _kf_products_get_remaining_time($ field_expiry_date ['und'] [0] ['value']); 
$ result-> field_field_deal_expire [0] ['rendered'] ['#markup'] = $ expiry_date; 



</代码>

Knackforge

RAFIQ(未经核实)

星期四,09/26/2013 - 05:42

永久链接

我正在使用搜索API和

我正在使用搜索api和Solr,这个功能对我不起作用。当我回显结果变量时,它给了我以下结果

stdClass对象

[entity] => 442415 
[_entity_properties] =>数组

[search_api_relevance] => 1 
[search_api_excerpt] => 
[search_api_item_id] => 442415 

Knackforge

BRAD LOWRY(未经核实)

星期二,12/15/2015 - 12:27

永久链接

谢谢!…

谢谢!

不确定为什么你创建了
$ products_view = array('products','expired_products');

也许你会使用
if(in_array($ view-> name,$ products_view))
作为你的标准而不是
if($ view-> name =='products')
......但我学会了不要假设任何东西说到Drupal。

那么$ products_view是否有意义,或者只是一个我可以忽略的代码'遗留'?

再次感谢有用的文章。


来自  https://knackforge.com/blog/sivaji/how-alter-views-field-output-programmatically




drupalDRUPAL 7 VIEWS HOOK_VIEWS_PRE_RENDER() DRUPAL PLANET

HOW TO ALTER VIEWS FIELD OUTPUT PROGRAMMATICALLY

 - Thu, 01/19/2012 - 05:03 11 Comments

Amending the view output is no longer a tedious task. Especially by taking the advantage of settings available in Views 3.x like exclude from display, style settings, rewrite results and their sub-settings. The change can be anything simple from adding a <span> wrapper for CSS styling to complex token replacement (thanks to token module for making the Views module more awesome).

 

[[{"type":"media","view_mode":"media_original","fid":"82","attributes":{"alt":"","class":"media-image","typeof":"foaf:Image"}}]]

 

Well, this works great most of the times, however there are cases where you need a few lines of PHP code to make the output closer to project's requirements. I hit upon such a case in my recent project. My requirement was to show the time difference from the expiry date (unixtimestamp) field. Something similar to what format_interval() API would return but it in a different way.

 

The quickest and most temptating solution would be to enable Drupal core's PHP filter module and add a code snippet from Views admin interface. At first look this might look simple and hassle free as you don't need to write any module but seriously this is not a Drupal way of doing. To learn in depth about why you should avoid PHP filter see http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args

 

I Googled for views API documentation and came across hook_views_pre_render(). After a few attempts of failure I figured the way it works. I have a product node that has expiry field. In the view output I need to show the remaining time in terms of number of days, hours, minutes and seconds left before expiry. 

 

A quick module that implements hook_views_pre_render() did the trick. All it requires is a few lines of code as below,

  1. /**

  2.  * Implements hook_views_pre_render().

  3.  */

  4. function kf_products_views_pre_render(&$view) {

  5.   $products_view = array('products''expired_products');  

  6.   $results = &$view->result;

  7.   foreach ($results as $key => $result) {

  8.     if ($view->name == 'products') {

  9.       $field_expiry_date = $result->_field_data['nid']['entity']->field_deal_expire;

  10.       $expiry_date = _kf_products_get_remaining_time($field_expiry_date['und'][0]['value']);

  11.       $results[$key]->field_field_deal_expire[0]['rendered']['#markup'] = $expiry_date;

  12.     }    

  13.   }

  14. }

 

Ideally the code above loops throught the result items of view and overriddes the field_deal_expire value with value returned by a custom function _kf_products_get_remaining_time().

 

The function _kf_products_get_remaining_time() returns a string value and it resembels as below,

  1. function _kf_products_get_remaining_time($expiry_date) {

  2.   $remaining = '';

  3.   $diff = $expiry_date - REQUEST_TIME;

  4.   $days = floor($diff / 86400);

  5.   $hours = floor(($diff - ($days * 86400)) / 3600);

  6.   $minutes = floor(($diff - ($days * 86400) - ($hours * 3600)) / 60);

  7.   $seconds = floor($diff - ($days * 86400) - ($hours * 3600) - ($minutes * 60));

  8.   if ($diff > 86400) {

  9.     $remaining .= $days . ' d ';

  10.   }

  11.   if ($hours > 0) {

  12.     $remaining .= $hours . ' h ';

  13.   }

  14.   if ($minutes > 0) {

  15.     $remaining .= $minutes . ' m ';

  16.   }

  17.   if ($diff < 86400) {

  18.     $remaining .= $seconds . ' s ';

  19.   }

  20.   return $remaining;

  21. }

Besides page and block display, this trick works for additional displays like CSV and XLS file export featured by other modules like Views data export.

分享FacebookTwitterGoogle+LinkedInPinterest

COMMENTS

Knackforge

BILL (NOT VERIFIED)

Thu, 01/26/2012 - 11:35

Permalink

THANK YOU FOR THIS POST

Thank you for this post sivaji!  It actually helped me get over a hurdle in trying to understand how to replace the value of a field in a view with a calculated value.  I've been able to get everything to work with my use case, except creating a variable ($interest_rate) that should be available from all nodes represented in the view.  The variable assigned in the content type is field_mortgage_rate.  The rate values are displaying in the View itself, so I'm confident the data is there.  But all this seems to be doing is returning an $interest_rate value = 0.

Any suggestions or information you can provide to get this to work correctly?

<code>

 

function home_finance_views_pre_render(&$view) {//  $products_view = array('home_lending', 'expired_products');    $results = &$view->result;  foreach ($results as $key => $result) {    if ($view->name == 'home_lending') {      $interest_rate = $result->_field_data['nid']['entity']->field_field_mortgage_rate;      $results[$key]->field_field_mortgage_monthly_payment[0]['rendered']['#markup'] = 1000 * ($interest_rate + 1);</code>

$INTEREST_RATE COULD BE AN

$interest_rate could be an array. This one should work.

  1. $interest_rate = $result->_field_data['nid']['entity']->field_field_mortgage_rate;

  2. $interest_value = $interest_rate['und'][0]['value'];

  3. $results[$key]->field_field_mortgage_monthly_payment[0]['rendered']['#markup'] = 1000 * ($interest_value + 1);

http://drupalbin.com/20725

THANKS SIVAJI!  IT DIDN'T

Thanks sivaji!  It didn't work at first, but then I tried field_mortgage_rate instead of field_field_mortgage_rate and it worked like a charm!  Thanks for your help!My next challenge is to grab an input value from a Views exposed filter.  Have you done anything along those lines?

Knackforge

JIBUS (NOT VERIFIED)

Tue, 10/02/2012 - 10:41

Permalink

MANY THANKS FOR THIS POST

Many thanks for this post sivaji!I searched for hours how to get the field value with hook_views_pre_render. Your post is really helpful !Thanks !

Knackforge

BRAD (NOT VERIFIED)

Tue, 04/30/2013 - 22:41

Permalink

THANKS FOR THE REMINDER ABOUT

Thanks for the reminder about how pre_render works. This function will be more efficient if you check for which view it is before looping through the values.
<code>
function kf_products_views_pre_render(&$view) {
if ($view->name == 'products') {
foreach ($view->result as $key => &$result) {
$field_expiry_date = $result->_field_data['nid']['entity']->field_deal_expire;
$expiry_date = _kf_products_get_remaining_time($field_expiry_date['und'][0]['value']);
$result->field_field_deal_expire[0]['rendered']['#markup'] = $expiry_date;
}
}
}
</code>

Knackforge

RAFIQ (NOT VERIFIED)

Thu, 09/26/2013 - 05:42

Permalink

I AM USING SEARCH API AND

I am using search api and Solr, This function is not working for me. When I echo the result variable , it gave me the following results

stdClass Object
(
[entity] => 442415
[_entity_properties] => Array
(
[search_api_relevance] => 1
[search_api_excerpt] =>
[search_api_item_id] => 442415
)

)

Knackforge

BRAD LOWRY (NOT VERIFIED)

Tue, 12/15/2015 - 12:27

Permalink

THANKS!…

Thanks!

Not sure why you created
$products_view = array('products', 'expired_products');

Perhaps you were going to use
if (in_array($view->name, $products_view))
as your criteria instead of
if ($view->name == 'products')
... but I've learned NOT to assume anything when it comes to Drupal.

So is $products_view meaningful, or just a code 'left-over' that I can ignore?

Thanks again for the helpful article.


来自  https://knackforge.com/blog/sivaji/how-alter-views-field-output-programmatically

普通分类: