Use Widget Without View

Hi,

I am a newbie at Yii. I am trying to create a widget which gets the RSS feed.

It is working fine, but I want to know am I doing it the right way?

/protected/components/TestWidget.php




class TestWidget extends CWidget 

{

  public function run() 

  {

    $feed_url = '---url---';

    $feed = simplexml_load_file($feed_url);

    

    foreach($feed -> entry as $item) 

    {

       $title = $item -> title;

       $url = $item -> id;

        

       echo '<strong>Title is: </strong>' . $title . '<br />';

       echo '<strong>Url is:   </strong>' . $url . '<br />';

      

    }

   }

}



And in main.php I am simply doing.




<div ...... >

  <h4>My Widget</h4>

  <?php

    $this->widget('application.components.TestWidget');

  ?>

</div>



But on the wiki pages and on forum I have seen rendering it to the view /protected/components/views/testWidget.php file.

Thanks.

Hi razor101

The right way (according to MVC) is using view file.

Although widgets are kind of controllers, you could use directly echo-print etc to output the results

render() method of a widget works like renderPartial() of a normal controller, so we can make an exception and skip the main architecture of MVC,

The above also applied in the kernel of Yii framework,

for example see the run method of CBaseListView

Hmm…

Thanks for clearing that up.

One more thing, if I add that RSS feed’s content in an array and then pass it to the view.

Then how can I get those contents in the view.

For example:




public function run() 

  {

    $feed_url = '---url---';

    $feed = simplexml_load_file($feed_url);

    

    $output = array();


    foreach($feed -> entry as $item) 

    {

       $title = $item -> title;

       $url = $item -> id;

        

       $output[] = array(

          'title' => $title,

          'url' => $url

        );


       // echo '<strong>Title is: </strong>' . $title . '<br />';

       // echo '<strong>Url is:   </strong>' . $url . '<br />';

      

    }


    $this->render('testWidget');

   }



Found a solution. At the end of my widget I did




$this->render('testWidget', array('output' => $this->output));



And in the /views/testWidget.php, I loop through that array and echo it out.

Is there a way to get these values in main.php ??

Right now I am doing:




<?php

   $this->widget('application.components.TestWidget');

?>