How to get a DateTime input in a Play! CRUD form? - datetime

By default a java.util.Date field is represented in a CRUD form as a simple "DATE" input.
public class DatedModel extends Model {
public Date creationDate;
in the CRUD admin I see:
creationDate [TEXTINPUT]
yyyy-MM-dd format.
Is there any way to have a DateTime input instead, on selected fields only (not all of them modifying the application.conf date.format)?
Is there a way to affect which "widget" is used for a given field in the 'automated' CRUD admin?

Something like this in your application.conf:
module.crud=${play.path}/modules/crud
date.format=yyyy-MM-dd hh:mm:ss
Then in the model:
package models;
import java.util.*;
import play.data.binding.As;
import play.db.jpa.*;
import play.data.validation.*;
import play.templates.*;
import play.mvc.Scope.*;
import javax.persistence.*;
import play.Logger;
import play.templates.JavaExtensions;
#Entity
public class Product extends Model {
#As(lang={"*"}, value={"yyyy-MM-dd hh:mm:ss"})
public Date creationDate;
}
Your controller:
package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Products extends CRUD {
}
Documentation
Working demo: https://github.com/saxxi/play-framework-test

I finally found in the documentation my answer:
You can indeed customize each field; a more extensive example can be found on the lunatech blog using jquery datatables which also shows how to modify pagination.
#{crud.table fields:['name', 'company']}
#{crud.custom 'company'}
<a href="#{Companies.show(object.company.id)}">
${object.company.name}
</a>
#{/crud.custom}
#{/crud.table}
PS.
#AditSaxena hint was good and indeed a simple solution; but not what I wanted because it's not acceptable that the 'hint' is not correct! Clearly confusing for a user!
So for a datetime input (the specific question) we can combine the annotation (described in the doc)
#As(lang={"*"}, value={"yyyy-MM-dd hh:mm:ss"})
with a custom hint, eg.
#{crud.custom 'mydate'}
<span class="crudHelp">
Date format: etcetc.
</span>
...
#{/crud.custom}
I'll also point out that you can write your own validator
Other related useful questions:
Is it possible in playframework to override the default save action in the CRUD controller and redirect to list after
Play! framework CRUD module: adding default values and change date format?
Play framework CRUD file upload about custom file upload fields

Related

How to use LazyPaginator together with RequestConfig and Table classes?

I want to visualize a big, indexed table - big enough for count(*) to be too slow for my use case. Here's my views.py code:
import django_tables2
from projectname.models import Growth
def dashboard(request):
class StatisticsTable(django_tables2.Table):
class Meta:
model = Growth
table = StatisticsTable(Growth.objects.all())
django_tables2.RequestConfig(
request
).configure(table)
return render(request, "plain_table.html", {'table': table,
'title': 'Growth dashboard',
'search': None})
I was looking for examples on how to use django_tables2.paginators.LazyPaginator here and so far only found that I should pass it as a paginate= in django_tables2.RequestConfig, but I still get a regular paginator if I pass a reference to the class there. What's the proper use of this class in this context?
RequestConfig(paginate={"paginator_class": LazyPaginator}).configure(table)

Making a minecraft mod in java. Creating and registering an instance

I'm trying to make an uranium ingot that gives players that hold it in their inventory a wither effect. I got some tips from the minecraft forums, they told me to do to make my item give me the wither effect.
Re: 1.10.2 Item has wither « Reply #2 on: Today at 02:29:58 am » QuoteThank You Create a class that extends Item and overrides
Item#onUpdate.
In your override, check if the entityIn argument is an instance of EntityLivingBase. If it is, cast it to EntityLivingBase and call EntityLivingBase#isPotionActive to check if it has the MobEffects.WITHER effect active. If it doesn't, create a PotionEffect and call EntityLivingBase#addPotionEffect to add it.
My Question
Create and register an instance of this class instead of Item.
The last line is what im confused on.
Here is the class i made that he told me to do. Also please inform me if i didnt do something else right in this class
package item;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.MobEffects;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
public class UraniumIngotEffect extends Item{
#Override
public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
if(entityIn instanceof EntityLivingBase){
Object EntityLivingBase = ((EntityLivingBase) entityIn).isPotionActive(MobEffects.WITHER);
}else{
Object PotionEffect = new PotionEffect(MobEffects.WITHER);
}
super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected);
}
}
You need to make the item object in your mod hold the onUpdate method.
This means:
have a class that extends Item(your uranium ingot)
Register the item in the item loader
Item myurnanium = new UraniumIngot();
GameRegistry.register(myuranium);
and of course make the proper json files so the item will render properly.
I suggest you read:
http://bedrockminer.jimdo.com/modding-tutorials/basic-modding-1-8/first-item/

How to create dynamic dropdown from folder names in alfresco?

I have a task in which I have to present a drop down with client names while uploading a document of a particular type. The names of the client are tied to folders in a given site.
For e.g. Let say I have a site XYZ in alfresco and I have 10 folder with names Client 1 to Client 10 all on the same level, now while uploading the doc the client name field should be populated by the names of the folder present in the site.
I have created a custom java class that will fetch the folder names and place a constraint on the client name in the custom-model.xml file. I was able to show the hard-coded data as a dropdown but now I want the data to be fetched dynamically.
As I am new to alfresco I don't have enough idea how to get it done. I am trying to use Alfresco public java api and CMIS but not able to get anywhere.
Any help on this will be extremely helpful.
Here is the code.
model.xml
<!-- For client name -->
<constraint name="ev:clientNames" type="com.eisenvault.repo.dictionary.constraint.ClientNameConstraint">
<parameter name="allowedValues">
<list>
<value></value>
<!-- Will be empty -->
</list>
</parameter>
</constraint>
ClientNameConstraint.java
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ClientNameConstraint extends ListOfValuesConstraint implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
Log log = LogFactory.getLog(ClientNameConstraint.class);
private List<String> allowedValues;
protected boolean caseSensitive;
protected boolean sorted;
public ClientNameConstraint(){
caseSensitive = true;
sorted = false;
allowedValues = Collections.emptyList();
}
#Override
public List<String> getAllowedValues() {
allowedValues = Arrays.asList("Client1", "Client2", "Client3", "Client4", "Client5", "Client6");
Collections.sort(allowedValues);
super.setAllowedValues(allowedValues);
return allowedValues;
}
#Override
public void initialize() {
System.out.println("Initialized called in ClientNameConstraint....................................");
super.initialize();
checkPropertyNotNull(ALLOWED_VALUES_PARAM, allowedValues);
}
}
I would avoid using a constraint in this case. Others may disagree, but a dynamic constraint could be more trouble than it is worth. This is because you can get integrity exceptions which could be messy to deal with if your client list ever gets out of sync. Imagine if you create some documents with one version of the list, but then delete a folder. Now any operation on those documents will throw an integrity exception.
I personally would create a webscript (it could be in Javascript if you like) which reads out the folders and returns them as JSON. Then, I would create a custom share component and configure my form to use this component. The component would build the list of vales from your webscript but would not depend on a constraint.
It's "more" development than your original idea, but it's more flexible and you won't have any issues with upgrades, etc, if your client folders get out of sync with the content.

Determine runmode in Adobe CQ

How do I programmatically know which run-mode the instance is running? I created a custom tag that provides the config depending on the instance run-mode, but I can not determine the current run-mode.
I found a method that returns a list of run-mods instance:
SlingSettings settings = ...get from BundleContext...
Set<String> currentRunModes = settings.getRunModes();
But I can not get the objects SlingSettings or BundleContext. How can I get these objects or perhaps there is another way to get the current run-mode?
SlingSetttings is the right way - If it's from Java the simplest way to get it is with an SCR #Reference annotation in a class that's an SCR #Component, saves you from having to go through BundleContext.
If it's from a Sling script, you can use sling.getService(....) to get the SlingSettings.
Note that the cases where you need to read the run modes are rare, usually you'd rather setup your OSGi configurations to depend on the run modes and have the OSGi components modify their behavior based on that.
Finally I decided to use global.jsp, write run-modes in the page context and get it in my class:
<%
pageContext.setAttribute("runModes", sling.getService(SlingSettingsService.class).getRunModes().toString());
%>
import java.util.Set;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.apache.sling.settings.SlingSettingsService;
public class myClass {
public static Set<String> getRunModes() {
BundleContext bundleContext = FrameworkUtil.getBundle(myClass.class).getBundleContext();
ServiceReference serviceReference = bundleContext.getServiceReference(SlingSettingsService.class.getName( ));
SlingSettingsService slingSettingsService = (SlingSettingsService)bundleContext.getService(serviceReference);
return slingSettingsService.getRunModes();
}
}
#Reference
RunMode runmode;
or
sling.getService( RunMode.class )
and call
getCurrentRunModes(); //returns String[]
If you're using Sightly and working with a class that extends WCMUsePojo
slingSettings =this.getSlingScriptHelper().getService(SlingSettingsService.class);
Set<String> runmodes = slingSettings.getRunModes();
As Bertrand Delacretaz said it is the right way to check whether instance is Author or Publish.
In jsp or java you could check like
import org.apache.sling.settings.SlingSettingsService
Set<String> runModes = sling.getService(SlingSettingsService.class).getRunModes();
if (runModes.contains("author")) {
}
Another way is using
if (mode == WCMMode.EDIT)
{
}
But this approach will fail in case of Preview mode and wouldn't work.
You can also try this:
RunModeService runModeService = getSlingScriptHelper().getService(RunModeService.class);
author = runModeService.isActive("author");

z3c.forms dynamic sources provider returns empty dictionary as a context object

I'm using Plone 4.1.4 and I'm trying to get dynamic sources for a schema.Choice to work, I need to populate country list which in turn depends on the context object.
I'm using this example:
http://plone.org/products/dexterity/documentation/manual/developer-manual/advanced/vocabularies
For IContextSourceBinder, example, an empty dictionary instead of actual context object is returned:
from zope import interface
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from zope.schema.interfaces import IContextSourceBinder
import zope.schema
from z3c.form import form
class CountryGenerator(object):
interface.implements(IContextSourceBinder)
def __call__(self, context):
#context is == {}
import pdb; pdb.set_trace()
return SimpleVocabulary([
SimpleTerm(value="not_selected", title=_("Country Not Selected"))
])
class IStep(interface.Interface):
region = schema.Choice(title=_("Select your country"),
required=True,
source=CountryGenerator,
default="not_selected")
class Step(form.Form):
fields = field.Fields(IStep)
label = _("Step")
description = _("Select your country")
When debugging point is hit inside CountryGenerator.__call__() method and I examine context object, the latter turn out to be just an empty dictionary.
When I try to use named utility example in the article mentioned above, and the similar thing happens, context there is also {}.
Could anyone point me to what I might be doing wrong?
UPDATE
ZCML for the form wrapper that calls the form is
<browser:page
name="view"
for="Products.oldproduct.MyFolderishClass"
class=".file.RegionClass"
permission="zope2.View"
/>
Where RegionClass inherits from Form wrapper, could it be permission or traversal issue?
Because your source is a class, you need to instantiate it:
class IStep(interface.Interface):
region = schema.Choice(title=_("Select your country"),
required=True,
source=CountryGenerator(),
default="not_selected")
In certain circumstances, such as with using sub forms or complex form widgets (widget within a widget for list selections, etc), you need to follow the __parent__ pointers to a proper outer context for getting back to the Plone context.

Resources