Reputation: 705
How do I set checked within a form input radio field? This form field is added using a custom Form Element. The value of this field isn't consistent.
My custom Form Element returns 1 element. It is a radio input field. I need this checked each and every time the form is submitted. The reason I am using this instead of a "hidden" field is for the user to see this settings.
This is the custom Form Element
namespace Member\Form\Element;
use Doctrine\ORM\EntityManager;
use Zend\Form\Element\Radio;
/**
* Class OriginalLanguageIsoRadio
*
* @package Member\Form\Element
*/
class OriginalLanguageIsoRadio extends Radio
{
/**
* @var EntityManager $entityManager
*/
protected $entityManager;
/**
* @var string $translationKey
*/
protected $translationKey;
/**
* @var string $textDomain
*/
protected $textDomain;
/**
* @param EntityManager $entityManager
* @param string $translationKey
* @param string $textDomain
*/
public function __construct(
EntityManager $entityManager,
$translationKey,
$textDomain
)
{
$this->entityManager = $entityManager;
$this->translationKey = $translationKey;
$this->textDomain = $textDomain;
}
/**
* Get Value Options
*
* @return array
*
* @throws \Exception
*/
public function getValueOptions()
{
$array = [];
$query = $this->entityManager
->createQueryBuilder()
->from(
'AMDatabase\Entity\TheVerse\TranslationsMasters',
't'
)
->select('t.languageIso')
->setMaxResults(1);
$result = $query->getQuery()
->getArrayResult();
if (is_array($result) && count($result) > '0') {
foreach ($result AS $value) {
if ( $value['languageIso'] == '' ) {
$array['Global'] = $value['Global'];
} else {
$array[$value['languageIso']] = $value['languageIso'];
}
}
}
return $array;
}
}
Then I call the custom Form Element:
/**
* Original Language Iso
*/
$this->add(
[
'type' => 'Member\Form\Element\OriginalLanguageIsoRadio',
'name' => 'original_language_iso',
'options' => [
'label' => 'original_language_iso'
],
'attributes' => [
'id' => 'original_language_iso',
]
]
);
This adds the following to my form:
<input type="radio" name="original_language_iso" id="original_language_iso" value="en-US">
My desired output is
<input type="radio" name="original_language_iso" id="original_language_iso" value="en-US" **checked**>
Upvotes: 0
Views: 1074
Reputation: 1273
You have two options: a) Backend: The attributes array must contain a 'value' set to the only element of the values available, that's the way to auto-check the radio input. With your example, it would be:
$this->add(
[
'type' => 'Member\Form\Element\OriginalLanguageIsoRadio',
'name' => 'original_language_iso',
'options' => [
'label' => 'original_language_iso'
],
'attributes' => [
'id' => 'original_language_iso',
'value'=>'something_here'
]
]
);
b) Front: Use jQuery to check the radio input. You may do it with:
jQuery('#original_language_iso').attr('checked','checked');
Upvotes: 1