Retrieve the values from a list to Gridview in SharePoint Webpart? - list

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.

Related

cfgrid not working after upgrade from Coldfusion 11 to Coldfusion 2018

After upgrading from CF11 to CF2018, Update 3, none of my editable cfgrids are working. When I make an edit and then submit the form, the columns seem to get jumbled. I created the simplest cfgrid I could (below) but am still getting the same behavior.
<cfif isDefined("form.submitname")>
<cfdump var="#form#">
<cfelse>
<cfform action="test.cfm" method="post" name="testform" id="testformId">
<cfinput type="Submit" name="submitname" id="submitid">
<cfgrid name="TestGrid" format="html" selectmode="edit">
<cfgridcolumn name="A">
<cfgridcolumn name="B">
<cfgridrow data="john,doe">
<cfgridrow data="steve,anon">
</cfgrid>
</cfform>
</cfif>
The grid displays correctly, but what I change 'john' to 'peter' and submit, I get the following dump:
enter image description here
As you can see, it thinks 'peter' was entered as both the first and last name, and it also thinks that 'peter' was the original first name.
When I modify any of the fields in the second column, I get the following javascript error in the console:
TypeError: _dd.values[_de] is undefined.
The error is thrown by cfgrid.js
If I submit only a change in the second column, the dump is completely empty.
It seems like the cfgrid is mixing up columns or something.
Your thoughts?
Ultimately the solution here is to move away from ColdFusion's implementation of <cfgrid> and roll your own grid-UI or.... wait for a patch from Adobe.
This is definitely a bug in ColdFusion, the error you are seeing is specifically a bug in the function ColdFusion.Grid.Actions.afterEdit()
I spent a little bit of time fiddling around with the JS generated with <cfgrid> and found that they index into the columns incorrectly
You can override ColdFusion's implementation of ColdFusion.Grid.Actions.afterEdit() with your own to create a possible workaround ( I ran on Solaris 11.4 - Apache - ColdFusion 2018 : Update 3 )
<Body>
<cfif isDefined("form.submitname")>
<cfdump var="#form#">
<cfelse>
<cfform action="test.cfm" method="post" name="testform" id="testformId">
<cfinput type="Submit" name="submitname" id="submitid">
<cfgrid name="TestGrid" format="html" selectmode="edit">
<cfgridcolumn name="A">
<cfgridcolumn name="B">
<cfgridrow data="john,doe">
<cfgridrow data="steve,anon">
</cfgrid>
</cfform>
</cfif>
<script>
ColdFusion.Grid.Actions.afterEdit = function(_d8, _d9, _da) {
var _db = _d9.value;
if (_db == this.editOldValue) {
return;
}
if (this.insertInProgress == false && this.onChangeFunction) {
this.onChangeHandler("U", this.selectedRow, _d9);
} else {
if (!this.dynamic) {
rowidx = _d9.rowIdx;
if (!rowidx && rowidx != 0) {
rowidx = _d9.row;
}
var _dc = ColdFusion.Grid.computeActualRow_editField(this.editFieldState, _d9.record.data.CFGRIDROWINDEX);
var _dd = this.editFieldState[_dc - 1];
var _de = _d9.colIdx;
if (!_de && _de != 0) {
_de = _d9.column;
}
_de = _de + 1;
if (_dd) {
if (this.multiRowSelection === true && this.insertInProgress == true) {
_de = _de - 1;
}
//-------------------------------------------------------------------
//Subtracted 1 from column index to correctly index array
//-------------------------------------------------------------------
_dd.values[_de -1][1] = _db;
} else {
var _df = this.grid.getStore().getById(_d9.record.data.CFGRIDROWINDEX);
_dd = ColdFusion.Grid.Actions.initEditState(this, "U", _df, _dc);
var _e0 = this.editOldValue + "";
if (_d9.column.type == "date") {
if (_e0 && typeof _e0 == "string") {
_e0 = new Date(_e0);
}
var _e1 = "F, j Y H:i:s";
if (_d9.column && _d9.column.format) {
_e1 = _d9.column.format;
}
_dd.values[_de][1] = Ext.Date.format(_db, _e1);
_dd.values[_de][0] = _e0 ? Ext.Date.format(_e0, _e1) : _e0;
} else {
//-------------------------------------------------------------------
//Subtracted 1 from column index to correctly index array
//-------------------------------------------------------------------
_dd.values[_de -1][0] = _e0;
_dd.values[_de -1][1] = _db;
}
}
ColdFusion.Grid.Actions.computeEditField(this);
}
}
this.editOldValue = null;
this.fireSelectionChangeEvent();
}
;
</script>
</BODY>
There are definitely a ton of other bugs plaguing this tag ... and its definitely worth noting that Lucee ( opensource ColdFusion engine) DOES NOT support this tag

Can i user pattern in #Html.Editor In MVC?

we can use pattern(regex) for inputs control
like that :
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
My question is can i user Pattern in #html.Editor ?
I tried to use this way:
#Html.Editor("country_code", null, new { htmlAttributes = new { #class = "form-control" , required = "required" , pattern="[A-Za-z]{3}"} })
But pattern="[A-Za-z]{3}" does not recognize

Grails comparing a list within a list in a gsp

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'
}
}

How to get values from select form to a python file with Flask

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().

How to get values from Extjs template

I am using a Rowexpander inside a ExtjsGrid. RowExpander's template has text area which is used to get values from the user.
Below is my code.How can I read the value
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.Template(
'<p><b></b><div class="abc"> <input type="textarea" id = "hans_" name ="hans_" value = "{comment}"</ div></p><p></p><p>{promptMsg}</p>'
),
listeners:
{
expand: function(ex, record, body, rowIndex){
},
collapse: function(ex, record, body, rowIndex){
}
}
});
Solved ...
Below is the solution
Give a dynamic names to textarea of template
'<p><b></b><div> <textarea rows="2" cols="100" id = "{qnNum}" name ="{qnNum}" > {comment} </textarea><b></b></ div></p><p></p>'
Read the values
document.getElementById(record.data.qnNum);