Zend2 Form - set attributes to options in select element - php

I wonder how to add some attributes to select's options in Zend 2. My form element looks like this:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'brand_name',
'options' => array(
'label' => 'Choose brand',
'value_options' => $this->getBrands(),
),
));
So it's populate select looking similar to this:
<select name="brand_name"><option value="1">aaaa</option></select>
But I want to achieve something like this:
<select name="brand_name"><option value="1" class="test">aaaa</option></select>
And the classes should be different, depends on particular option. Is it possible? Why am I trying this? I need to add jquery plugin - chained which needs classes for options.

I've found a solution, array of parent select value_options should look like this:
foreach ($data as $item) {
$models[] = array(
'label' => $item->model_name,
'attributes' => array('class' => $item->id_brand_list),
'value' => $item->id);
}

If your data were array that you preferred getting from sql or db, you can code like:
public function getOptionsForDataSelect()
{
$dbAdapter = $this->_adapter;
$sql = "SELECT * FROM db_name ORDER BY db_name ASC";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[] = array(
'label' => $res['label_data'],
'attributes' => array(
'data-key' => $res['data_id']
),
'value' => $res['value_id']
);
// $selectData[$res['id']] = $res['name'];
}
return $selectData;
}

Related

how to modify <select required> to form_dropdown in codeigniter

according to the question asked by Outliers here, and according to the answer posted by Adr
echo form_dropdown('salutation', $salutationOptions, '', 'required="required"');
i've tried similar line of code when creating form_dropdown in controller of code igniter, i do it like this
$code = array(
'type' => 'text',
'id' => 'productcode',
'name' => 'productcode',
'class' => 'form-control',
'required'=> 'required'
);
$form['open'] = form_open_multipart('Mould/saveeditproduct');
$form['code'] = form_input($code);
$form['category'] = form_dropdown('category',$category,'','id="category" class="form-control" required="required"');
$form['submit'] = form_input($submit);
$form['close'] = form_close();
i try to run the program, i found that the 'required' property is worked well in form_input, but does not work in form_dropdown. so, how can i fix this? thank you
The problem was that you assigned a value for first option in dropdown (----- Select Category -----) as 0
Try this code:
// $data['category'] = array( array('idcategory' => 4,'categoryname' => 'new'),
// array('idcategory' => 2,'categoryname' => 'old'));
$data['category'] = $this->Mouldmodel->getallcategory();
$category[] = array();
$category[''] = '----- Select Category -----';
foreach($data['category'] as $dm){
$category[$dm['idcategory']] = $dm['categoryname'];
}

Laravel: eloquent relationship create multi

i have a ParentItem model
$parentItem = ParentItem::get()->first();
I have this array
$items = array(
array(
'title' => 'test1',
'desc' => 'test1'
),
array(
'title' => 'test2',
'desc' => 'test2'
)
);
i want to add it as a has many relationship.
so i can do:
foreach($items as $item) {
$parentItem->items()->create($item)
}
is there any way way to create all at once..?
something like:
$parentItem->items()->createMany($items);
You can tryout two path.
Using saveMany method:
$parentItem = ParentItem::first();
$items = array(
new Item(['title' => 'test1','desc' => 'test1']),
new Item(['title' => 'test2','desc' => 'test2'])
);
$parentItem->items()->saveMany($items)
For further info you can read here.
https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models
Using insert method:
$parentItem = ParentItem::first();
$items = array(
array('title' => 'test1','desc' => 'test1','parent_item_id' => $parentItem->id),
array('title' => 'test2','desc' => 'test2','parent_item_id' => $parentItem->id)
);
Item::insert($items);
Remember in insert created_at and updated_at won't be inserted automatically, you have to provide them in the array if you have them in your table. For further info you can read here.
https://laravel.com/docs/5.1/queries#inserts
As of right now, you may use the createMany Eloquent method to achieve this.
Details here: https://laravel.com/docs/9.x/eloquent-relationships#the-create-method

get configuration scope selector for custom module

I'm working on a module where I need to save the records based on the scope of website and store. For that I need to have the select box as its in the system->configuration.
How can I get that select box in my form and save the website/store value in database so that it can be displayed in the specific store/website? Any suggestions on it?
Now I'm trying it breaking into two fields -> website and store. Now, how can I change the options in store based on the website selected?
Finally, I'd written my own code for this.
$scope = array('default' => 'default');
foreach (Mage::app()->getWebsites() as $website) {
$scope['website_' . $website->getCode()] = $website->getName();
foreach ($website->getGroups() as $group) {
$stores = array();
foreach ($group->getStores() as $store) {
$stores[] = array(
'label' => $store->getName(),
'value' => 'store_' . $store->getCode()
);
}
$scope[] = array(
'label' => $website->getName(),
'value' => $stores
);
}
}
$fieldset->addField('website', 'select', array(
'label' => Mage::helper('designer')->__('Website'),
'name' => 'website',
'values' => $scope
));
Thanks to this post by Marius

Cakephp $this->request->data returns id of select field instead of value which is needed and shown in the select field

I have a CakePHP controller like this:
$this->loadModel('Project');
$list2 = $this->Project->find( 'list', array(
'fields' => array('Project.project'),
'conditions' => array('Project.user_id' => $userId)
));
$this->set($list2, 'list2');
$this->loadModel('Distance');
if(!empty($this->request->data)){
$this->Distance->create();
if ($this->Distance->save($this->request->data)) {
$this->Session->setFlash('Saved.');
// $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('FAILED');
}
}else{
// $this->Session->setFlash('test');
}
and a view like this:
echo $this->Form->input('Distance.project', array('options' => $list2, 'label' => false, 'empty' => '(choose one)' ;
But I get inserted to the database the id of the project instead of the project name.
I never have such problems working with the fields - just with a list of data.
Any idea why it happens?
It's normal ... The $list2 it's and array ... and the values of the options are the indexes from that array.
If you want to insert only the project name you need to change $list2 with $list2['project_name']. You need to remove or replace the indexes of $list2.
LE: take iexiak example. He change also the code for you.
$list2 = $this->Project->find( 'list', array(
'fields' => array('Project.project'),
'conditions' => array('Project.user_id' => $userId)
)
);
This is because $list2 automatically creates a list of ID => project; and when you use that as input for your form it automatically creates the drop down to reflect this. This is generally the best practice, to link to ID's instead of to descriptions, as ID's do not change as often. The below should get you exactly what you want though:
$list2 = $this->Project->find( 'list', array(
'fields' => array('Project.project','Project.project'),
'conditions' => array('Project.user_id' => $userId)
)
);

How to include drupal form elements in a data table

I have a data table which is populated with data unrelated to drupal content (from a third party system). The data relates to photos which must be approved / flagged as inappropriate.
So I'm writing a Drupal admin module which should moderate this content. So far, I have built a table using theme('table',...) which shows 1 photo per row, along with some other meta data. I now want to include some form buttons in the table and build some Ajax actions which are triggered by those buttons.
This article looks relevant http://drupal.org/node/112358 but I'm concerned this isn't the Drupal 6 way of doing things.
Can anyone offer some advice on how best to approach this problem - preferably using core modules / form override functions. Drupal version is 6.14.
Custom theme functions allow you to render content in a completely custom way. You can also create a custom template for your content, this could include the buttons.
hook_theme() will allow you to create your own content type to add to the theme function so you could have theme('moderatedimages').
A workaround would be to put the HTML for the moderate buttons into the table data so that it is output by theme table. This would save you having to write your own theme function.
For the AJAX calls you will need to build your own menu callback using hook_menu() and a custom function. (Code snippets are from this tutorial.)
<?php
function mymodule_products_menu() {
$items = array();
$items['products/get'] = array(
'title' => 'mymodule callback',
'page callback' => 'mymodule_myfunction',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK
);
return $items;
}
This will call the function mymodule_myfunction(). One thing to remember about this function is that you want to print the result and exit. You may want to use drupal_json() to encode the response.
Why are you using the standard theme_table() function? Just make your own theme function that includes the form elements you need. More on theme functions here and here.
I had the same problem. I found the solution in drupal-directory/modules/menu/menu.admin.inc. The Form-API and Themes will be used only!
Implementation:
-write your query with scheme-api (I think you did it already for your theme('table',...) )
-for each row create a form like this:
$form[$row->id]['column_name_1'] = array(...here description of the column -> checkbox, textfield...);
$form[$row->id]['column_name_2'] = array(...);
-write your own theme-funktion, witch use hook_theme_table (you habe already did it, you need only to change some cells into checkboxes or other form-elements.)
I write a submit-function now, but it doesn't work :-) For more information see the menu-modul.
Hier my code:
/**
* Form for editing the event types.
*
* #ingroup forms
*/
function mymodule_event_type_overview_form() {
$vid = variable_get('mymodule_category_vocabulary', '');
$sql = "SELECT term_data.tid AS tid,
term_data.name AS tname,
term_data.vid AS vid,
term_site_config.color AS color,
term_site_config.site_enabled AS site_enabled,
term_site_config.site_shown AS site_shown
FROM {term_data} term_data
INNER JOIN {term_site_config} term_site_config
ON term_data.tid = term_site_config.tid
WHERE term_data.vid = %d";
$result = db_query(db_rewrite_sql($sql), $vid);
$form = array(); while ($term = db_fetch_object($result)) {
$form[$term->tid]['tname'] = array(
'#type' => 'value',
'#value' => $term->tname,
);
$form[$term->tid]['color'] = array(
'#type' => 'value',
'#value' => $term->color,
);
$form[$term->tid]['enabled'] = array(
'#type' => 'checkbox',
'#default_value' => $term->site_enabled,
);
$form[$term->tid]['shown'] = array(
'#type' => 'checkbox',
'#default_value' => $term->site_shown,
);
// Build a list of operations.
$operations = array();
$operations['delete'] = l(t('delete'), 'admin/settings/mymodule/eventtype/'. $term->tid .'/delete');
$operations['edit'] = l(t('edit'), 'admin/settings/mymodule/eventtype/'. $term->tid .'/edit');
$form[$term->tid]['operations'] = array();
foreach ($operations as $op => $value) {
$form[$term->tid]['operations'][$op] = array('#value' => $value);
} }
if (element_children($form)) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save configuration'),
);
$form['reset'] = array(
'#type' => 'submit',
'#value' => t('Reset to defaults'),
);
if (!empty($_POST) && form_get_errors()) {
drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
} }else {
$form['empty'] = array('#value' => t('There are no event types yet.')); }
return $form; }
/**
* Theme the event type overview form into a table.
*
* #ingroup themeable
*/
function theme_mymodule_event_type_overview_form($form) {
$header = array(
t('Event type'),
t('Color'),
array('data' => t('Enabled'), 'class' => 'checkbox'),
array('data' => t('Shown'), 'class' => 'checkbox'),
array('data' => t('Operations'), 'colspan' => '2'), );
$rows = array(); foreach (element_children($form) as $id) {
$element = &$form[$id];
if (isset($element['tname'])) {
$row = array(
t($element['tname']['#value']),
t($element['color']['#value']),
array('data' => drupal_render($element['enabled']), 'class' => 'checkbox'),
array('data' => drupal_render($element['shown']), 'class' => 'checkbox'),
array('data' => drupal_render($element['operations']['delete'])),
array('data' => drupal_render($element['operations']['edit'])),
);
$rows[] = $row; } } $output = ''; if ($rows) {
$output .= theme('table', $header, $rows); }
$output .= drupal_render($form);
return $output;
}
You will get the html-code of the form if you call drupal_get_form('mymodule_event_type_overview_form');
and don't forget co write following function in mymodule.module:
/**
* Implementation of hook_theme().
*/ function mymodule_theme() {
return array(
'mymodule_event_type_overview_form' => array(
'arguments' => array(),
),
);
}
Have fun :-)
Katja

Categories