Magento – How to set data from controller to .phtml file in magento

custommagento-2.1module

I have created a custom module and there are some drop downs in it. I have done all the things in .phtml file as pure php.

How can I change that to correct way code in my .phtml file:

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();

$tableColor = $resource->getTableName('color_price');

$sql = "SELECT * FROM " . $tableColor;
$color = $connection->fetchAll($sql);
?>

drop down like below its in .phtml file too:

<p><br>Frame Color</p>
<select id="color">
<?php
foreach($color as $c){ ?>
    <option value="<?php print_r($c['price_component']);?>"><?php print_r($c['color']);?></option>
<?php
}
?>
</select>

<b><p id="framecolor"></p></b>

below code is my layout.xml file

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" 
layout="1column">
    <body>
        <referenceContainer name="content">
            <block class="Test2\Helloworld\Block\Helloworld" 
            name="helloworld" template="helloworld.phtml" />
        </referenceContainer>
    </body>
</page>

what is the correct way of doing this. now all the things in .phtml file

Best Answer

In controller file,

$om = \Magento\Framework\App\ObjectManager::getInstance();
$persistor = $om->get('Magento\Framework\App\Request\DataPersistorInterface');
$data = array('test1','test2');
<!-- set data in persistor object -->
$persistor->set('coloroption', $data);

In template file,

<!-- get data in persistor object -->  

  $om = \Magento\Framework\App\ObjectManager::getInstance();
  $persistor = $om->get('Magento\Framework\App\Request\DataPersistorInterface');
  $colorOption =     $persistor->get('coloroption');
  print_r($colorOption);