I'm writing a custom web part that need to use a couple of rich text box controls. I'm placing the controls onto the web part programatically. When the web part gets a save postback I'm able to capture the data from all the fields except the two rich text box ones. What's the trick to be able to get the value of a rich text box?
The code I"m using to place my form controls is:
private void CreateInputControls()
{
inputPanel.Controls.Clear();
SPList list = SPContext.Current.Site.RootWeb.Lists["MyList"];
SPContentType cType = list.ContentTypes[0];
Table table = new Table();
table.CellPadding = 3;
table.CellSpacing = 0;
SPContext newContext = SPContext.GetContext(System.Web.HttpContext.Current, list.DefaultView.ID, list.ID, list.ParentWeb);
foreach (SPField field in cType.Fields)
{
if (!field.Hidden && field.CanBeDisplayedInEditForm)
{
FieldLabel fieldLabel = new FieldLabel();
fieldLabel.ControlMode = SPControlMode.New;
fieldLabel.ListId = list.ID;
fieldLabel.FieldName = field.InternalName;
fieldLabel.ItemContext = newContext;
fieldLabel.RenderContext = newContext;
fieldLabel.Field.Required = fieldLabel.Field.Required;
FormField formField = new FormField();
formField.ControlMode = SPControlMode.New;
formField.ListId = list.ID;
formField.FieldName = field.InternalName;
formField.ItemContext = newContext;
formField.RenderContext = newContext;
formField.ID = field.InternalName;
formField.EnableViewState = true;
TableRow row = new TableRow();
table.Rows.Add(row);
TableCell cellLabel = new TableCell();
TableCell cellField = new TableCell();
cellLabel.Controls.Add(fieldLabel);
cellField.Controls.Add(formField);
row.Cells.Add(cellLabel);
row.Cells.Add(cellField);
}
}
inputPanel.Controls.Add(table);
}
The code I'm using to save a new item is:
private void UpdateItem(string bannerImageURL, string thumbnailImageURL)
{
SPList list = SPContext.Current.Site.RootWeb.Lists["MyList"];
SPContentType cType = list.ContentTypes[0];
SPItem item = list.AddItem();
foreach (SPField field in cType.Fields)
{
if (!field.Hidden && field.CanBeDisplayedInEditForm)
{
FormField formField = (FormField)inputPanel.FindControl(field.InternalName);
if (formField != null)
{
// Saves data for all fields EXCEPT for rich text box (sharepoint multiline columns).
item[field.Title] = formField.Value;
}
}
}
item.Update();
}
Maybe there's an issue with the field name. Try to use the InternalName.
item[field.InternalName] = formField.Value;
I have been struggling with this and am using a workaround which I thought I'd post as this was quite frustrating.
The problem is that the RTE control is rendered empty and then populated from a hidden control with JavaScript on the client. However this hidden control is accessible server side thus:
switch (formField.Field.Type)
{
case SPFieldType.Note:
var rtf = (RichTextField)formField.Controls[0];
item[field.Title] = rtf.HiddenInput.Value;
break;
default:
item[field.Title] = formField.Value;
break;
}
This may need extending for other field types but you get the idea...
Related
When I use EPPlus to autofit a column that is formatted as a date string, the autofit mechanism is using the unformatted string as measurement for how wide the column should become.
Is it a bug or did I do something wrong?
Code
sheet.Column(2).Style.Numberformat.Format = "yyyy-MM-dd hh:mm";
sheet.Cells.AutoFitColumns();
Result:
widening the second column in excel
Autofit using no formatting, notice that the second column is having the same width as the supposed-to-autofit column in the first picture.
For completion, here is the result when no autofit is used
It could be your font settings either in your code or globally in excel. Try running this test (I am posting this as an answer since I cannot fit it in a comment):
[TestMethod]
public void Auto_Col_Fomat_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]
{
new DataColumn("Col1", typeof (int)), new DataColumn("Col2", typeof (DateTime)), new DataColumn("Col3", typeof (object))
});
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
row[0] = i; row[1] = DateTime.Now.AddDays(i); row[2] = Path.GetRandomFileName();
datatable.Rows.Add(row);
}
//Create a test file
var fi = new FileInfo(#"c:\temp\Auto_Col_Fomat.xlsx");
if (fi.Exists)
fi.Delete();
using (var pck = new ExcelPackage(fi))
{
var workbook = pck.Workbook;
var sheet = workbook.Worksheets.Add("Sheet1");
sheet.Cells.LoadFromDataTable(datatable, true);
sheet.Column(2).Style.Numberformat.Format = "yyyy-MM-dd hh:mm";
sheet.Cells.AutoFitColumns();
pck.Save();
}
}
If this shows the same thing you may have changed your default excel font or zoom which means you may have to set the font in code to Body Font size 11 (at least that was 2013 uses). If it doesnt show post more of your code.
I had the same issue.
Here is my work around:
First call AutoFitColumns, then add some padding to the column that has a special format:
cells[sheet.Dimension.Address].AutoFitColumns();
sheet.Column(2).Width *= 1.25;
I'm successfully creating a Sharepoint List (named "XMLToPDFTestList"), which I can see via Site Actions > View All Site Content, but my attempts to add columns to the list has so far proven fruitless.
Here is how I'm trying to do it:
private void ProvisionallyCreateList()
{
SPWeb mySite = SPContext.Current.Web;
// Check to see if list already exists; if so, exit
if (mySite.Lists.TryGetList(listTitle) != null) return;
SPListCollection lists = mySite.Lists;
SPListTemplateType listTemplateType = new SPListTemplateType();
listTemplateType = SPListTemplateType.GenericList;
string listDescription = "This list is to hold inputted vals";
lists.Add(listTitle, listDescription, listTemplateType);
// Now add a couple of columns
SPList list = lists["XMLToPDFTestList"];
string faveNum = list.Fields.Add("favoriteNumber", SPFieldType.Text, false);
list.Fields[faveNum].Description = "favorite number";
list.Fields[faveNum].Update();
string faveCol = list.Fields.Add("favoriteColor", SPFieldType.Text, false);
list.Fields[faveCol].Description = "favorite color";
list.Fields[faveCol].Update();
}
This is all I see when I click "XMLToPDFTestList":
My "gut feeling" is that this line:
SPList list = lists["XMLToPDFTestList"];
...is not right/not specific enough. Instead of "XMLToPDFTestList" it should be something else/prepend something, or so. But what, exactly?
It was, as is so often the case, "my bad" (YMMV?).
The problem is in my list item creation code which, because I was not assigning anything to the default/inherited "Title" field, made it appear to me (as in the scream shot above) that no item was being added.
Once I fixed the code, by changing this:
private void SaveInputToList()
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists[listTitle];
SPListItem SPListItemFaveNum = list.Items.Add();
SPListItemFaveNum["favoriteNumber"] = "7"; //inputtedNumber; TODO: Once 7 and teal are being saved and retrieved successfully, assign the var vals - will need to declare the controls created in CreateChildControls() globally
SPListItemFaveNum.Update();
SPListItem SPListItemFaveHue = list.Items.Add();
SPListItemFaveHue["favoriteColor"] = "teal";
SPListItemFaveHue.Update();
}
}
}
...to this:
private void SaveInputToList()
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists[listTitle];
SPListItem spli = list.Items.Add();
spli["Title"] = "Write the Title";
spli["favoriteNumber"] = "7";
//SPListItemFaveNum.Update();
//SPListItem SPListItemFaveHue = list.Items.Add();
spli["favoriteColor"] = "teal";
//SPListItemFaveHue.Update();
spli.Update();
}
}
}
...it works fine: an item is added with all three values (Title, favoriteNumber, and favoriteColor).
I was assuming the item wasn't being created because "Title" was blank, and I was calling update on each SPListItem, whereas all I really need to do is call Update once, and on one SPListItem, not multiple.
I'm trying to use a GWT 2.5rc1 custom tablebuilder to render a subtable for each row in my datagrid. I've followed the example in the 2.5 rc1 showcase (url: http://showcase2.jlabanca-testing.appspot.com/#!CwCustomDataGrid).
I'm able to see the newly added sub-rows, but the problem comes when I want to add a clickhandler to a subrow anchor element.. the clickhandler is never invoked, which it seems also quite clear to me since I'm not "registering" the event handler anywhere.
Here the code I'm using now, "relevant part":
private void buildRegRow(Registrazione rowValue,final int absRowIndex, boolean isCommentRow) {
// Calculate the row styles.
SelectionModel<? super Registrazione> selectionModel = cellTable.getSelectionModel();
boolean isSelected =
(selectionModel == null || rowValue == null) ? false : selectionModel
.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Calculate the cell styles.
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
if(isCommentRow)
cellStyles += childCell;
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively,
* you can call dataGrid.setSelectionEnabled(true) to enable mouse
* selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (!isCommentRow) {
renderCell(td, createContext(0), cellTable.getColumn(0), rowValue);
}
td.endTD();
/*
* View children column.
*
* Displays a link to "show children". When clicked, the list of friends is
* displayed below the contact.
*/
td = row.startTD();
td.className(cellStyles);
if(!isCommentRow) {
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if(rowValue.hasComments())
//td.className(CellTableResource.INSTANCE.dataGridStyle().showChildren());
renderCell(td, createContext(1), cellTable.getColumn(1), rowValue);
} else {
td.colSpan(getColumns().size() - 1);
// // Draw sub-table header
TableBuilder subTable = td.startTable();
TableSectionBuilder subTableSection = subTable.startTHead();
TableRowBuilder tr2 = subTableSection.startTR();
TableCellBuilder td2 = tr2.startTH();
td2.text(msgs.date());
tr2.endTH();
td2 = tr2.startTH();
td2.text(msgs.username());
tr2.endTH();
td2 = tr2.startTH();
td2.text(msgs.comment());
tr2.endTH();
td2 = tr2.startTH();
td2.text(msgs.actions());
tr2.endTH();
subTableSection.endTR();
subTable.endTHead();
subTableSection = subTable.startTBody();
for(final EntityComment ec : rowValue.getCommentList()) {
tr2 = subTableSection.startTR();
// Date
td2 = tr2.startTD();
td2.text(DateUtil.getDefaultDateTimeFormat().format(ec.getCreationDate()));
tr2.endTD();
// Username
td2 = tr2.startTD();
td2.text(ec.getUsername());
tr2.endTD();
// Text
td2 = tr2.startTD();
td2.text(ec.getText());
tr2.endTD();
// Actions
td2 = tr2.startTD();
// Remove
Anchor removeAnchor = new Anchor("remove");
removeAnchor.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("clicked");
}
});
td2.html(new SafeHtmlBuilder().appendHtmlConstant(removeAnchor.toString()).toSafeHtml());
tr2.endTD();
subTableSection.endTR();
}
subTable.endTBody();
td.endTable();
}
td.endTD();
for(int i = 2; i <= 6; i++) {
// Recorded, list name, callcenter, msisdn
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if(!isCommentRow) {
renderCell(td, createContext(i), cellTable.getColumn(i), rowValue);
}
td.endTD();
}
row.endTR();
}
The subtable shows up, with an anchor at the correct position, but the clickhandler is never invoked. I do not know how to write the handler code to the page, like I've done to render the anchor.
Thanks for any help.
I have tried custom tablebuilder and created a grid. You can add any element using the proper structure. Make sure you set the Unique Id to each element you create. Then through code access the element through the following code,
Element e = DOM.getElementById( id );
Cast the element to its proper widget i.e, if you are using text input element you can always cast it to textbox. To cast the element there is one more step which you can google out. Then add the clickhandler or whichever handler you want.
First, you have to know that I am developing my project with Struts (J2EE
Here is my problem :
I have 2 dijit.form.Select widgets in my page, and those Select are filled with the same list (returned by a Java class).
When I select an option in my 1st "Select widget", I would like to update my 2nd Select widget, and disable the selected options from my 1st widget (to prevent users to select the same item twice).
I succeed doing this (I'll show you my code later), but my problem is that when I open my 2nd list, even once, it will never be refreshed again. So I can play a long time with my 1st Select, and choose many other options, the only option disabled in my 2nd list is the first I've selected.
Here is my JS Code :
function removeSelectedOption(){
var list1 = dijit.byId("codeModif1");
var list2 = dijit.byId("codeModif2");
var list1SelectedOptionValue = list1.get("value");
if(list1SelectedOptionValue!= null){
list2.reset();
for(var i = 0; i < myListSize; i++){
// If the value of the current option = my selected option from list1
if(liste2.getOptions(i).value == list1SelectedOptionValue){
list2.getOptions(i).disabled = true;
} else {
list2.getOptions(i).disabled = false;
}
}
}
Thanks for your help
Regards
I think you have to reset() the Select after you've updated its options' properties. Something like:
function removeSelectedOption(value)
{
var list2 = dijit.byId("codeModif2"),
prev = list2.get('value');
for(var i = 0; i < myListSize; i++)
{
var opt = myList[i];
opt.disabled = opt.value === value;
list2.updateOption(opt);
}
list2.reset();
// Set selection again, unless it was the newly disabled one.
if(prev !== value) list2.set('value', prev);
};
(I'm assuming you have a myList containing the possible options here, and the accompanying myListSize.)
I have a textArea and a list. When a user double clicks a list item, the label of the selected item should be inserted into the textarea. When a text is selected in the textArea, it should be replaced, otherwise the text just needs to be inserted into the existing text at the caret point.
I've managed to get the text and everything, I just can't manage to insert it at the caret point. Does anyone know how to do this?
It's actually not JavaScript but Adobe Flex 3. Thanks for the help though, it did push me in the right direction. This is the way its done in Flex 3:
var caretStart:int = textArea.selectionBeginIndex;
var caretEnd:int = textArea.selectionEndIndex;
textArea.text = textArea.text.substring(0,caretStart)
+ newText
+ textArea.text.substr(caretEnd);
The accepted answer works great if you do not have existing HTML formatting. In my case, I inserted a new button into the editor that the user could click to put in a key word. I kept losing all HTML formatting until I dug around in the actual class and sided with a TextRange object:
public function keyWord_Click(event:Event) : void
{
var caretStart:int = txtEditor.textArea.selectionBeginIndex;
var caretEnd:int = txtEditor.textArea.selectionEndIndex;
var newText : String = "[[[KEYWORD]]]";
var tf:TextRange = new TextRange(txtEditor,true,caretStart,caretEnd);
tf.text = newText;
}
The nice thing about this approach is, you can also apply conditional formatting to that TextRange object as needed.
You can use txtarea.selectionStart and txtarea.selectionEnd to get Selected text position.
After that, You delete txt and add new selected text.
I don't known much about Javascript, so I wrote it for U.
You can search on google with keywords:
"Javascript Selected Text TextArea"
"Javascript add text at position"
Sample code:
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
caretPos = doGetCaretPosition(myField);
alert(caretPos);
setCaretPosition(myField,caretPos-3);
}