PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 8, 2022

[FIXED] Where to define a function for use within a Yii's view?

 March 08, 2022     php, yii, yii2     No comments   

Issue

I'm developing a web application with Yii2.

I am passing an array from my controller to my view for display as a table. Each element in the array is a sub-array that represents a table row. However, the sub-array, where each element represents a table cell, can be made up of both strings and "sub-sub-arrays". In the case of a string, then the string would just be output in a table cell. In the case of a sub-sub-array, I want to "unwind" the array for display. Again, these sub-sub-arrays can be made of strings or "sub-sub-sub-arrays". And so on.

What is the best way of approaching this? I'm thinking that I should write a recursive function to unwind the array in the view. If it's a string, then output, else if it's an array, unwind the array.

Writing the function itself seems straightforward to me, but where do I actually define it? Does it go in my controller class? Somewhere else? I'm thinking that I will call it from my view. Within the Yii structure, how do I call it such that it is within scope (if I'm using the right term) and being called correctly?

So in my controller, I would have something like:

return $this->render('//messages', [
    'table' => $array_to_unwind
]);

And in my messages.php view file, I would have something like the following, where the unwind() function outputs a string if it's a string, or unwinds an array if it's an array:

<table>
  <?php
  foreach ($table as $row) {
    echo '<tr>';
    foreach ($row as $cell) {
      echo '<td>';
      unwind($cell);
      echo '</td>';
    }
    echo '</tr>';
  }
  ?>
</table>

Solution

You should create own Helper (for example in path-to-project/components/ - in Basic Template) class to do such things, and inside create static functions.

<?php

namespace app\components;

class MyHelper
{
     public static function unwind($param) {
            // here body of your function
     }
}

Then in view call it:

foreach ($row as $cell) {
  echo '<td>';
  echo \app\components\MyHelper::unwind($cell);  //or without echo if your function is doing it, but it will be better if function will return value instead of echoing it
  echo '</td>';
}


Answered By - Yupik
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing