I have a one-to-many relationship table where I am grabbing a list of members by a committee id. When the output is displayed I get the correct amount of members but the corresponding committee position type is being displayed as a list and not the individual position for that committee.
So I came up with the idea of comparing the committee position list with a param that I pass.
When I put in the if tag, nothing is displayed. When I remote the tag, I can see the output of my list and the param that I am pasting into it. I have used == and .equals() but get that same output of nothing.
What an I missing?
Legacy DB Using Oracle 11g, and Grails 2.3.3
Here is an example of my list within a list.
Here is my GSP code
<thead>
<tr class="revheaddark-c">
<!-- display all of the current members information -->
<th width="33%" class="revheaddark-t"><g:message code="trustee.lastName.label" default="Name" /></th>
<th width="33%" class="revheaddark-t"><g:message code="trustee.committees.label" default="Officers of the Board" /></th>
<th width="33%" class="revheaddark-t"><g:message code="trustee.hospital.label" default="Trustee Membership" /></th>
</tr>
</thead>
<g:each in="${trusteeInstanceList}" status="i" var="trusteeInstance">
<tr class="${i % 2 == 0 ? 'even' : 'cellshade'}">
<td><g:link action="contactInfo" params="[contactId:'${trusteeInstance.id}']" id="${trusteeInstance.id}">${fieldValue(bean: trusteeInstance, field: "salutation")}${fieldValue(bean: trusteeInstance, field: "firstName")} ${fieldValue(bean: trusteeInstance, field: "middleName")} ${fieldValue(bean: trusteeInstance, field: "lastName")}</g:link></td>
enter code here
<td><g:each in="${trusteeInstance.membership}">
<g:if test="${it.committees.id == params.committee }">
<%--<tr><td>--%>
${params.committee }, ${it.position }, ${it.committees.id }
<%--</td></tr>--%>
</g:if>
<td><g:each in="${trusteeInstance.board}">
<g:if test="${it.boardName.next() == null}">${it.boardName} </g:if>
<g:else>${it.boardName}, </g:else>
</g:each></td>
</tr>
</g:each>
Here is my controller
def members(){
params.max = Math.min(params.max ? params.int('max'): 15, 100)
def listCommittees = Committees.findAll("from Committees as c where c.hospital.id = '1'")
def indexSearch = Trustee.withCriteria(){
//search by First letter of lastName
if(params.letter){
ilike("lastName", "${params.letter}%")
}
//search by lastName
if(params.lastName){
ilike("lastName", "%${params.lastName}%")
}
//search by firstName
if(params.firstName){
ilike("firstName", "%${params.firstName}%")
}
//search by hospitalName
// if(params.hospital){
// board{
// eq "hospital.id", params.long('hospital')
// }
// }
//search by committeeId
if(params.committee){
//display only members will the board id
membership{
eq "committees.id", params.long('committee')
}
}
//search by Type
if(params.mType){
membership{
eq("memberType", "${params.mType}")
}
}
//search by boardName
if(params.boardId){
//display only members with the boardName
board{
eq("id", params.long('boardId'))
}
}
like("is_Trustee","Y")
order("lastName", "asc")
}
//def memberTrustee = TrusteeMembership.findAll("from TrusteeMembership as tm where tm.committee.id = 'params.committee'")
respond Hospitals.list(params), model:[hospitalsInstanceCount: Hospitals.count(),
trusteeInstanceList : indexSearch,
//memberList: memberTrustee,
sideMenu: Hospitals.list(max:1, order:"desc")]
}
Here are the domains.
class TrusteeMembership implements Serializable{
String position
String memberType
static belongsTo = [trustee:Trustee, committees:Committees]//
static constraints = {
position nullable:true
memberType nullable:true, unique:true
}
static mapping = {
table 'BOT_TRUSTEE_COMMITTEES'
version false
id composite: ['trustee','committees']
trustee column:'TRUSTEE_ID'
committees column: 'COMMITTEE_ID'
position column:'POSITION'
memberType column:'TYPE'
}
package trusteedbtest
class Trustee {
String salutation
String firstName
String middleName
String lastName
static hasMany = [board:Boards, membership:TrusteeMembership]
static constraints = {
salutation nullable: true
firstName nullable: true
middleName nullable: true
lastName nullable: true
}
//map to the existing DB table
static mapping = {
table 'BOT_TRUSTEE'
id column:'TRUSTEE_ID'
salutation column: 'SALUTATION'
firstName column: 'FIRST_NAME'
middleName column: 'MIDDLE_INITIAL'
lastName column: 'LAST_NAME'
}
}
Related
I added Custom Fields to my WooCommerce Single Product Page, with this Code:
// DISPLAY CUSTOM FIELDS IN WOOCOMMERCE SINGLE PRODUCT PAGE
add_action('woocommerce_single_product_summary', 'wpsh_single_posts_custom_meta_fields', 10 );
function wpsh_single_posts_custom_meta_fields(){
$post_id = get_the_ID();
$post = get_post( $post_id );
$month_year = get_post_meta( $post->ID, 'month_year' ); // Date field
$art_size = get_post_meta( $post->ID, 'art_size' ); // Text field
// Date field
if(!empty($month_year)){
echo '<p class="creation-year"><span style="font-weight: bold; color: #4cbb17;">PRODUCT YEAR</span>: ' . $month_year[0] . '</p>';
}
// Text field
if(!empty($art_size)){
echo '<p class="art-dimension"> <span style="font-weight: bold; color: #4cbb17;">ART SIZE</span>: ' . $art_size[0] . '</p>';
}
echo '</p>';
}
--- and it gave me this result: https://snipboard.io/dVOLKv.jpg
But two things are missing from my Code and I don't know how to add them:
1.) Show those Custom Fields according to Category.Meaning that, show:
a.) ART SIZE and PRODUCT YEAR if Category is equal to Artworks.
b.) CRT PRICE and PRODUCT YEAR if Category is Equal to Bags.
c.) CRAFT SIZE, MATERIAL and WEIGHT if Category is Equal to Crafts.
2.) Hide Custom Fields if value is equal to Null. Meaning that, if these fields are not filled in, with a value, they should not appear.
How do I add these extra rules to my Code above?
Or, can anyone help me with a better Code that could be more flexible than the one I already have?
Regards.
You can use get_the_terms() to get the category list then filter out based on category id what to display.
Try out this sample code and replace the category id.
add_action('woocommerce_single_product_summary', 'wpsh_single_posts_custom_meta_fields', 10);
function wpsh_single_posts_custom_meta_fields()
{
$post_id = get_the_ID();
$post = get_post($post_id);
$month_year = get_post_meta($post->ID, 'month_year', true); // Date field
$art_size = get_post_meta($post->ID, 'art_size', true); // Text field
$term_obj_list = get_the_terms( $post->ID, 'product_cat' );
if(is_array($term_obj_list)){
foreach($term_obj_list as $term){
if($term->term_id == 22){ //here 22 is your category id
if ($month_year && !empty($month_year)) {
echo '<p class="creation-year"><span style="font-weight: bold; color: #4cbb17;">PRODUCT YEAR</span>: ' . $month_year . '</p>';
}
if ($art_size && !empty($art_size)) {
echo '<p class="art-dimension"> <span style="font-weight: bold; color: #4cbb17;">ART SIZE</span>: ' . $art_size . '</p>';
}
}
}
}
}
I've created a session list that contains my products, i need to update the quantity of any product by increasing it amount, for that am using an HTML type="number" , i also created a function which take the changed amount and multiplying it value with the current quantity, so lets say the amount of the first product by default is 2 by increasing the number lets say 2 the product amount will become 4 and so on, also the price will be multiplied .
Here are the codes:
<th style="text-align: center;" class="amount-izd">{{value["amount"]}}</th>
<th style="text-align: center; width: 14%;">
<div class="block">
<input type="number" id="myNumber" value="1" min=1 data-amount='{{value["amount"]}}' data-pros='{{value["id"]}}' data-price='
{% if g.currency == "euro" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["euro"]).rsplit(".",1)[0]}}
{% elif g.currency == "dollar" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["dollar"]).rsplit(".",1)[0]}}
{% else %}
{{format_price(value["price"] * config.SITE_CURRENCIES["ruble"]).rsplit(".",1)[0]}}
{% endif %}
'>
<label for="myNumber">qty</label>
</div>
</th>
JQuery codes:
$("input[type='number']").bind('keyup change click', function (e) {
if (! $(this).data("previousValue") ||
$(this).data("previousValue") != $(this).val()
)
{
var currentAmount = $(this).attr('data-amount');
var currentPrice = $(this).attr('data-price');
$(this).closest('tr').find('.amount-izd').text(parseInt(currentAmount) * $(this).val());
$(this).closest('tr').find('.price-izd').text(parseInt(currentPrice) * $(this).val());
$.ajax({
type: 'post',
url: '/standard-{{g.currency}}/profile/'+$(this).attr("data-pros")+'/update/price/' + parseInt(currentPrice) * $(this).val(),
cache: false
}).done(function(data){
if(data.error){
toastr.error(data.error)
}
});
$(this).data("previousValue", $(this).val());
} else {
}
});
And finally views.py :
#profile_route.route("/standard-<set_curr>/profile/cart/", methods=['GET','POST'])
#authorize
def cart_products():
if "cart" not in session:
return render_template("my-cart.html", display_cart = {}, total = 0)
else:
items = session["cart"]
dict_of_products = {}
total_price = 0
for item in items:
product = Goods.query.get(item)
total_price += product.price
if product.id in dict_of_products:
pass
else:
dict_of_products[product.id] = {"qty":1, "name":product.product_name, 'category':product.Category.name, "sizes": product.sizes, "hex_color":product.hex_color, "text_color":product.text_color, "material":product.material, "article":product.article, "price":product.price, "sort": product.sort, "amount": product.amount, 'slug':product.slug, 'public_id' : product.public_id, "id":product.id}
return render_template("my-cart.html", display_cart=dict_of_products, total = total_price)
#profile_route.route("/standard-<set_curr>/profile/<int:id>/update/price/<price>", methods=['GET','POST'])
#login_required
def update_price(id, price):
items = session["cart"]
dict_of_products = {}
for item in items:
product = Goods.query.get(item)
if product.id in dict_of_products:
dict_of_products[id]['price'] = price
return jsonify(success=dict_of_products[id]['price'])
return jsonify(error='No product found.')
If i changed the amount , in console i got a 500 error that says:
return jsonify(success=dict_of_products[id]['price'])
KeyError: 47
Please how to overcome this problem ?
Update:
I was wondering , is it possible to update any value of the dictionary by accessing it directly from JQuery ??
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().
My Ajax request to update the tables is not working. Attached is the screenshot. It simply displays "processing" but nothing happens. The JSON object that is returned (if i visit the URL -{% url 'search_list_json' %} --used in AjaxSource of Js code below) seems to be correct. but still the mainpage is not displaying the JSON content in table.
Here it is:
{"result": "ok",
"iTotalRecords": 1, "aaData": [["<center><font color=\"red\">Mazda=>626:2012-1986</font>\n </center>", "04/07/2014", "10000", "1000", "<center><a href='/search/update/1/'><img src='/static/images/icons/icon_changelink.gif'></a> <a href='/search/delete/1/'><img src='/static/images/icons/icon_deletelink.gif'></a></center>"]],
"sEcho": 0,
"iTotalDisplayRecords": 1}
My views.py
class SearchListJson(BaseDatatableView):
model = Search
columns=['title','created','max_price', 'min_price','actions']
order_columns = ['created', 'max_price']
max_display_length = 500
def render_column(self, row, column):
user = self.request.user
url_edit=static('images/icons/icon_changelink.gif')
url_delete=static('images/icons/icon_deletelink.gif')
#print url_edit, url_delete
if column == 'title':
value = '{0}=>{1}:{2}-{3}'.format(row.vehicle_make,row.vehicle_model,
row.max_year,row.min_year)
edit_url = reverse('search_detail', args=(row.id,))
#print self.get_value_cell_style(edit_url, value,'red')
return self.get_value_cell_style(edit_url, value,'red')
elif column == 'max_price':
#print '%s' %row.max_price
return '%s' %row.max_price
elif column == 'min_price':
#print '%s' %row.min_price
return '%s' %row.min_price
elif column == 'created':
#print row.created.strftime('%m/%d/%Y')
return row.created.strftime('%m/%d/%Y')
elif column == 'actions':
print "in columns actions"
edit_link = """<a href='%s'><img src='%s'></a>""" %(\
reverse('search_update', args=(row.id,)),url_edit)
delete_link = """<a href='%s'><img src='%s'></a>""" %(\
reverse('search_delete', args=(row.id,)),url_delete)
print "edit_link", edit_link
print "delete_link",delete_link
return '<center>%s %s</center>' % (edit_link, delete_link)
else:
return super(SearchListJson, self).render_column(row, column)
def get_value_cell_style(self, url, value, color=None):
style = '''<center>%s</center>''' % (url, value)
if color:
style = '''<center><font color="%s">%s</font>
</center>''' % (url, color, value)
return style
def get_initial_queryset(self):
"""
Filter records to show only entries from the currently logged-in user.
"""
#print "get intial queryset called"
#print Search.objects.filter(user=self.request.user)
return Search.objects.filter(user=self.request.user)
The js-code is below:
$(document).ready(function() {
var oTable = $('#search_table').dataTable( {
"sDom": 'T<"clear">lrtip',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{% url 'search_list_json' %}",
"aaSorting": [ [1,'desc'], [2,'desc'] ],
// Disable sorting for the Actions column.
"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 4 ] } ]
} );
} );
The HTML is:
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<div class="well">
<table id="search_table">
<thead>
<tr>
<th width="10%"><center>Title</center></th>
<th width="15%">Date Created</th>
<th width="15%">Min Price</th>
<th width="15%">Max Price</th>
<th width="10%"></th>
</tr>
</thead>
</table><br>
</div>
</div>
</div>
I have a List called Registration and the following are the columns of my list.
Column : Type
Employee Name : Person or Group
Manager Name : Person or Group
Practice Name : Single line of text
Program Name : Lookup
Status : Choice
Prerequisite : Multiple lines of text
And now i created a web part which will display all these values as a grid view
here is the code which i have done for webpart.cs
protected void Page_Load(object sender, EventArgs e)
{
gridViewManager.DataSource = GetData();
gridViewManager.DataBind();
}
#region Try2
DataTable GetData()
{
SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWeb = oSiteCollection.OpenWeb();
SPList oSPList = oWeb.Lists["Registration"];
SPListItemCollection oSPListItemCollection = oSPList.Items;
DataTable dt = new DataTable();
try
{
dt.Columns.Add("Employee Name", typeof(String));
dt.Columns.Add("Manager Name", typeof(String));
dt.Columns.Add("Practice Name", typeof(String));
dt.Columns.Add("Program Name", typeof(LookupField));
//dt.Columns.Add("Program Name", typeof(String));
dt.Columns.Add("Status", typeof(String));
dt.Columns.Add("Prerequisite", typeof(String));
DataRow dataRow;
foreach (SPListItem oSplistItem in oSPListItemCollection)
{
dataRow = dt.Rows.Add();
dataRow["Employee Name"] = oSplistItem["Employee Name"].ToString();
dataRow["Manager Name"] = oSplistItem["Manager Name"].ToString();
dataRow["Practice Name"] = oSplistItem["Practice Name"].ToString();
dataRow["Program Name"] = oSplistItem["Program Name"].ToString();
dataRow["Status"] = oSplistItem["Status"].ToString();
dataRow["Prerequisite"] = oSplistItem["Prerequisite"].ToString();
}
return dt;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Managers Approval" + ex.Message.ToString());
return dt;
}
#endregion Try2
}
Here is the code for usercontrol code:
<SharePoint:SPGridView runat="server" ID="gridViewManager" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Employee Name" HeaderText="Employee Name" />
<asp:BoundField DataField="Manager Name" HeaderText="ManagerName" />
<asp:BoundField DataField="Practice Name" HeaderText="Practice Name" />
<asp:BoundField DataField="Program Name" HeaderText="Program Name" />
<asp:BoundField DataField="Status" HeaderText="Current Status" />
<asp:BoundField DataField="Prerequisite" HeaderText="Prerequisite" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Take Action" />
<asp:Button ID="Button1" runat="server" Text="View Details" />
</ItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</SharePoint:SPGridView>
Now i am facing a proble with these two lines of code
dt.Columns.Add("Program Name", typeof(LookupField));
dt.Columns.Add("Prerequisite", typeof(String));
if i don't use this then this webpart works perfectly . but i wanted to display these fields too . how can i do this ?
Did you take a look at having the SharePoint API generate the DataTable for you using SPListItemCollection.GetDataTable()?
The problem you're having is with null values. .ToString() will fail if the object is null. I assume that all of the other fields never have any null values (at least with your queries) but the fields that you are having problems with do. You have a few options. You can just check if the value is null and put in an empty string if it's not, for many of the fields that are already strings you can just cast them, rather than .ToString-ing them. You can use Convert.ToString(object) which handles nulls. I could go on with several other options, but I think you can take it from here.