We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Radio buttons to select related record

Hi everyone,

I've got 2 tables: users, and groups. Users belong to groups through their group_id field.

I created a Form class with which I can Insert/Update my users. Now I would like to add a set of radio buttons to my form with all the groups I have in the DB so I can chose which group the user should belong to. I know it's simple to solve with a Select, but my form should look like this:

USER FORM

name:.........................................

username:.................................

email:.........................................

Select Group:

O | Admin | Can edit anything |

O | Guest | You are a lot less cooler than admins |

O | Writer | Can only edit |

I hope I described my problem clearly, I have been struggling with radios and checkboxes for a long time in Phalcon as the documentation says almost nothing about them.

Does anyone know how to implement this properly? (not in a dodgy way)

Thanks everyone in advance! Peter



338

I can confirm a problem with radios. We can set up a form with radios by following code:

<?php

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Radio;

class RadioTestForm extends Form
{
    public function initialize($entity = null, $options = null)
    {
        $admin = new Radio('admin', [
            'name' => 'group',
            'value' => 1
        ]);
        $this->add($admin);

        $guest = new Radio('guest', [
            'name' => 'group',
            'value' => 2
        ]);
        $this->add($guest);

        $writer = new Radio('writer', [
            'name' => 'group',
            'value' => 3
        ]);
        $this->add($writer);
    }
}

But I didn't find a way to set a radio value.

$app->get('/', function () use ($app) {     
    $form = new RadioTestForm((object) [
        'guest' => 1 // not working
    ]);
    $app->view->form = $form;

    echo $app->render('index/index');
});


595
edited Oct '16

I ended up creating a custom form element called RadioTable which renders a simple HTML table with radio buttons from a ResultSet using the desired fields and table headings. 'valueColumn' shows which column of the ResultSet should be used as the values of the radios. Plus you can give the table and the radios some additional html attributes. It works well.

RadioTable extends Phalcon\Forms\Element\Select

$group_id = new RadioTable('group_id',
    Group::find(array('order' => 'name')),
    array(
        'valueColumn' => 'id',
        'using' => array(
            'name' => 'Name', 
            'description' => 'Description'
        ),
        'tableAttributes' => array(
            'class' => 'table table-bordered table-hover'
        ),
        'radioAttributes' => array()
    );
);