Get changed unsaved property value of a node in content tab, after clicking save button and before saving the changes. Umbraco - umbraco

Update:
I want to get a node's property value that has been changed after clicking save button and before saving the changes programmatically, on content tab in BackOffice.
The node could contain many properties. When the save button is clicked, I want to first get the new changed value for the node's properties. I think Umbraco should have APIs to get those in server side.
Any idea would be very much appreciated.

You want to wire into the Document.BeforeSave method in an IApplicationEventHandler class. Like so (assuming you're changing bodyText from "apple" to "orange"):
using umbraco.cms.businesslogic.web;
using Umbraco.Core;
using Umbraco.Web;
namespace ClassLibrary1
{
public class Class1 : IApplicationEventHandler
{
public void OnApplicationStarted(UmbracoApplication httpApplication, ApplicationContext applicationContext)
{
Document.BeforeSave += new Document.SaveEventHandler(Document_BeforeSave);
Document.AfterSave += new Document.SaveEventHandler(Document_AfterSave);
}
void Document_BeforeSave(Document sender, umbraco.cms.businesslogic.SaveEventArgs e)
{
// your code goes here!
sender.getProperty("bodyText").Value // returns apple
}
void Document_AfterSave(Document sender, umbraco.cms.businesslogic.SaveEventArgs e)
{
// your code goes here!
sender.getProperty("bodyText").Value // returns orange
}
public void OnApplicationStarting(UmbracoApplication httpApplication, ApplicationContext applicationContext)
{
// unused
}
public void OnApplicationInitialized(UmbracoApplication httpApplication, ApplicationContext applicationContext)
{
// unused
}
}
}
I tested this in Umbraco 4.11
Cheers
Jonathan

What you could do is use a jquery event handler, that is targeted at the field in the umbraco admin you want to check for changes. This example will work by finding the label of the umbraco field you want to monitor and then adding a jquery event handler that will fire when the field that is the sibling to the label is changed - this example will work for any changes to the 'Name' field that is on every node's 'properties' tab. Different field types will hold the value differently, so $(this).val() should usually work for most - but not all field types.
Drop this into the end of \umbraco\editcontent.aspx
<script type="text/javascript">
$(document).ready(function () {
$("div.propertyItemheader:contains('Name') + div.propertyItemContent").keyup(function () {
alert("field changed");
});
});
</script>

Related

vaadin 10 - Push - Label won't update

MainView include InformationCOmponent:
#Push
#Route
public class MainView extends VerticalLayout {
InformationComponent infoComponent;
public MainView(#Autowired StudentRepository studentRepo, #Autowired Job jobImportCsv, #Autowired JobLauncher jobLauncher, #Value("${file.local-tmp-file}") String inputFile) {
[...] // some stuffs
infoComponent = new InformationComponent(studentRepo);
add(infoComponent);
}
//update when job process is over
private void uploadFileSuccceed() {
infoComponent.update(myUploadComponent.getFile());
}
InformationComponent:
public class InformationComponent extends HorizontalLayout {
StudentRepository studentRepo;
Label nbLineInFile = new Label();
VerticalLayout componentLeft = new VerticalLayout();;
VerticalLayout componentRight = new VerticalLayout();;
public InformationComponent(StudentRepository studentRepo) {
[...] // some init and style stuff
addLine("Nombre de lignes dans le fichier", nbLineInFile);
}
private void addLine(String label, Label value) {
componentLeft.add(new Label(label));
componentRight.add(value);
}
public void update(File file) {
try {
long nbLines = Files.lines(file.toPath(), Charset.defaultCharset()).count();
System.out.println("UPDATED! " +nbLines); // value is display in console ok!
UI.getCurrent().access(() -> nbLineInFile.setText(nbLines)); // UI is not updated!!
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
When I call InformationComponent from MainView the Label is not update in the browser.
UI.getCurrent().access(() -> nbLineInFile.setText(nbLines))
also try wwith #Push(PushMode.MANUAL) and ui.push(); but doesn't work either...
Complete source code is here: https://github.com/Tyvain/ProcessUploadedFile-Vaadin_SpringBatch/tree/push-not-working
I suspect the problem here is that uploadFileSuccceed() is run from a background thread, in which case UI.getCurrent() will return null. This would cause a NullPointerException that either kills the background thread or alternatively the exception is caught and silently ignored by the caller. Another alternative is that uploadFileSuccceed() happens through a different browser window and thus also a different UI instance, which means that the changes would be pushed in the context of the wrong UI.
For exactly these reasons, UI.getCurrent().access(...) is generally an anti pattern, even though it's unfortunately quite widely used in old examples.
You can check whether this is the cause of your problem by logging the value of UI.getCurrent() in the beginning of the update method, and comparing that to the value of UI.getCurrent() e.g. in the constructor of InformationComponent.
To properly fix the problem, you should pass the correct UI instance through the entire chain of events originating from whatever triggers the background processing to start. You should also note that it might be tempting to use the getUI() method that is available in any Component subclass, but that method is not thread safe and should thus be avoided in background threads.
As a final notice, I would recommend using the Span or Text component instead of Label in cases like this. In Vaadin 10, the Label component has been changed to use the <label> HTML element, which means that it's mainly intended to be used as the label of an input component.
Based on information provided by Leif you should do something like the following example.
At runtime, when this HorizontalLayout subclass object is attached to a parent UI object, its onAttach method is called. At that point we can remember the UI by storing its reference is a member variable named ui. Actually, an Optional<UI> is returned rather than a UI object, so we need to test for null, though it should never be null at point of onAttach.
public class InformationComponent extends HorizontalLayout {
UI ui;
StudentRepository studentRepo;
Label nbLineInFile = new Label();
VerticalLayout componentLeft = new VerticalLayout();;
VerticalLayout componentRight = new VerticalLayout();;
public InformationComponent(StudentRepository studentRepo) {
[...] // some init and style stuff
addLine("Nombre de lignes dans le fichier", nbLineInFile);
}
private void addLine(String label, Label value) {
componentLeft.add(new Label(label));
componentRight.add(value);
}
public void update(File file) {
try {
long nbLines = Files.lines(file.toPath(), Charset.defaultCharset()).count();
System.out.println("UPDATED! " +nbLines); // value is display in console ok!
this.ui.access(() -> nbLineInFile.setText(nbLines)); // UI is not updated!!
} catch (IOException e) {
throw new RuntimeException(e);
} catch (UIDetachedException e) {
// Do here what is needed to do if UI is no longer attached, user has closed the browser
}
#Override // Called when this component (this `HorizontalLayout`) is attached to a `UI` object.
public void onAttach() {
ui = this.getUI().orElseThrow( () -> new IllegalStateException("No UI found, which should be impossible at point of `onAttach` being called.") );
}

unable to Validate Custom components in SmartGWT

I am unable to get my custom compoenent to be validated in the dynamic form. I tried many versions but it is not working as expected. For e.g. either the label is not showing in BOLD to indicate the field is mandatory and it aloows to save the form without entering anything in the field. Only when the user enters something in the field and deletes it, then the red icon is displayed to the user that the field is mandatory.I dont know what i am missing. please help. code is below
telnumber = new CustomTelephoneTextItem();
telnumber.setName("tel");
telnumber.setTitle("Tel");
telnumber.setTitle(nerpweb.clientFactory.getMessages().tel());
Below is my Custom TextItem which i am using in the above class
public class CustomTelephoneTextItem extends CanvasItem
{
textField_value = new CustomIntegerItem();
textField_value.setShowTitle(false);
textField_value.setWidth(100);
textField_value.setRequired(true);
form.setItems(textField_value, textField_code);
form.validate();
setWrapTitle(false);
this.setCanvas(form);
First, if you want to item title showin bold, you must call item's setRequired(true).
in your code is telnumber.setRequired(true);
Second, if you want to validate item on form.validate(), you must override validate() function in your item and write validation code in this function.
in your code is call form.validate() in CustomTelephoneTextItem validate() function
Here is the code to be implemented to validate custom component
This code will go in your Custom component which you will implement
#Override
public Object getValue()
{
if (validate() && textField_value.getValue() != null)
return textField_value.getValue();
return null;
}
#Override
public void setRequired(Boolean required) {
super.setRequired(true);
}
#Override
public Boolean validate() {
return super.validate();
}
#Override
public void setValidators(Validator... validators) {
textField_value.setValidators(validators);
}
Then in the class where you will create the custom component you will call the setRequired() method,like so
telnumber.setRequired(true);

Umbraco : Refresh dropdown datatype items automatically on parent node publish

I have a dropdown datatype which has all the child nodes of a parent node. I can create this list manually. But the problem is, the child nodes will be created/deleted on the fly, which means I need to edit/remove the dropdown values manually each time.
Is there a way to add/remove items from dropdown list whenever my parent node is published??
Please let me know.
Assuming you are using the latest version of Umbraco, you can register an event on document publish which will fire for every single event publish. In the event handler code you can then selectively fire for only the node you are concerned with.
http://our.umbraco.org/documentation/Reference/Events/application-startup
Something like the following should do it
using Umbraco.Core;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
namespace Umbraco.Extensions.EventHandlers
{
public class RegisterEvents : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
Document.BeforePublish += Document_BeforePublish;
}
private void Document_BeforePublish(Document sender, PublishEventArgs e)
{
//Do what you need to do. In this case logging to the Umbraco log
Log.Add(LogTypes.Debug, sender.Id, "the document " + sender.Text + " is about to be published");
if (sender.Id == YourIDAsAConstantOrConfigurableValue)
{
//Do your list building here
}
//cancel the publishing if you want.
e.Cancel = true;
}
}
}
You can trigger selectively for your specific parent node based on either ID or based on document type alias
Hope that helps

Putting parameters in velocity context in Jira 4.4

I'm developing a plugin to display additional information related to a project.
So I'm developing a Project Tab Panel module but my page does not display the paramenters I put in the velocity context.
Here is the a part of plugin xml:
<project-tabpanel key="stats-tab-panel" name="Stats Tab Panel" i18n-name-key="stats-tab-panel.name" class="it.pride.jira.plugins.StatsTabPanel">
<description key="stats-tab-panel.description">The Stats Tab Panel Plugin</description>
<label key="stats-tab-panel.label"></label>
<order>10</order>
<resource type="velocity" name="view" location="templates/tabpanels/stats-tab-panel.vm"/>
Here instead the useful part of my class:
public class StatsTabPanel extends GenericProjectTabPanel {
public StatsTabPanel(JiraAuthenticationContext jiraAuthenticationContext,
FieldVisibilityManager fieldVisibilityManager) {
super(jiraAuthenticationContext, fieldVisibilityManager);
// TODO Auto-generated constructor stub
}
public String testvalue="112002";
#Override
public boolean showPanel(BrowseContext context){
return true;
}
#Override
public Map<String, Object> createVelocityParams (BrowseContext context) {
Map<String, Object> contextMap = createVelocityParams(context);
contextMap.put("testvalue", testvalue);
return contextMap;
}
}
So, as in this case, when i write `$testvalue in my template the number doesn't show up.
What am I doing wrong?
The problem is that the getHtml method that is used to return the HTML for the tab has a Map that is the Velocity context but only contains the params in the BrowseContext object. The way to fix this is to override createVelocityParams in your class, e.g.
protected Map createVelocityParams(final BrowseContext ctx) {
Map params = super.createVelocityParams(ctx);
params.put("myparam", "some value for it");
return params;
}
The problem is that method is protected so I ended up also overriding getHtml which calls createVelocityParams in a parent class.
Some Project tabs extend GenericProjectTabPanel but some such as SummaryProjectTabPanel.java seem to use UI Fragments. I suspect that Fragments is what things are moving towards.

Asynchronous postback when click on a treenode in master page

I am using ASP.NET MVC to build my application. I have a treeview (with treenodes having hrefs) in the masterpage and when click on the treenode corresponding page get loaded in the content view. I need this to happen asynchronously. Also I need to persist the state of the tree(i.e. expand / collapse of each nodes) after each node click.
with regards to activating a click event on an element you need to either know its id or class name.
so to activatea click event on an element with a class of "treeNode" use;
$(".treeNode").click(function(){
//your code here.
});
to do a postback to a controller actionresult, use;
$.post('/Controller/Action', { param1: paramValue }, function (retHTML) {
//code here on success
});
retHTML above is what is returned from the ajax post.
in your controller do this;
public void jQuery_DeleteAttachment(string param1)
{
//your code here
}
I would, from my controller, i would return a partialview.
public void jQuery_DeleteAttachment(string param1)
{
return PartialView("viewname", model);
}
In the jQuery success code I would replace, append, whatever, the retHTML to where I wanted it.

Resources