I am having a scenario in which i want to call a sling model with input parameter.
For this i have a code like this
<div data-sly-use.model3="${'com.bhf.aem.sling.models.Test' # colour='red'}">
</div>
But I want to call a method in sling model twice with two different parameters .Is it possible with sling models?
Any Help!!!
From AEM 6.3 there is a new HTL feature that allows to do this.
In the data-sly-include and data-sly-resource you can now pass
requestAttributes in order to use them in the receiving HTL-script.
This allows you to properly pass-in parameters into scripts or
components.
<sly data-sly-use.settings="com.adobe.examples.htl.core.hashmap.Settings"
data-sly-include="${ 'productdetails.html' # requestAttributes=settings.settings}"/>
Java-code of the Settings class, the Map is used to pass in the
requestAttributes:
public class Settings extends WCMUsePojo {
// used to pass is requestAttributes to data-sly-resource
public Map<String, Object> settings = new HashMap<String, Object>();
#Override
public void activate() throws Exception {
settings.put("layout", "flex");
}
}
For example, via a Sling-Model, you can consume the value of the specified requestAttributes. In this example, layout is injected via the Map from the Use-class:
#Model(adaptables=SlingHttpServletRequest.class)
public class ProductSettings {
#Inject #Optional #Default(values="empty")
public String layout;
}
By design of the HTL/Sightly language, sending parameters is only possible for data-sly-use (use objects initialization) and data-sly-call (template calls). The reason for this is to separate business logic from the view.
As mentioned by #tomasz-szymulewski, since https://issues.apache.org/jira/browse/SLING-5812, there is support for passing request attributes on resource/script inclusion in the Sling/AEM implementation.
Related
I'm writing an AEM component and I have an object being returned that is a type from an SDK. This type has public properties and no getters. For simplicity, it might be defined like this:
class MyItem {
public String prop1;
public String prop2;
}
Now normally, I would need a getter, like so:
class MyItem {
public String prop1;
public String prop2;
public String getProp1() {
return prop1;
}
}
But I do not have this luxury. Right now, I've got a Java implementation that uses another type to resolve this, but I think it's sort of crazy that HTL doesn't allow me to just access prop1 directly (it calls the getter). I've reviewed the documentation and can't see any indication of how this could be done. I'd like to be able to write:
${item.prop1}
And have it access the public property instead of calling getProp1().
Is this possible?
You don't need getters for public fields if those fields were declared by your Java Use-class. There's actually a test in Apache Sling that covers this scenario:
https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/testing-content/src/main/resources/SLING-INF/apps/sightly/scripts/use/repopojo.html
This also applies to Use-classes exported from bundles.
For Sling Models using the adapter pattern [0] I've created https://issues.apache.org/jira/browse/SLING-7075.
[0] - https://sling.apache.org/documentation/bundles/models.html#specifying-an-alternate-adapter-class-since-110
From the official documentation
Once the use-class has initialized, the HTL file is run. During this stage HTL will typically pull in the state of various member variables of the use-class and render them for presentation.
To provide access to these values from within the HTL file you must define custom getter methods in the use-class according to the following naming convention:
A method of the form getXyz will expose within the HTL file an object property called xyz.
For example, in the following example, the methods getTitle and getDescription result in the object properties title and description becoming accessible within the context of the HTL file:
The HTL parser does enumerate all the public properties just like any java enumeration of public fuields which include getters and public memebers.
Although it is questionable on whether you should have public variable but thats not part of this discussion. In essence ot should work as pointed by others.
I have a HTL component class like
MyComponent extends WCMUser{
#Reference
private ResourceResolverFactory resourceResolverFactory;
But when i am trying to use it i am getting NullPointerException on same.
I even tried using #Service & #Component SCR tags but no help.
You cannot use #Reference or other annotations with your Java Use API since it is not treated as an OSGi service. Instead use the getSlingScriptHelper() to get the SlingScriptHelper object which can then be used to get the services.
public MyComponent extends WCMUsePojo {
public void activate() {
getSlingScriptHelper().getService(<<SomeService.class>>);
}
}
However if it is only the ResourceResolver that you need you can call the getResourceResolver() method available within WCMUsePojo class.
More information on Java Use-API can be found in this official doc.
Got it, so i can create another service, get ResourceResolverFactory there. Once there i can use ResourceResolverFactory in this service or pass it to WCMUse class.
What is the way to consume a list of custom objects inside another custom object in JAX-RS CXF implementation? As an example my object looks like below
#POST
#Produces({MediaType.APPLICATION_JSON})
#Path("test")
public Response myMethod(MyCustomObject myCustomObject) {
Inside MyCustomObject it has a list of another custom object which reside inside this as an inner class
public class MyCustomObject {
private List<MyInner> innerObjects;
public class MyInner {
private String property;
....
}
....
}
Request JSON object is passed as the POST body of the request. When I debug this I could get the MyCustomObject passed properly while I am sending the innerObjects list as null. But it seems its not picking this correctly when I have this array based structure there with a custom object. Additionally instead of this custom object array when I have a primitive type or a string based array the service works fine. How to deal with the above scenario.
It is probably because of the inner class.
Similar question here
Not sure what mapper you use (cxf default is jettison but it is all configurable), but the case is probably similar.
Great explanation here
non-static inner classes (including anonymous ones) have set of hidden variables added by compiler, passed via (hidden) constructor. And as a consequence, do not have zero-argument ("default") constructor
So I have a model like this:
class MyClass
{
public $customer = null;
public $address = null;
}
And a form like this:
class MyForm extends CFormModel
{
public $customer = null;
public $address = null;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
array('customer, address', 'required'),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
What I would like to do, is extend the model in my form, but you can't do multiple object inheritance in PHP.
How would I do this, so as to avoid duplicating all of the field properties of model in form?
Use of Component Behavior
A component supports the mixin pattern and can be attached with one or several behaviors. A behavior is an object whose methods can be 'inherited' by its attached component through the means of collecting functionality instead of specialization (i.e., normal class inheritance). A component can be attached with several behaviors and thus achieve 'multiple inheritance'.
Behavior classes must implement the IBehavior interface. Most behaviors can extend from the CBehavior base class. If a behavior needs to be attached to a model, it may also extend from CModelBehavior or CActiveRecordBehavior which implements additional features specifc for models.
To use a behavior, it must be attached to a component first by calling the behavior's attach() method. Then we can call a behavior method via the component:
// $name uniquely identifies the behavior in the component
$component->attachBehavior($name,$behavior);
// test() is a method of $behavior
$component->test();
An attached behavior can be accessed like a normal property of the component. For example, if a behavior named tree is attached to a component, we can obtain the reference to this behavior object using:
$behavior=$component->tree;
// equivalent to the following:
// $behavior=$component->asa('tree');
A behavior can be temporarily disabled so that its methods are not available via the component. For example,
$component->disableBehavior($name);
// the following statement will throw an exception
$component->test();
$component->enableBehavior($name);
// it works now
$component->test();
It is possible that two behaviors attached to the same component have methods of the same name. In this case, the method of the first attached behavior will take precedence.
When used together with events, behaviors are even more powerful. A behavior, when being attached to a component, can attach some of its methods to some events of the component. By doing so, the behavior gets a chance to observe or change the normal execution flow of the component.
A behavior's properties can also be accessed via the component it is attached to. The properties include both the public member variables and the properties defined via getters and/or setters of the behavior. For example, if a behavior has a property named xyz and the behavior is attached to a component $a. Then we can use the expression $a->xyz to access the behavior's property.
More reading:
http://www.yiiframework.com/wiki/44/behaviors-events
http://www.ramirezcobos.com/2010/11/19/how-to-create-a-yii-behavior/
I have a new project where I am using GWT-Views like Composite, etc.
I have injected the items in the main menu (like ProductList below) using GinInjector. This works fine!
Somewhere I want to have a reference from a small component to an item from my main menu in order to update it. I try to inject it this way:
public class ProductForm extends Composite {
...
#Inject
ProductList list;
....
}
But when I use the list I always get null. Whereby, ProductList is defined this way:
public class MyModule extends AbstractGinModule {
...
#Override
protected void configure() {
bind(ProductList.class).asEagerSingleton();
bind(ProductForm.class).asEagerSingleton();
}
...
}
Any idea what I am doing wrong?!
Solution:
I failed to mention that ProductForm is an element of the ProductList using the UIBinder's #UIField tag, So That injecting it will create a new object rather than the one created using UIBinder.
I had to restructure my code to include presenters and an event bus so that no direct references between views are needed (other than the #UIField attributes).
I was working through Gin documentation : I'll quote it here :
Gin "Magic"
Gin tries to make injection painless and remove as much boilerplate from your code as possible. To do that the generated code includes some magic behind the scenes which is explained here.
Deferred Binding
One way Gin optimizes code is by automating GWT deferred binding. So if you inject an interface or class1 bound through deferred binding (but not through a Guice/Gin binding), Gin will internally call GWT.create on it and inject the result. One example are GWT messages and constants (used for i18n purposes):
public interface MyConstants extends Constants {
String myWords();
}
public class MyWidget {
#Inject
public MyWidget(MyConstants myconstants) {
// The injected constants object will be fully initialized -
// GWT.create has been called on it and no further work is necessary.
}
}
Note: Gin will not bind the instances created through GWT.create in singleton scope. That should not cause unnecessary overhead though, since deferred binding generators usually implement singleton patterns in their generated code.
You can see for yourself in this URL : http://code.google.com/p/google-gin/wiki/GinTutorial
It fails to mention why a singleton cannot be autogenerated by deferred binding and injected.
You can fix this by handcreating, using GWT.create(YourFactoryInterface.class).getProductList() in the constructor.
This means for testing puposes, you will need to pull the GWT.create into a seperate method and override it in a subclass and use that for testing like :
YourFactoryInterface getFactory() {
return GWT.create(YourFactoryInterface.class)
}
and
getFactory().getProductList()
Gin's asEagerSingleton() binding was broken for quite a while, and was injecting null. Not sure when the fix went in, but I had problems with eager singletons on v1.0. See the issue or the explanation, if you're interested. I'd either switch to regular .in(Singleton.class) bindings, or make sure you're using Gin 1.5.
Is the Ginjector creating the ProductForm? I think maybe that is needed to make it populate the injected variable.