Saturday, February 26, 2022

[FIXED] Set default radio button in Cakephp

Issue

The below code creates some radio buttons and html to go with them, it works well however I now want to set the first radio button as the default selected one and im not sure what needs to be added.

<?php
     for ($i =0; $i < count($packages); $i++){
       echo "<div class='package-outter'>";
       echo "Name: ".$packages[$i]['Package']['name']."<br>";
       echo "Number of Campaigns (per month): ".$packages[$i]['Package']['quantity']."<br>";
       echo "Price: ".$packages[$i]['Package']['price']."<br>";

         if ($i == 0){
           echo $this->Form->input('package', array(
                                   'type' => 'radio',
                                   'options' => array($packages[$i]['Package']['id'] => $packages[$i]['Package']['name'],),
                                   'class' => 'testClass',
                                    ));
         }else{
           echo $this->Form->input('package', array(
                                   'type' => 'radio',
                                   'options' => array($packages[$i]['Package']['id'] => $packages[$i]['Package']['name'],),
                                   'class' => 'testClass',
                                   'hiddenField' => false, // added for non-first elements
                                    ));
          }


          echo "</div>";
          }

?>

Solution

I'm not really familiar with CakePHP but a quick Google Search gave me this

$options = array(
    'standard' => 'Standard',
    'pro' => 'Pro'
);

$attributes = array(
    'legend' => false,
    'value' => $foo
);

echo $this->Form->radio('type', $options, $attributes);

So you should add the attribute 'value' and set it as your default selected radio



Answered By - kbonnelly

No comments:

Post a Comment

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