How can I add (and select) a new option on the client side with django-select2? - django-forms

I have a selectable field that uses the django-select2 library. I am currently trying to copy the behaviour of the "add another" functionality present in the admin forms of Django.
I added a "+" icon to my regular form template and opened a popup so that the user can register a new item. This part works, now I wish to select the newly added item automatically once the popup is closed. I cannot seem to add a new option to the selectable, though.
I read the original dismissAddAnotherPopup() code and the select2 docs on that, but appending a new Option(...) to the element does not have the desired effect - in fact it adds as many options as I want, but they appear under the select box instead of in the dropdown menu, as if they were completely different things.
I looked at the html result and it seems the select2 field is not using <option ...> for the options rendered with Django, but rather some deeper nested elements for the options.
What is the correct syntax for adding new options in this situation?

What solved it for me was this answer:
let opt = "<option value=" + myValue + " selected='selected'>" + myValueText + "</option>";
$('#mySelect').html(opt);
$('#mySelect').val(myValue).trigger("change");
It looks a bit ugly to just replace the html, but as I mentioned in the question, appending a new Option(...) to the element did not work.

Not fully client side, but might be helpful: you can use the django-addanother wrapper, like:
widgets = {
'somefield': AddAnotherWidgetWrapper(Select2Widget, reverse_lazy('somefield_add')),
}
This will render a "+" next to the Select2 field; when pressing a popup will be opened which allows to add a new object. Once saved, the Select2Widget will be automatically populated with this newly created object.

Related

Link directly to a notebook page in a view

I have an view that extends the current project view, where we add multiple tabs (notebook pages) to show information from other parts of a project.
One of these pages is an overview page that summarizes what is under the other tabs, and I'd like to link the headlines for each section directly to each displayed page. I've currently solved this by using the index of each tab and calling bootstrap's .tab('show') method on the link within the tab:
$(".overview-link").click(function (e) {
e.preventDefault();
var sel = '.nav-tabs a:eq(' + $(this).data('tab-index') + ')';
$(sel).tab('show');
});
This works since I've attached a data-tab-index="<int>" to each header link in my widget code, but it's brittle - if someone adds a tab later, the current indices will be broken. Earlier I relied on the anchor on each tab, but that broke as well (and would probably break if a new notebook page were inserted as well).
Triggering a web client redirect / form link directly works, but I want to show a specific page in the view:
this.do_action({
type: 'ir.actions.act_window',
res_model: 'my.model.name',
res_id: 'my.object.id',
view_mode: 'form',
view_type: 'form',
views: [[false, 'form']],
target: 'current'
});
Is there any way to link / redirect the web client directly to a specific notebook page tab through the do_action method or similar on FormWidget?
If I understood well you want to select the tab from the JavaScript (jQuery) FormWidget taking into account that the id could change if anybody install another module that adds another tab
Solution 0
You can add a class to the page in the xml form view. You can use the id of the element selected by this class name in order to call the right anchor and select the right tab item. This should happen when the page is completely loaded:
<page class="nb_page_to_select">
$('a[href=#' + $('.nb_page_to_select').attr('id') + ']').click()
NOTE: As you have said the following paragrah I assume that you know where to run this instruction. The solution I suggest is independent of the index.
This works since I've attached a data-tab-index="<int>" to each
header link in my widget code, but it's brittle - if someone adds a
tab later, the current indices will be broken. Earlier I relied on the
anchor on each tab, but that broke as well (and would probably break
if a new notebook page were inserted as well).
Solution 1
When the page is loaded you can get the tab list DOM object like this:
var tablist = $('ul[role="tablist"]')
And then you can click on the specifict tab, selecing by the text inside the anchor. So you don't depend on the tab index:
tablist.find('a:contains("Other Information")').click()
I think if you have two tabs with the same text does not make any sense, so this should be sufficient.
Solution 2
Even if you want to be more specific you can add a class to the notebook to make sure you are in the correct notebook
<notebook class="nt_to_change">
Now you can use one of this expressions in order to select the tab list
var tablist = $('div.nt_to_change ul.nav-tabs[role="tablist"]')
// or
var tablist = $('div.nt_to_change ul[role="tablist"]')
Solution 3
If the contains selector doesn't convince you because it should be equal you can do this as well to compare and filter
tablist.find('a').filter(function() {
return $.trim($(this).text()) === "Other Information";
}).click();
Where "Other Information" is the string of the notebook page
I didn't tried the solution I'm giving to you, but if it doesn't work at least may be it makes you come up with some idea.
There's a parameter for XML elements named autofocus (for buttons and fields is default_focus and takes 1 or 0 as value). If you add autofocus="autofocus" to a page in XML, this page will be the displayed one when you open the view.
So, you can try to add this through JavaScript, when the user clicks on the respective link -which honestly, I don't know how to achieve that by now-. But you can add a distinctive context parameter to each link in XML, for example context="{'page_to_display': 'page x'}". When you click on the link, I hope these context keys will arrive to your JS method.
If not, you can also modify the fields_view_get method (here I wrote how to do that: Odoo - Hide button for specific user) to check if you get the context you've added to your links and add the autofocus parameter to the respective page.
As you said:
This works since I've attached a data-tab-index="" to each header
link in my widget code, but it's brittle - if someone adds a tab
later, the current indices will be broken.
I assume that your app allow multi-user interaction in realtime, so you have to integrate somewhere in your code, an update part function.
This function will trig if something has changed and cleanout the data to rebuilt the index in order to avoid that the current indices will be broken.

jqGrid: Create a custom edit form

I am wanting to customise the edit form in jqGrid so that instead of using the table structured layout provided I would like to use my own custom css structured layout for the form elements. How should I go about modifying the edit form to allow me to use my own custom look?
You can definitely achieve this by jquery ui dialog. However I can not put full code for you but helps you in the steps you have to do.
1 design your custom form whatever CSS and style you want to apply.
Suppose this is youe custome form
<div id="dialog-div">
<input type="text">
</div>
2 on jquery dialog open the dialog on your jqgrid editbutton click
$("#edit").click(function(){
var rowdata = $("#coolGrid").jqGrid('getGridParam','selrow');
if(rowdata){
$("#dialog-div").dialog('open');
var data = $("#coolGrid").jqGrid('getRowData',rowdata);
alert(data);
}
});
by default it will close as-
$("#dialog-div").dialog({
autoOpen: false,
});
Now as you get data in variable you can put in your edit form and of jquery dialog button save it according to your logic.
Hope this helps you.
I would recommend you first of all to read (or at least look thorough) the code of form editing module which implement the part which you want to replace. You will see that it consist from more as 2000 lines of code. If you write "I would like to ..." you should understand the amount of work for implementing what you ask. If you are able to understand the code and if you are able to write your modification of the code even using libraries like jQuery UI then you can decide whether it's worth to invest your time to do the work. The main advantage of using existing solutions is saving of the time. What you get in the way is not perfect, but using existing products you could create your own solutions quickly and with acceptable quality. The way to study existing products which you can use for free seems me more effective as large investments in reinventing the wheel.
http://guriddo.net/?kbe_knowledgebase=using-templates-in-form-editing
Using templates in form editing
As of version 4.8 we support templates in the form editing. This allow to customize the edit form in a way the developer want. To use a template it is needed to set the parameter template in the edit add/or add options of navigator. This can be done in navigator or in the editing method editGridRow :
$("#grid").jqGrid("navGrid",
{add:true, edit:true,...},
{template: "template string for edit",...}
{template: "template string for add",...},
...
);
and in editGridRow method:
$("#grid").jqGrid("editGridRow",
rowid,
{template: "template string",...}
);
To place the CustomerID field in the template the following code string should be inserted in the template string
{CustomerID}
With other words this is the name from colModel put in { }
The usual problem with table layouts is when you have columns with different widths, especially with those very wide.
I solved my problem adding the attr colspan to wide columns in the beforeShowForm event.
for example
"beforeShowForm":function() {
$('#tr_fieldnameasinColModel > td.DataTD').attr('colspan',5);
}
It's not fancy but it worked for me. Perhaps there is a more elegant way to do the same.
I could arrange the fields in several columns without having to make the form extrawide.
When user click on edit button the page navigate to another page, based on Id get the details of a row and you can display the values..
Previous answer of Creating a link in JQGrid solves your problem.

How to open and handle richtext editor in javascript in sitecore 6.5?

I've been working on a custom field, which contains a list.
I have to be able to edit the selected item on the list in a richtext editor. (this is the only missing part).
I've read the topic on opening from c# code Opening Rich Text Editor in custom field of Sitecore Content Editor .
This works nice for the "add" button, since i have to open the RTE empty(with default text...), but not for the Edit button.
My aproaches are:
Somehow in the Edit button's message field list:edit(id=$Target) pass the selected index (like list:edit(id=$Target,index=$SelectedIndex), but i don't know how to populate $SelectedIndex
Somehow in the overridden HandleMessage method get the list's selected index. I'm able to get the selected value Sitecore.Context.ClientPage.ClientRequest.Form[ID of list], but thats alone not much of a help, since i won't be able to decide which one to edit if two listitem equals.
Do the richtext editor opening and handling fully in javascript. As i saw at some script in content editor, i tried to do that, but i can't understand it clearly:
richtext editor url:
var page = "/sitecore/shell/Controls/Rich Text Editor/EditorPage.aspx";
some params :
var params = "?da=core&id&ed=" + id + "&vs=1&la=en&fld=" + id + "&so&di=0&hdl=H14074466&us=sitecore%5cadmin&mo";
and the part where i'm not sure:
var result = scForm.browser.showModalDialog(page + params, new Array(window), "dialogHeight:650px; dialogWidth:900px;");
This way the RTE opens as expected (i guess i could get the selected index from javascript and pass it as a parameter later). However when i click ok, i get exception from EditorPage.js saveRichText function: Cannot read property 'ownerDocument' of null. Am i missing some parameter?
Either of the three aproaches is fine for me(also i'm open for new better ones) as soon as i'm able to do it.
Thanks in advance!
Tamas
I was able to enter some javascript into the message:
list:Edit(id=$Target,index='+document.getElementById(ID of the select using $Target ).selectedIndex+')
this way i got the index in HandleMessage.
I'm waiting for better solutions now.

How to call the same function that the ToolBar editbutton does

So I have created a context box upon right click that has Add/Edit/Delete Rows. I also have a bunch of code launched before the Dialog is shown. My problem is that when I use the context menu it doesn't go through some of the code. I have tried to call on the functions directly but it doesn't format correctly.
I am mainly concerned with the edit button, here is the code I am using to bring up the edit Dialog
function editRow() {
var grid = jQuery("#<%= Jqgrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
if (rowKey) {
// I have tried calling functions here and it still doesn't work
grid.editGridRow(rowKey, grid.editDialogOptions);
}
else {
alert("No rows are selected");
}
}
So if I use this to display the editform it isn't formatted correctly nor does it go through the functions all correctly.
I am using the ASP Webforms version of Jqgrid so I call the function by doing this
<cc1:JQGrid1 ID="Jqgrid1
//other attributes
ClientSideEvents-BeforeEditDialogShown="ChangeMonitor"
//Rest of code />
So this works just fine, and I'm trying to get the Edit button on the context menu to display correctly.
My thought was to use Jquery to trigger a click on the actual Edit button once someone used the context menu. I couldn't find an ID that would work however.
Is there an easy way to connect my context menu Edit button, with the actual Edit button in the toolbar?
Well I found a solution to my problem.
The id field of the button was edit_ct100_cpMainContent_Jqgrid1_top so I just triggered a click with this code.
$("td[id^=edit][id$=top]").trigger("click")
For some reason when I used the _ct100_cpMainContent_Jqgrid1 it wasn't working, but now it does. Hope this helps someone.

HTML.SelectListFor selectedValue never gets set

I have the following partial view which renders a drop down list:
#model MartinDog.Core.Models.Section
#{
#Html.DropDownListFor(x=>x.Name
, new SelectList(Model.Dock.DockTemplate.Columns,
"Id", "FriendlyName",
Model.DockTemplateColumn.Id.ToString())
, new { #id = "ddlb_dockTemplateColumns" +
Model.Id.ToString()})
}
I render it on my page like so:
#{Html.RenderPartial("_Admin_Page_DockTemplateColumnDropDown", Model);}
The partial view is rendered once for every Section object. A Section object one I've created and is editable in a jquery dialog box (change the name, display order, dock template column, etc.)
On the test page I am using, this Section dialog box is rendered four times (as there are four of them in my parent object).
The problem:
*The SelectedValue in the SelectList for the drop down never gets set* - that is to say, the correct item in the drop down list is never selected when the dialog is displayed and I can't quite work out why.
I thought it might be because the drop down is rendered four times, so I tried rendering it for just one of the 'Sections' but still the same problem.
Anyone know what I can do?
***edit
Not sure if I'm doing it in a sucky way. I had thought of building the dialog just once with jquery and json but I'd prefer to do it this way as it just feels cleaner.
I do this:
In controller action (Edit for example):
ViewData["ProvinceID"] = new SelectList(dc.Provinces.OrderBy(p => p.NameAr), "ID", "NameAr", factory.ProvinceID);
and Markup:
<%: Html.DropDownList("ProvinceID") %>
See? so it is a list of factories and it has a Province field and what I want you to notice is the 4th parameter in the SelectList constructor, I passed factory.ProvinceID so the DropDownList knows which option to be set on. Otherwise the DropDownList will show the default value (the first one).
P.S: It is your job to change to Razor syntax; I don't use it.
Hope that helps.
Doh... fixed - totally my own fault.
I had set up my html.dropdownlistfor like so
#Html.DropDownListFor(x=>x.Name,
When it should've been like so:
#Html.DropDownListFor(x=>x.DockTemplateColumn.Id,
Setting the first argument to x=>x.DockTemplateColumn.Id (which uniquely identifies the items in my list) instead of x.Name fixed the issue straight away.
Just thought I'd post it here in case someone else makes the same mistake I did.
edit
Found the answer here:
C# mvc 3 using selectlist with selected value in view

Resources