Since i've to position checkboxes in design I'm not using MultiCheckbox and using Checkbox instead in zend. I've seen some zf1 solutions but didnt found any zf2 or zf3 solutions.
My Php Code
$languages = new \Zend\Form\Element\Checkbox('languages[]');
$languages->setLabel('English');
$languages->setValue('1');
This produce the following output
<?php
echo $this->formRow($form->get('languages[]'));
//It produce the following
?>
<input type="checkbox" name="languages[]" value="1" checked="checked">
How can I add more items with name "languages[]" without writing direct HTML code ?
You can use a Form collection for this:
1) In your form:
use Zend\Form\Element\Collection;
...
$languages = new \Zend\Form\Element\Checkbox();
$languages->setLabel('English');
$languages->setValue('1');
$languages->setName('language');
$collection = new Collection();
$collection->setName('languages');
$collection->setLabel('Language Collection');
$collection->setCount(2);
$collection->setTargetElement($languages);
$collection->populateValues(array(
1, 0
));
$this->add($collection);
2) Do not forget to prepare your form in your controller action:
$form->prepare();
3) Finally, in your view, get all elements of the collection and render them separately:
<?php $elements = $form->get('languages')->getElements(); ?>
<?php //echo $this->formCollection($form->get('languages')); ?>
<?php echo $this->formRow($elements[0]); ?>
<?php echo $this->formRow($elements[1]); ?>
You can use MultiChebox
https://framework.zend.com/manual/2.2/en/modules/zend.form.element.multicheckbox.html
It works similar to radio form element. Your example implementation
use Zend\Form\Element;
$languages = new Element\MultiCheckbox('languages');
$languages->setLabel('Used languages');
$languages->setValueOptions([
'en_US' => 'english',
'de_DE' => 'german',
'pl_PL' => 'polish',
]);
$languages->setValue('en_US'); //default value; you can use array
My solution (Method 2)
Method 1:
Give name as "language[1]" instead of "language[]". By using this I can call the elements in view seperately.
Creating form.
$language1 = new \Zend\Form\Element\Checkbox('language[1]');
$language2 = new \Zend\Form\Element\Checkbox('language[2]');
$form = new Form('Set');
$form->add($name)
->add($language1)
->add($language2)
->add($submit);
In view file
<div><?php echo $form->get('language[1]');?></div>
<div><?php echo $form->get('language[2]');?></div>
Edit: Method 2
Using fieldset
//Create form
$languages = [
['id' => 1, 'language' => 'English'],
['id' => 2, 'language' => 'Malayalam'],
] ;
$fieldSet = new \Zend\Form\Fieldset('languages') ;
foreach( $languages as $one ) {
$c = new \Zend\Form\Element\Checkbox($one['id']);
$c->setLabel($one['language']) ;
$fieldSet->add($c) ;
}
//Add collection of checkboxes to form
$form->add($fieldSet) ;
In view file
<?php
$language = $form->get('languages') ;
?>
<div class="form-group row">
<label class="control-label col-sm-2" >Choose Languages</label>
<div class="col-sm-10">
<?php foreach($language as $one ) { ?>
<?php echo $this->formCheckbox($one); ?> <span> <?php echo $this->formLabel( $one ) ; ?> </span>
<?php echo $this->formElementErrors($one); ?>
<?php } ?>
</div>
</div>
Related
I have an array like this
$current_asset = [
['name'=>'Land,'id'=>1],
['name'=>'Building ,'id'=>2],
['name'=>'Machinery','id'=>3],
];
<?php
foreach($current_asset as $key=>$value){ ?>
<input type="checkbox" name="current_asset[]" value="<?php echo $value['id'] ?>">
<?php } ?>
My question how can I add checked attribute in if one of the value is checked when the form populated with the POST data
I am getting the checkbox array like this on form submit
Here are the current checkboxes on form submit (ie values of current_asset)
Array(
0=>1
1=>1
)
You would need to do some kind of check before printing
$html=‘’;
foreach($current_asset as $asset) {
if($asset[‘hasBeenCheckedBefore’]) {
$checked = ‘checked’;
} else {
$checked = ‘’;
}
$html .= “$asset[‘name’] <input type=‘checkbox’ name=‘current_asset[]’ value=‘$asset[“id”]’ $checked />”;
}
Here is an example of one way to do it. I have changed your data structure to be easier to use. I was confused initially because you didn't mention any way to store data. So this is only good for the one page view.
<?php
// initialize data
/**
* Data structure can make the job easy or hard...
*
* This is doable with array_search() and array_column(),
* but your indexes might get all wonky.
*/
$current_asset = [
['name'=>'Land','id'=>1],
['name'=>'Building' ,'id'=>2],
['name'=>'Machinery','id'=>3],
];
/**
* Could use the key as the ID. Note that it is being
* assigned as a string to make it associative.
*/
$current_asset = [
'1'=>'Land',
'2'=>'Building',
'3'=>'Machinery',
];
/**
* If you have more information, you could include it
* as an array. I am using this setup.
*/
$current_asset = [
'1'=> ['name' => 'Land', 'checked'=>false],
'2'=> ['name' => 'Building', 'checked'=>false],
'3'=> ['name' => 'Machinery', 'checked'=>false],
];
// test for post submission, set checked as appropriate
if(array_key_exists('current_asset', $_POST)) {
foreach($_POST['current_asset'] as $key => $value) {
if(array_key_exists($key,$current_asset)) {
$current_asset[$key]['checked'] = true;
}
}
}
// begin HTML output
?>
<html>
<head>
<title></title>
</head>
<body>
<!-- content .... -->
<form method="post">
<?php foreach($current_asset as $key=>$value): ?>
<?php $checked = $value['checked'] ? ' checked' : ''; ?>
<label>
<input type="checkbox" name="current_asset[<?= $key ?>]" value="<?= $key ?>"<?= $checked ?>>
<?= htmlentities($value['name']) ?>
</label>
<?php endforeach; ?>
</form>
<body>
</html>
i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)
Elgg Version 2.0
How can I go about creating an Elgg entity with an image icon, just like how one can do when creating an Elgg group?
I've tried implementing the following, but no image gets uploaded:
Action file:
<?php
// get the form inputs
$title = get_input('title');
$body = get_input('body');
$tags = string_to_tag_array(get_input('tags'));
// create a new my_blog object
$blog = new ElggObject();
$blog->subtype = "nganya";
$blog->title = $title;
$blog->description = $body;
// for now make all my_blog posts public
$blog->access_id = ACCESS_PUBLIC;
// owner is logged in user
$blog->owner_guid = elgg_get_logged_in_user_guid();
// save tags as metadata
$blog->tags = $tags;
// save to database and get id of the new my_blog
$blog_guid = $blog->save();
// if the my_blog was saved, we want to display the new post
// otherwise, we want to register an error and forward back to the form
if ($blog_guid) {
system_message("Your nganya post was saved >>>>>>>>>> " . $blog_guid);
forward($blog->getURL());
} else {
register_error("The nganya post could not be saved");
forward(REFERER); // REFERER is a global variable that defines the previous page
}
$has_uploaded_icon = (!empty($_FILES['icon']['type']) && substr_count($_FILES['icon']['type'], 'image/'));
if ($has_uploaded_icon) {
$icon_sizes = elgg_get_config('icon_sizes');
$prefix = "nganya/" . $blog->guid;
$filehandler = new ElggFile();
$filehandler->owner_guid = $blog_guid;
$filehandler->setFilename($prefix . ".jpg");
$filehandler->open("write");
$filehandler->write(get_uploaded_file('icon'));
$filehandler->close();
$filename = $filehandler->getFilenameOnFilestore();
$sizes = array('tiny', 'small', 'medium', 'large', 'master');
$thumbs = array();
foreach ($sizes as $size) {
$thumbs[$size] = get_resized_image_from_existing_file(
$filename,
$icon_sizes[$size]['w'],
$icon_sizes[$size]['h'],
$icon_sizes[$size]['square']
);
}
if ($thumbs['tiny']) { // just checking if resize successful
$thumb = new ElggFile();
$thumb->owner_guid = $blog->owner_guid;
$thumb->setMimeType('image/jpeg');
foreach ($sizes as $size) {
$thumb->setFilename("{$prefix}{$size}.jpg");
$thumb->open("write");
$thumb->write($thumbs[$size]);
$thumb->close();
}
$blog->icontime = time();
}
}
The Form:
<div>
<label><?php echo elgg_echo("groups:icon"); ?></label><br />
<?php echo elgg_view("input/file", array("name" => "icon")); ?>
</div>
<div>
<label for="title"><?= elgg_echo("title"); ?></label><br />
<?= elgg_view('input/text', ['name' => 'title', 'id' => 'title']); ?>
</div>
<div>
<label for="body"><?= elgg_echo("body"); ?></label><br />
<?= elgg_view('input/longtext', ['name' => 'body', 'id' => 'body']); ?>
</div>
<div>
<label for="tags"><?= elgg_echo("tags"); ?></label><br />
<?= elgg_view('input/tags', ['name' => 'tags', 'id' => 'tags']); ?>
</div>
<div>
<?= elgg_view('input/submit', ['value' => elgg_echo('save')]); ?>
</div>
The action code looks correct. In Elgg 2.2, this will be a lot easier, but in the meantime:
You need to add a plugin hook handler for
'entity:icon:url',<entity_type> hook and replace the URL if
$params['entity'] is of the subtype your are adding
Update your page handler to serve a file for the above URL.
I am using the Yii Framework 1.1.17, and have generated three models:
Question, AnswerOption and Response.
The relationships:
Table: Question (list of questions)
id
text
Table: AnswerOption (list of possible answers, associated with question)
id
question_id
text
Table: Response (question and selected answer collector)
id
question_id
answer_option_id
text
I am trying to create a form, and admittedly collect answers for all possible questions.
File: ResponseController
public function actionCreate()
{
// load all questions and with it the possible answer Options
$questions = Question::model()->findAll();
// get number of questions
$count = Question::Model()->count();
$model = array();
$i = 1;
while ($i <= $count) {
$model[] = Response::model();
$i++;
}
if (isset($_POST['Response'])) {
//
}
$this->render('create', array(
'model' => $model,
'questions' => $questions,
));
}
This is the area that I am having trouble with:
File: response/_form
<?php foreach($questions as $i=>$question): ?>
<?php echo CHtml::activehiddenField($question,"[$i]id"); ?> <?php echo $question['text']; ?>
<?php $options = CHtml::listData($question->answerOptions, 'id', 'text');?>
<?php echo CHtml::activeDropDownList(AnswerOption::model(), "[$i]text", $options, array('empty' => 'Select answer...')); ?>
<?php endforeach; ?>
I may have populated my questions and possible answers, but I need to validate and save the results in $model.
It seems like I cannot find a way to efficiently work this out. Can someone please guide me?
I managed to resolve my "loop" problem by:
File: response/_form
<?php $questions = Question::model()->findAll(); ?>
<?php foreach ($questions as $j=>$question): ?>
<div class="row">
<?php echo $form->labelEx($model["$j"], "[$j]question_id"); ?>
<?php echo $form->hiddenField($model["$j"], "[$j]question_id", array('value' => $question["id"])); ?>
<?php echo $question['text']; ?>
</div>
<div class="row">
<?php $options = CHtml::listData($question->answerOptions, 'id', 'text');?>
<?php echo $form->labelEx($model["$j"], "[$j]answer_option_id"); ?>
<?php echo $form->dropDownList($model["$j"], "[$j]answer_option_id", $options, array('empty' => 'Select answer...')); ?>
</div>
<?php endforeach; ?>
Hopefully, this would come in handy for someone, someday.
i have a countries, states, cities tables , and I need 3 dropdown menus
wherein, if i select a country like e.g United States, the states dropdown menu will automatically show only the states that are under United States, and next, if I select a State like e.g California, the Cities drop down menu will only show off the Cities under California
am currently having problem implementing this in yii. I have this _form file
where these 3 dropdown should be included. I have a partial code, but I can't figure out how to make this work out
this is from the Controller
public function actionDynamicstates()
{
$sql = "SELECT StateName FROM gg_t_worldareasstates ".
"WHERE CountryID = :countryid";
$command = Yii::app()->createCommand($sql);
$command->bindValue(':countryid', $_POST['CountryID'], PDO::PARAM_INT);
$data = $command->execute();
$data = CHtml::listData($data,'StateID','StateName');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
this is from the _form view file
<div class="row">
<?php
$country = new CDbCriteria;
$country->order = 'CountryName ASC';
echo $form->dropDownList($model, 'CountryID',
CHtml::listData
(
Worldareascountries::model()->findAll($country),
'CountryID',
array
(
'ajax' => array
(
'type' => 'POST',
'url' => CController::createUrl('wsmembersdetails/dynamicstates'),
'update' => '#StateID',
)
)
)
);
echo $form->dropDownList('StateID','', array());
?>
</div>
I changed that those codes above into this one
<div class="row">
<?php echo $form->labelEx($model,'Country'); ?>
<?php
$country = new CDbCriteria;
$country->order = 'CountryName ASC';
?>
<?php
echo $form->dropDownList($model,'CountryID',CHtml::listData(Worldareascountries::model()->findAll($country),'CountryID','CountryName'),
array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('wsmembersdetails/dynamicstates'),
'update' => "#StateID"
)
)
);
?>
<?php echo $form->error($model,'CountryID'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'State'); ?>
<?php
$state = new CDbCriteria;
$state->order = 'StateName ASC';
?>
<?php
echo $form->dropDownList($model,'StateID',CHtml::listData(Worldareasstates::model()->findAll($state),'StateID','StateName'),
array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('wsmembersdetails/dynamiccities'),
'update' => '#CityID'
)
)
);
?>
<?php echo $form->error($model,'StateID'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'CityID'); ?>
<?php echo $form->dropDownList($model,'CityID','',array());?>
<?php echo $form->error($model,'CityID'); ?>
change this line
$data = $command->execute();
to
$data = $command->query();
this problem was solved, it's on the yii wiki docs