$selected attribute not working in codeigniters form_dropdown() - forms

I have an editform with a dropdown for choosing a category.
I also made a function for getting the category from the database.
I set an array $opties for the dropdown to select form and a 'selected' parameter called $selectie this one contains the category for that specific company in the database.
It looks like this:
<tr>
<td><?= form_label('Categorieen'); ?></td>
<td><?= form_dropdown('categorieen', $opties, $selectie); ?></td>
</tr>
Question
Why is my 'selected' part not working?
When I do a print_r($selectie) I get:
Array
(
[12] => Vlaggen
)
which is my category in the database.
When I do a print_r($opties) I get:
Array
(
[11] => Webdesign
[12] => Vlaggen
[13] => Auto-s
[14] => Electronica
[15] => Boeken
[16] => Antiek-en-Kunst
[17] => Auto-Onderdelen
[18] => Computers-Hardware
[19] => Computers-Software
)
I don't know what the problem is.
Some help would be appreciated.
Controller:
function updatebedrijven()
{
$dbres = $this->db->get('categorieen');
$ddmenu = array();
foreach ($dbres->result_array() as $tablerow) {
$ddmenu[$tablerow['idcategorieen']] = $tablerow['Categorie'];
}
$data['opties'] = $ddmenu;
$id = $this->uri->segment(3);
$id2 = $this->uri->segment(3);
$data['selected'] = $this->members_model->getselection($id2);
$data['info'] = $this->members_model->getbedrijf($id);
$data['id'] = $id;
$this->load->view('members/header');
$this->load->view('members/editform', $data);
$this->load->view('members/footer');
}
Model:
//This one is for the $opties
function getbedrijf($id)
{
$this->db->where('idbedrijven', $id);
$query = $this->db->get('bedrijven');
if ($query->num_rows() == 1) {
$row = $query->row_array(0);
return $row;
}
}
//This one is for the $selectie
function getselection($id2)
{
$this->db->from('bedrijfcategorieen');
$this->db->join('categorieen', 'bedrijfcategorieen.idcategorieen = categorieen.idcategorieen');
$this->db->where('bedrijfcategorieen.idbedrijven', $id2);
$query = $this->db->get();
return $query->result();
}

form_dropdown uses the arrays key => value as its 'value' and 'option',
to select a data from your dropdown you will need the key of your selected data for example you choose
[12] => Vlaggen to select it you need its key which is 12, and not an array like
Array
(
[12] => Vlaggen
)
<?
//just for testing
echo form_dropdown('categorieen', $opties, key($selectie));
?>

Related

Drop down does not show the option in correct format selected in codeigniter

<datalist id="stoplist">
Array
(
[0] => Array
(
[stops] => katraj dairy
)
[1] => Array
(
[stops] => bharati vidyapith
)
[2] => Array
(
[stops] => balaji nagar
)
[4] => Array
(
[stops] => k k market
)
)
</datalist>
This is my view
foreach ($data1 as $row) {
echo "<option value=".$row['stops'].">".$row['stops']."</option>";
}
When I select katraj dairy I get only katraj as a value.
I am getting correct value from database as I print above. What is the problem?
From your controller you need to pass data from your controller before you can access it from your view.
&this->load->view("viewname.php",$data)
Where $data is the array you get from your database
format for select option
<select>
<option value="">name</option>
</select>
Modified code:
echo "<select>";
foreach ($data1 as $row) {
echo "<option value=".$row['stops'].">".$row['stops']."</option>";
}
echo "</select>";

How to get List for Contact Form 7

I have 2 contact forms created by Contact Form 7.
How to list all contact forms created through shortcode?
Please check images, tks.
Updated:
this is my code, this working!
$args = array('post_type' => 'wpcf7_contact_form', 'posts_per_page' => -1);
$rs = array();
if( $data = get_posts($args)){
foreach($data as $key){
$rs[$key->ID] = $key->post_title;
}
}else{
$rs['0'] = esc_html__('No Contact Form found', 'text-domanin');
}
Below is a dropdown list:
<select name="field-name" id="field-id">
<option value="">--Select--</option><?php
$dbValue = get_option('field-name'); //example!
$posts = get_posts(array(
'post_type' => 'wpcf7_contact_form',
'numberposts' => -1
));
foreach ( $posts as $p ) {
echo '<option value="'.$p->ID.'"'.selected($p->ID,$dbValue,false).'>'.$p->post_title.' ('.$p->ID.')</option>';
} ?>
</select>

PHP- PDO get metadata from database

I want to get the metadata from a database with a table 'friends'
id name
1 Herbert
2 LG
3 Levins
Here is the code I was trying to get the data.
<?php
$dsn = 'mysql:host=localhost;dbname=postgre';
$username = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$db = new PDO($dsn, $username, $password, $options);
$stmt = $db->query("SELECT * FROM friends");
$cnt_columns = $stmt->columnCount();
for($i = 0; $i < $cnt_columns; $i++) {
$metadata = $stmt->getColumnMeta($i);
var_dump($metadata);
}
?>
When I execute the code:, it displays
array
'native_type' => string 'LONG' (length=4)
'pdo_type' => int 2
'flags' =>
array
empty
'table' => string 'friends' (length=7)
'name' => string 'id' (length=2)
'len' => int 11
'precision' => int 0
array
'native_type' => string 'VAR_STRING' (length=10)
'pdo_type' => int 2
'flags' =>
array
empty
'table' => string 'friends' (length=7)
'name' => string 'name' (length=4)
'len' => int 60
'precision' => int 0
Till here, it is giving the correct count of rows, but I need the result to display as it looks in the my database like
Output:
id name
1 Hebert
2 LG
3 Levins
How could I get all my fields as it is like a table in my database using metadata.
Use columnCount.
$stmt = $db->query("SELECT * FROM friends");
$cnt_columns = $stmt->columnCount();
for($i = 0; $i < $cnt_columns; $i++) {
$metadata = $stmt->getColumnMeta($i);
var_dump($metadata);
}
By the way, getColumnMeta is experimental. Not recommended to use. Why do you want to use it?
For the desired output, you don't need metadata. Just loop through the results:
$sql = "SELECT * FROM friends";
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
// field names
if(count($result) > 0) {
foreach($result[0] as $k => $v) {
if(!is_int($k)) {
echo $k . "\t";
}
}
}
echo PHP_EOL;
// data
foreach ($result as $row) {
foreach($row as $k => $v) {
if(!is_int($k)) {
echo $row[$k] . "\t";
}
}
echo PHP_EOL;
}

Auditlogging functionality for zend db

I have a requirement to implement audit logging functionality in a zend project. The models are created using zend db and the update function is as follows.
public function updateGroup($data,$id)
{
$row = $this->find($id)->current();
// set the row data
$row->name = $data['name'];
$row->description = $data['description'];
$row->updatedBy = $data['updatedBy'];
$row->updatedOn = date('Y-m-d H:i:s');
$id = $row->save();
return $id;
}
I have to create a table with the auditlog information which includes the current userid. I have tried many methods and nothing is a good solution. What is the best practice for a good audit logging functionality for zend?
I just want to log only the modified data. and the log table schema is like
id,
table,
column,
rowId
oldvalue,
newvalue,
updatedon,
updatedbyuser
use Zend_Log_Writer_Db :
Zend_Log_Writer_Db writes log information to a database table using
Zend_Db. The constructor of Zend_Log_Writer_Db receives a
Zend_Db_Adapter instance, a table name, and a mapping of database
columns to event data items
for example :
$columnMapping = array('name' => 'name',
'desc' => 'desc',
'updatedBy' => 'userid',
'updatedOn' => 'date');
$writer = new Zend_Log_Writer_Db($db, 'auditlog_table', $columnMapping);
$logger = new Zend_Log($writer);
$logger->setEventItem('name', $data['name']);
$logger->setEventItem('desc', $data['name']);
$logger->setEventItem('updatedBy',$data['updatedBy']);
$logger->setEventItem('updatedOn',date('Y-m-d H:i:s'));
EDIT : to log only the modified data :
public function logUpdate(array $values)
{
$columnMapping = array('id' => 'id',
'table' => 'table',
'column' => 'column',
'rowId' => 'rowId',
'oldvalue' => 'oldvalue',
'newvalue' => 'newvalue',
'updatedon' => 'updatedon',
'updatedbyuser' => 'updatedbyuser');
$writer = new Zend_Log_Writer_Db($db, 'auditlog_table', $columnMapping);
$logger = new Zend_Log($writer);
$logger->setEventItem('id', $values['id']);
$logger->setEventItem('table', $values['table']);
$logger->setEventItem('column', $values['column']);
$logger->setEventItem('rowId', $values['rowId']);
$logger->setEventItem('oldvalue', $values['oldValue']);
$logger->setEventItem('newValue', $values['newValue']);
$logger->setEventItem('updatedon', $values['updatedon']);
$logger->setEventItem('updatedbyuser', $values['updatedbyuser']);
}
and in updateGroup :
public function updateGroup($data,$id)
{
$row = $this->find($id)->current();
$values = array('table' => $this->name);
$values = array('updatedon' => $data['updatedBy']);
$values = array('updatedbyuser' => date('Y-m-d H:i:s'));
//go through all data to log the modified columns
foreach($data as $key => $value){
//check if modified log the modification
if($row->$key != $value){
$values = array('column' => $key);
$values = array('oldValue' => $row->$key);
$values = array('newValue' => $value);
logUpdate($values);
}
}
// set the row data
$row->name = $data['name'];
$row->description = $data['description'];
$row->updatedBy = $data['updatedBy'];
$row->updatedOn = date('Y-m-d H:i:s');
$id = $row->save();
return $id;
}
Note that its better to implement logging for all your application and seperate logging from update , see this answer for that .

zend-form select optgroup, how to specify id

Hello i am using Zend Framework Form and have tried to get this example to work http://framework.zend.com/issues/browse/ZF-8252, but it fails xD
this is my code
$options = Array
(
[] => Qualsiasi Agente
[agenti_attivi] => Array
(
[4] => Giovanni Abc
[10] => Luigi Abc
[13] => Michela Abc
)
);
$agenti->addMultiOptions($options);
and the generated code is :
<select name="agente_id" id="agente_id" tabindex="6">
<option value="" label="Qualsiasi Agente" selected="selected">Qualsiasi Agente</option>
<optgroup id="agente_id-optgroup-Agenti attivi: " label="Agenti attivi: ">
<option value="4" label="Giovanni Abc">Giovanni Abc</option>
<option value="10" label="Luigi Capoarea">Luigi Abc</option>
<option value="13" label="Michela Abc">Michela Abc</option>
</optgroup>
</select>
where id="agente_id-optgroup-Agenti attivi: " is not xhtml valid Line 724, Column 44: value of attribute "id" must be a single token
i am using zend 1.11.10
thanks
Create a custom view helper FormSelect that extends the core FormSelect and then modify the code.
Include the path to your view helpers in the bootstrap file
protected function _initHelpers()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
The custom view helper. It's a copy of Zend_View_Helper_FormSelect but with small modification.
class My_View_Helper_FormSelect extends Zend_View_Helper_FormSelect
{
public function formSelect($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// check if element may have multiple values
$multiple = '';
if (substr($name, -2) == '[]') {
// multiple implied by the name
$multiple = ' multiple="multiple"';
}
if (isset($attribs['multiple'])) {
// Attribute set
if ($attribs['multiple']) {
// True attribute; set multiple attribute
$multiple = ' multiple="multiple"';
// Make sure name indicates multiple values are allowed
if (!empty($multiple) && (substr($name, -2) != '[]')) {
$name .= '[]';
}
} else {
// False attribute; ensure attribute not set
$multiple = '';
}
unset($attribs['multiple']);
}
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
. ' name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $multiple
. $disabled
. $this->_htmlAttribs($attribs)
. ">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ((array) $options as $opt_value => $opt_label) {
if (is_array($opt_label)) {
$opt_disable = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
if (null !== $translator) {
$opt_value = $translator->translate($opt_value);
}
$opt_id = ' id="' . $this->formatElementId($id . '-optgroup-' . $opt_value) . '"';
$list[] = '<optgroup'
. $opt_disable
. $opt_id
. ' label="' . $this->view->escape($opt_value) .'">';
foreach ($opt_label as $val => $lab) {
$list[] = $this->_build($val, $lab, $value, $disable);
}
$list[] = '</optgroup>';
} else {
$list[] = $this->_build($opt_value, $opt_label, $value, $disable);
}
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list) . "\n</select>";
return $xhtml;
}
private function formatElementId($id)
{
// in here put whatever filter you want for the id value
$id = trim(strtr($id, array('[' => '-', ']' => '', ' ' => '', ':' => '')), '-');
$id = strtolower($id);
return $id;
}
}
Done. Create multi select element with a valid id.
<?php
$this->addElement('multiSelect', 'agente_id', array(
'label' => 'Label Name:',
'multiOptions' => array(
'' => 'Qualsiasi Agente',
'Agenti attivi: ' => array(
4 => 'Giovanni Verdi',
10 => 'Luigi Capoarea',
13 => 'Michela Passarin',
)
)
));
try this, it's works for me:
$select = new Zend_Form_Element_Select('select');
$options = Array(
'' => 'Qualsiasi Agente',
'agenti_attivi' => Array(
4 => 'Giovanni Verdi',
10 => 'Luigi Capoarea',
13 => 'Michela Passarin'
)
);
$this->addElements(array($xxxx,$select,$yyyy)); // $this : the form instance
and the result is:
<select id="select" name="select">
<option label="Qualsiasi Agente" value="">Qualsiasi Agente</option>
<optgroup label="agenti_attivi">
<option label="Giovanni Verdi" value="4">Giovanni Verdi</option>
<option label="Luigi Capoarea" value="10">Luigi Capoarea</option>
<option label="Michela Passarin" value="13">Michela Passarin</option>
</optgroup>
</select>
the problem is that the id attribute does not accept spaces and special special characters:
id="agente_id-optgroup-Agenti attivi: "
Zend is usually pretty good about rendering the proper html, given a doctype.
Try setting your doctype like this if you aren't already.
<?php
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->initView();
$viewRenderer->view->doctype('XHTML1_STRICT');
AND
<?php echo $this->doctype(); ?>
at the top of your layout
I don't have a install of ZF i can mess with easy, if this doesn't work ill setup a test environment.