If for example i have the following data retreived from a database:
--------------------------
| id | name | department|
--------------------------
| 1 | john | HR |
--------------------------
| 2 | peter| accounting|
--------------------------
| 3 | adam | secretary |
--------------------------
how can i create an optgroup tag to display this result in an optgroup to have the following:
<select >
<optgroup label='HR'>
<option value='1'>john</option>
</optgroup>
<optgroup label='accounting'>
<option value='2'>peter</option>
</optgroup>
<optgroup label='secretary'>
<option value='3'>adam</option>
</optgroup>
</select>
This may not be the best way, but you could represent department as a model and do it this way :
User model :
public class User extends Model {
public String name;
#ManyToOne
public Department department;
}
Department model :
public class Department extends Model {
public String name;
public List<User> getUsers() {
List<User> users = new Arraylist<User>();
if (this.id != null) {
users = User.find("department.id is ?", this.id).fetch();
}
return users;
}
}
Then in your view you can generate your select box list this way
<select>
#{list departments, as : 'department'}
<optgroup label="${department.name}"">
#{list department.users, as : 'user'}
<option value="${user.id}">${user.name}</option>
#{/list}
</optgroup>
#{/list}
</select>
Like I said, perhaps there is a better way, (maybe using raw sql queries...)
Related
why i cant get the ID of payment type, even i already print the ID in the html?
in my first html (elementary.html) I have this code
<select name="gradelevel" id="gradelevel" onchange="ChangeYearList(this.value)">
<option">-- Education Level --</option>
{% for ylvl in edulevel %}
<option value="{{ylvl.id}}">{{ylvl.Description}}</option>
{% endfor %}
</select>
<div id="txtHint" class="scale-in-center" width="100%"></div>
<script>
function ChangeYearList(str) {
var xhttp;
var x = document.getElementById("gradelevel").value;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
document.getElementById("demo").innerHTML = x;
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "{% url 'paymentElementary' %}?payments_ID="+str, true);
xhttp.send();
}
</script>
this is my views.py
def paymentElementary(request):
paymentsid = request.GET.get('payments_ID')
payment = ScheduleOfPayment.objects.filter(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type')
return render(request, 'accounts/paymentElementary.html', {"payment":payment})
This is my second html (paymentElementary.html)
<select id="payments" name ="payments">
<option value="0">-- Payment Type --</option>
{% for paymentschedule in payment %}
<option value="{{paymentschedule.Payment_Type.id}}">{{paymentschedule.Payment_Type.id}}. {{paymentschedule.Payment_Type}}</option>
{% endfor%}
</select>
this is what it looks like in web view
it works like a charm. but when i tried to save it into my database
id = request.POST.get('payments')
payment = PaymentType(id=id)
V_insert_data = StudentsEnrollmentRecord.objects.create(
Payment_Type=payment
)
this is the error
this is the full traceback
update view.py file in this way
def paymentElementary(request):
paymentsid = request.GET.get('payments_ID')
payment = ScheduleOfPayment.objects.get(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type')
return render(request, 'accounts/paymentElementary.html', {"payment":payment})
I've created a select options with html and templating in flask.
What I need to accomplish is to take the option values and put it inside my code, here is my html code :
<select id="oblast_select" name='areaid'>
<option value="0">0</option>
<option value="5971">value1</option>
<option value="7402">value2</option>
<option value="5219">value3</option>
<option value="4949">value4</option>
<option value="5764">value5</option>
<option value="7412">6</option>
<option value="6217">value7</option>
<option value="6802">value8</option>
<option value="6940">value9</option>
</select>
Also here is my java code that sends post request to python file:
var serviceid = document.getElementById("name_street").value;
var areaid = document.getElementById('oblast_select').value;
$(".btn").addClass("clicked");
$.post(
"/serviceidlookup",
{ serviceid: serviceid },
{ areaid: areaid }
).done(function (reply) {
$(".spinner").css("display", "block");
$('.spinner').fadeOut(5500);
setTimeout(function() {
$('#reply').empty().append(reply).fadeIn(3000);
}, 4000);`enter code here`
});
and finally my python file run.py:
#app.route('/serviceidlookup', methods=["GET", "POST"])
def serviceidlookup():
reload(sys)
sys.setdefaultencoding("utf-8")
sys.stdout.encoding
serviceid = request.form.get('serviceid')
areaid = request.args.get('areaid')
idarea = str(areaid)
con = psycopg2.connect(**config)
cur = con.cursor()
cur.execute("select ate,ate_type,name_kg,name_ru,name_en,parent from ate_history where ate in (select ate from street_ate where street in (select street from street_history where name_ru = '%s') and parent = %s)" %(serviceid,idarea))
entries = [dict(ate=row[0], ate_type=row[1], name_kg=row[2], name_ru=row[3], name_en=row[4], parent=row[5]) for row in cur.fetchall()]
return render_template('lookup.html', serviceid=serviceid, entries=entries)
After running this code, in the terminal gives me this error :
**LINE 1: ...om street_history where name_ru = 'None') and parent = None)**
infact, i get the serviceid value from the input field that i've created, it didn't get the other value which is in our case on of the options so for example 7402 to be inside the query at this part :
and parent = %s)"
Please any help would be toooooooons appreciated !!!!!!!
You have written
serviceid = request.form.get('serviceid')
areaid = request.args.get('areaid')
Try changing areaid to match the serviceid i.e
serviceid = request.form.get('serviceid')
areaid = request.form.get('areaid')
Edit: Try replacing
var areaid = document.getElementById('oblast_select').value;
with this..
var e = document.getElementById("oblast_select");
var areaid= e.options[e.selectedIndex].value;
Edit2: Change your jQuery post to this..
$.post(
"/serviceidlookup",
{ serviceid: serviceid },
{ areaid: areaid } , function (reply) {
$(".spinner").css("display", "block");
$('.spinner').fadeOut(5500);
setTimeout(function() {
$('#reply').empty().append(reply).fadeIn(3000);
}, 4000);
});
According to the Flask docs - http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.MultiDict the request.args.get() method will only return the first element by default. To get all the values you need to use a list method; request.args.getlist().
For the past 3 days, I've been stuck on a dropdown list development using joomla 2.5, I have to retrieve data from database and show this data in a drop down the steps I followed are mentioned below:
Inside the models folder I have created a new model inside fields folder and name this file "fieldname.php"
Now the file "Models/fields/fieldname.php" contains following source code:
<?php
defined('JPATH_BASE') or die;
jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
class JFormFieldMyCompany extends JFormFieldList
{
protected $type = 'MyCompany';
public function getOptions()
{
// Initialize variables.
$options = array();
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id As value,name As text');
$query->from('#_k2_tags AS a');
$query->order('a.name');
$db = $this->getDbo();
// Get the options.
$db->setQuery($query);
$options = $db->loadObjectList();
// Check for a database error.
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
}
print_r($options);exit;
return $options;
}
}
after that inside my model filter.php I added the following code.
Models/filter.php:
<?php
defined( '_JEXEC' ) or die;
jimport('joomla.application.component.modeladmin');
class FiltersModelFilter extends JModelAdmin
{
//Add this handy array with database fields to search in
protected $searchInFields = array('text','a.name');
//Override construct to allow filtering and ordering on our fields
public function __construct($config = array()) {
$config['filter_fields']=array_merge($this->searchInFields,array('a.name'));
parent::__construct($config);
}
public function getTable($type = 'Filter', $prefix = 'FiltersTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
protected function loadFormData()
{
$data = JFactory::getApplication()->getUserState('com_filters.edit.filter.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
public function getForm($data = array(), $loadData = true)
{
$form = $this->loadForm('com_filters.filter', 'filter', array('control' => 'jform', 'load_data' => $loadData));
return $form;
}
protected function getListQuery(){
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//CHANGE THIS QUERY AS YOU NEED...
$query->select('id As value, name As text')
->from('#_k2_tags AS a');
// Filter search // Extra: Search more than one fields and for multiple words
$regex = str_replace(' ', '|', $this->getState('filter.search'));
if (!empty($regex)) {
$regex=' REGEXP '.$db->quote($regex);
$query->where('('.implode($regex.' OR ',$this->searchInFields).$regex.')');
}
// Filter company
$company= $db->escape($this->getState('filter.name'));
if (!empty($company)) {
$query->where('(a.name='.$company.')');
}
// Filter by state (published, trashed, etc.)
$state = $db->escape($this->getState('filter.state'));
if (is_numeric($state)) {
$query->where('a.published = ' . (int) $state);
}
elseif ($state === '') {
$query->where('(a.published = 0 OR a.published = 1)');
}
//echo $db->replacePrefix( (string) $query );//debug
return $query;
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* #since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication('administrator');
// Load the filter state.
$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
//Omit double (white-)spaces and set state
$this->setState('filter.search', preg_replace('/\s+/',' ', $search));
//Filter (dropdown) state
$state = $this->getUserStateFromRequest($this->context.'.filter.published', 'filter_state', '', 'string');
$this->setState('filter.state', $state);
//Filter (dropdown) company
$state = $this->getUserStateFromRequest($this->context.'.filter.name', 'filter_company', '', 'string');
$this->setState('filter.name', $state);
//Takes care of states: list. limit / start / ordering / direction
parent::populateState('a.name', 'asc');
}
}
Inside the "Views/filter/view.html.php"
<?php
defined( '_JEXEC' ) or die;
jimport( 'joomla.application.component.view');
class FiltersViewFilter extends JView
{
protected $item;
protected $form;
protected $state;
protected $sortColumn;
protected $sortDirection;
protected $searchterms;
public function display($tpl = null)
{
$this->item = $this->get('Item');
$this->state = $this->get('State');
$this->form = $this->get('Form');
$this->state= $this->get('State');
//Following variables used more than once
$this->sortColumn = $this->state->get('list.ordering');
$this->sortDirection= $this->state->get('list.direction');
$this->searchterms= $this->state->get('filter.search');
$this->addToolbar();
parent::display($tpl);
}
public function addToolbar()
{
if ($this->item->ID) {
JToolBarHelper::title(JText::_('Filter Title'));
} else {
JToolBarHelper::title(JText::_('Add Filter Title'));
}
JToolBarHelper::apply('filter.apply', 'JTOOLBAR_APPLY');
JToolBarHelper::save('filter.save', 'JTOOLBAR_SAVE');
JToolBarHelper::save2new('filter.save2new', 'JTOOLBAR_SAVE_AND_NEW');
JToolBarHelper::cancel('filter.cancel');
}
}
inside the views/filter/tmpl/default.php
<?php defined( '_JEXEC' ) or die;
//Get companie options
JFormHelper::addFieldPath(JPATH_COMPONENT . '/models/fields');
$companies = JFormHelper::loadFieldType('MyCompany', false);
$companyOptions=$companies->getOptions(); // works only if you set your field getOptions on public!!
//Get companie options
?>
<form action="index.php?option=com_filters&ID=<?php echo $this->item->ID ?>"
method="post" name="adminForm" class="form-validate">
<fieldset id="filter-bar">
<div class="filter-search fltlft">
<input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->searchterms); ?>" title="<?php echo JText::_('Search in Names, etc.'); ?>" />
<button type="submit">
<?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?>
</button>
<button type="button" onclick="document.id('filter_search').value='';this.form.submit();">
<?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?>
</button>
</div>
<div class="filter-select fltrt">
<select name="filter_state" class="inputbox" onchange="this.form.submit()">
<option value="">
<?php echo JText::_('JOPTION_SELECT_PUBLISHED');?>
</option>
<?php echo JHtml::_('select.options', JHtml::_('jgrid.publishedOptions', array('archived'=>false)), 'value', 'text', $this->state->get('filter.published'), true);?>
</select>
<select name="filter_type" class="inputbox" onchange="this.form.submit()">
<option value=""> - Select Company - </option>
<?php echo JHtml::_('select.options', $companyOptions, 'value', 'text', $this->state->get('filter.name'));?>
</select>
</div>
</fieldset>
<div class="width-60 fltlft">
<fieldset class="adminform">
<ul class="adminformlist">
<?php foreach ($this->form->getFieldset() as $field): ?>
<li><?php echo $field->label; ?>
<?php echo $field->input; ?></li>
<?php endforeach ?>
</ul>
</fieldset>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
Please help me in identification of my error I need to sort out issue as soon as possible.
change this Models/fields/fieldname.php to Models/fields/mycompany.php
also change from JFormFieldMyCompany to JFormFieldMycompany
and protected $type = 'MyCompany'; to protected $type = 'mycompany';
When I select ordering I can't really include automatically per-page filter.
How do I make these filters "visible" to each other? What do I need include or read?
That's a small part of my view.py
if order == 'asc':
p = p.order_by('name')
elif order == 'desc':
p = p.order_by('-name')
elif order == 'price_asc':
p = p.order_by('price_netto')
elif order == 'price_desc':
p = p.order_by('-price_netto')
else:
p.order_by('name')
if limit == "12":
per_page = "12"
elif limit == "24":
per_page = "24"
elif limit == "48":
per_page = "48"
else:
from endless_pagination.settings import PER_PAGE
per_page = PER_PAGE
HTML
<select onchange="location = this.options[this.selectedIndex].value">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="?order=desc">Malejąco według nazwy</option>
<option rel="order" value="?order=asc">Rosnąco według nazwy</option>
<option rel="order" value="?order=price_asc">Rosnąco według ceny</option>
<option rel="order" value="?order=price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" href="?limit=12">12</a>, <a rel="limit" href="?limit=24">24</a>, <a rel="limit" href="?limit=48">48</a>
Why not use javascript, jquery. You need a function that will read the query string and override the item you're changing.
<select id="sort-dropdown">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="desc">Malejąco według nazwy</option>
<option rel="order" value="asc">Rosnąco według nazwy</option>
<option rel="order" value="price_asc">Rosnąco według ceny</option>
<option rel="order" value="price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" id="limit-12" href="#">12</a>, <a rel="limit" id="limit-24" href="#">24</a>, <a rel="limit" id="limit-48" href="#">48</a>
Then the javascript will look like:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function redirect(order, limit) {
window.location.url = "?order=" + order + "&limit=" + limit;
}
$("#sort-dropdown").change(function () {
redirect($(this).val(), getParameterByName("limit"));
});
$("#limit-12").change(function () {
redirect(getParameterByName("order"), "12");
});
$("#limit-24").change(function () {
redirect(getParameterByName("order"), "24");
});
$("#limit-48").change(function () {
redirect(getParameterByName("order"), "48");
});
Using the doc, I can set my own helper for the layout surrending my field, but I'd like to personalize also some fields given by play.
The main reason is for Twitter Bootstrap 2, where I need to change (in checkbox.scala.html)
#input(field, args:_*) { (id, name, value, htmlArgs) =>
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
<span>#args.toMap.get('_text)</span>
}
to :
<label class="checkbox">
<input type="checkbox" name="#name" id="#id" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value)) />
#args.toMap.get('_text)
</label>
How can I do that ?
Thanks for your help!
I finally did it like this :
I created a package views.helpers.form, that contains :
bootstrap.scala.html :
#(elements: helper.FieldElements)
<div class="control-group#if(elements.hasErrors) { error}">
<label class="control-label" for="#elements.id">#elements.label(elements.lang)</label>
<div class="controls">
#elements.input
#elements.infos(elements.lang).map { info =>
<span class="help-inline">#info</span>
}
#elements.errors(elements.lang).map { error =>
<span class="help-block">#error</span>
}
</div>
checkbox.scala.html :
#**
* Generate an HTML input checkbox.
*
* Example:
* {{{
* #checkbox(field = myForm("done"))
* }}}
*
* #param field The form field.
* #param args Set of extra HTML attributes ('''id''' and '''label''' are 2 special arguments).
* #param handler The field constructor.
*#
#(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: helper.FieldConstructor, lang: play.api.i18n.Lang)
#boxValue = #{ args.toMap.get('value).getOrElse("true") }
#helper.input(field, args:_*) { (id, name, value, htmlArgs) =>
<label class="checkbox">
<input type="checkbox" id="#id" name="#name" value="#boxValue" #(if(value == Some(boxValue)) "checked" else "") #toHtmlArgs(htmlArgs.filterKeys(_ == 'value))>
#args.toMap.get('_text)
</label>
div>
</div>
And in my template, all I have to do is :
#import helper.{FieldConstructor, inputText, inputPassword} #** Import the original helpers *#
#import helpers.form.checkbox #** Import my helpers *#
#implicitField = #{ FieldConstructor(helpers.form.bootstrap.f) }
And voilà! It works!
It will be simpler to just write your own tag with the code you want and use it instead of the provided helper. It will simplify potential issues related to overwritting platform tags.