Play framework 2 Constraints client side validation - playframework-2.3

I am currently using Play Framework and was wondering if there is a helper template out there (even by a 3rd party) that will add the HTML5 attributes (e.g. required) based on the model annotations.
For example on my model
public class MyModel {
Constraints.Required(message="Required")
public String name;
}
on my View.Scala.html
#helper.inputText(
field = myModelForm("name"),
'_label -> "Name",
'_class -> "form-control",
'_showConstraints -> false,
'_showErrors -> true)
Is there an existing set of helper templates or 3rd party plugin that will add the required attribute on the HTML element?
I thought about creating my own helper templates but I'm not very familiar with Scala and do not know how to use reflection to check for attributes. If you are familiar with this syntax, please help! This would give me the flexibility to use Angular validation or jQuery validation but it's not a requirement at this point.
Thank you in advance!

There is a module for this: https://github.com/loicdescotte/Play2-HTML5Tags
I just tested it occasionally but seems it does what you need (at least with most popular constraints like Required MinLength etc. Also allows to use input fields with email or number type.
If it won't satisfy you I'm pretty sure that you can use it as reference and create custom solution.

Related

Yii2 best practices translating dynamic content

Can anyone share own experience and best practices implementing multilingual sites with Yii2? I want translate user input that is stored in database. For example article, that may have its name in three different languages, body and some translatable attributes as well.
Does Yii2 have built in features to translate the dynamic content? Or should I use third party extensions like these ones below:
https://github.com/creocoder/yii2-translateable
https://github.com/LAV45/yii2-translated-behavior
https://github.com/lajax/yii2-translate-manager
Your help would be appreciated.
Well, I can give you my point of view only based on what I have done.
There are to places to work translation
The non dynamic strings managed with i18n and messages system from
yii, that will help you with static content.
Working the translated routes dynamically with a bootstrapped class, that allows you to build this routs when the app is built.
And working with tables that have columns that support the translation like 'title_en, title_es', and as many as you need to translate. Actually in your admin interface you may want to use something like yandex to help you translating the content to this fields.
Now I will explain:
The i18n Message Translation is based on translating strings in your views, models, and in some cases like on the bootstrapped class.
You will en using Yii::t('app/main', 'Your name is {0}' as an example to translate strings that are stored on message php files.
Now if you translate stings you will want to translate the routes so you will en with routes like /articles and /articulos when you change the language.
for this purpose you will like to build a class that implements BootstrapInterface and that will be called from the process of bootstrapping your app.
So this is an example of my settings.php that I use for this
namespace app\base;
use Yii;
use yii\base\BootstrapInterface;
class settings implements BootstrapInterface {
public function __construct() { }
public function bootstrap($app) {
/// Dynamic translated routes
$t_articles = Yii::t('app/route', 'articles');
$app->getUrlManager()->addRules([
'/'.$t_articles => '/articles',
], false);
}
}
And remember to bootstrap the class in your config file «i.e. web.php»
'bootstrap' => [
'log',
'app\base\settings',
],
And finally to translate text from the database you may want to make a table that supports the translated text like:
CREATE TABLE articles (
id INT,
title_en VARCHAR(20),
title_es VARCHAR(20)
);
So when you call your app you can pull your data using something like the following on the action (only a simple example):
$articles = ArticlesA::find()->where(['id' => 1])->one();
$lang = $this->module->language;
return $thi
s->render('index',['articles'=>$articles, 'lang'=>$lang]);
or in the view as:
<p class="lead"><?=$articles['title_'.$lang]?></p>
I hope this explains the way I have been translating my apps.
Use a Google translator API or Yandex API to for smooth translations for multiple languages.
Few links that i have found on git
https://github.com/borodulin/yii2-i18n-google
Tutorial
RichWeber/yii2-google-translate-api
Google Api is a paid service however you can get free credit for 12 months if your a first time user

How to implement PropertyDefiner for logback to access multiple properties

I would like to define some properties in my logback.xml config file and saw that by implementing the PropertyDefiner was a great way to set properties in a customizable way.
After starting to implement it I began to wonder how to access the value of the name attribute of the element within the tag. I'm not seeing anyway to do this and I'm scratching my head. Would this PropertyDefiner really make you create a new implementation for every single property? Why not just hard code it? I didn't see much discussion about this out on the web.
I hope I'm just not seeing it and that the brains of stackoverflow can help me out. Does anyone know how to do this? Thanks!
I found this discussion: essentially the same question is asked, but no answer was returned.
fyi: I want to customize how I get my properties because I am pulling it from a database. I have a helper class which pulls the properties in on server startup. These properties vary based on environment (dev, test, prod, etc.)
As of logback version 1.0.6, the value of the name attribute cannot be accessed directly. However, nothing prevents you from passing the value of the name attribute in a property of your choice. Example:
<define name="rootLevel" class="Your.PropertyDefiner">
<myKey>rootLevel</myKey>
</define>
where myKey is a property of Your.PropertyDefiner. For example:
class Your.PropertyDefiner implements PropertyDefiner {
String myKey;
public void setMyKey(String k) {
this.myKey= k;
}
public String getPropertyValue() {
return ...
}
}
Joran, logback's configuration framework, takes care of the wiring. Joran will inject the value of the myKey element into the myKey property of Your.PropertyDefiner. If you are curious about the technical details, see the documentation on implicit actions and implicit actions in practice.

How to map the PHP DateTime class to ActionScript / Flex Date class using Zend Framework AMF

Background
Okay I'm one of those guys who NEVER asks questions and who can usually find what I need from existing questions or forums....but alas I have spent the last few days trying to figure this one out and have come up with very little existing information.
I am using Flash Builder 4.6 for PHP Premium to build a Flex application that uses the PHP Zend Frameworks's AMF capabilities to map classes from PHP to Flex and to use them as objects to send back and forth instead of using XML or JSON. Right now I am doing it all on a single local machine for ease.
Issue
I am not having trouble mapping my own custom PHP classes into ActionScript/Flex classes but I cannot for the life of me manage to map a DateTime PHP class into an ActionScript Date class. I have read elsewhere that it automatically maps DateTime objects to Date objects but I have never gotten it to work.
Strangely though, I can get it to work if I replace all instances of, in my case, valueObjects.DateTime (the auto-generated ActionScript class) to Date in the _Super_Foo.as class that has the DateTime property. This basically forces Flex to interpret the data of that property as a Date. However, since all the _Super_XXX.as files are files that autogenerated by Flex, it gets rewritten any time I refresh or edit ANY PHP service that Flex is linking to in Flash Builder.
Remarks
I could of course do this the quick and dirty way by keeping the variable as a string (it's coming from MySQL in a DateTime field) and then just create some functions to convert it to a Date object on the client side but I need a more permanent and stable solution.
Example:
<?php
class Foo {
public $id; // int
public $name; // string
public $date; // DateTime
public $bar; // custom object
}
?>
should go to --->
package {
class Foo {
public var id:int;
public var name:String;
public var date:Date; // native class
public var bar:Bar;
}
}
but I am getting
package {
class Foo {
public var id:int;
public var name:String;
public var date:DateTime; // custom class
public var bar:Bar;
}
}
I have tried things such as the following:
in the gateway.php file
$server->setClassMap("Date", "DateTime");
using the Zend_Date object instead
$foo->date = new Zend_Date($blah);
and after trying to map it as well explicitly
$server->setClassMap("Date", "Zend_Date");
the change I currently have working in the _Super_Foo.as file (which gets written over frequently)
private var _internal_date : valueObjects.DateTime; // custom object
to
private var _internal_date : Date; // native object
I just need it to do this automatically like I have read it should.
Well I have to admit, that I usually use BlazeDS on Java and not Zend, but I have had similar problems in transfering Calendar objects (I wanted to prevent loosing the timezone data). For This BlazeDS supported so-called PropertyProxys, which are components that allow to takeover the serialization/deserialization process for certain types.
I would assume that ZEND would support a similar thing. So another option would actually be to make Zend zupport the full Flex type. I have searched a little and it seems that the entire terminology is different in Zend, but I think this stackoverflow article should explain it a little: Zend AMF custom dispatcher
Chris
In my experience, Zend Framework has taught me that it offers many features but many times they don't work exactly how you'd expect. For example:
Recently I was working with a bug in "digitalus-cms" (A blog-like framework built on top of ZF) that it couldn't post new articles with a hyphen in their title name. I tracked it down to Zend_Form_Element::filterName. It uses a regular expression that matches any character that falls into the category of: [^a-zA-Z0-9_\x7f-\xff] then removes it. This ends up removing hyphens from the names of form elements which wound up being the cause of the bug.
If Zend_Amf or Zend_Date doesn't work the way you want it to, find a workaround such as passing a unix timestamp number around so everything works the way it should. Then afterwards, you can write a class to extend off one of Zend's classes. Zend Framework is meant to be extended upon, that's the way the framework was built so you can fix issues like these on your own to get the framework to behave how you want it to. That's the whole point of wrappers. Go ahead, create some of your own wrapper classes and toss in some methods to interact with ZF so you can fine-tune everything.
As far as finding the cause of your issue, all I can tell you is keep on debugging and isolating code so you know what you are passing flex, and how flex responses to that. After you play around with it enough, I'm sure you'll find the culprit.
AmfPHP automatically maps it. http://www.silexlabs.org/amfphp/

Use of metadatatype in linq-to-sql

I had asked this question
Adding more attributes to LINQ to SQL entity
Now, when I add Browsable attribute to generated entity in designer,it works.But,when I use the MetaDataType approach,and add Browsable attribute in partial class,it does not work
"I added a MetaDataType class, and added browsable attribute to property,but seems to have no effect"
Adding the MetadataTypeAttribute will only be useful when you have written custom code that detects the BrowsableAttribute. The .NET framework doesn't handle MetadataTypeAttribute any differently than any other attribute and doesn't 'merge' your type with the meta data type.
When you have written your own code that detects the BrowsableAttribute, you can change it, so it also detects a MetadataTypeAttribute on a type and if it exists, you can go to the referred metadata class to search for properties decorated with the BrowsableAttribute. When the logic using the BrowsableAttribute has not been written by you (for instance, this is part of the .NET framework, because it is used by the Visual Studio designer), there is no way of getting this to work.
Currently there are only a few parts of the .NET framework that know about the MetadataTypeAttribute. MVC for instance uses it for validation and with .NET 4.0 DataAnnotations (that defines the attribute) also has a validator. Enterprise Library 5.0 (currently in beta) will also detect this attribute for validation.
While more and more applications and part of the framework might be able to handle this attribute, in most situations using it is useless.
I'm using it so that I can allow my Linq-To-SQL classes to also have Json properties to ease deserialization of Json objects:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(User_JsonProperties))]
public partial class User
{}
public class User_JsonProperties
{
[JsonProperty("user_id")]
public int UserId { get; set; }
}
Since the other author didn't include source code, I thought I would so that you'd see what it looks like.

Associating an Object with other Objects and Properties of those Objects

I am looking for some help with designing some functionality in my application. I already have something similar designed but this problem is a little different.
Background:
In my application we have different Modules. Data in each module can be associated to other modules. Each Module is represented by an Object in our application.
Module 1 can be associated with Module 2 and Module 3. Currently I use a factory to provide the proper DAO for getting and saving this data.
It looks something like this:
class Module1Factory {
public static Module1BridgeDAO createModule1BridgeDAO(int moduleid) {
switch (moduleId)
{
case Module.Module2Id: return new Module1_Module2DAO();
case Module.Module3Id: return new Module1_Module3DAO();
default: return null;
}
}
}
Module1_Module2 and Module1_Module3 implement the same BridgeModule interface. In the database I have a Table for every module (Module1, Module2, Module3). I also have a bridge table for each module (they are many to many) Module1_Module2, Module1_Module3 etc.
The DAO basically handles all code needed to manage the association and retrieve its own instance data for the calling module. Now when we add new modules that associate with Module1 we simply implement the ModuleBridge interface and provide the common functionality.
New Development
We are adding a new module that will have the ability to be associated with other Modules as well as specific properties of that module. The module is basically providing the user the ability to add their custom forms to our other modules. That way they can collect additional information along with what we provide.
I want to start associating my Form module with other modules and their properties. Ie if Module1 has a property Category, I want to associate an instance From data with that property.
There are many Forms. If a users creates an instance of Module2, they may always want to also have certain form(s) attached to that Module2 instance. If they create an instance of Module2 and select Category 1, then I may want additional Form(s) created.
I prototyped something like this:
Form
FormLayout (contains the labels and gui controls)
FormModule (associates a form with all instances of a module)
Form Instance (create an instance of a form to be filled out)
As I thought about it I was thinking about making a new FormModule table/class/dao for each Module and Property that I add. So I might have:
FormModule1
FormModule1Property1
FormModule1Property2
FormModule1Property3
FormModule1Property4
FormModule2
FormModule3
FormModule3Property1
Then as I did previously, I would use a factory to get the proper DAO for dealing with all of these. I would hand it an array of ids representing different modules and properties and it would return all of the DAOs that I need to call getForms(). Which in turn would return all of the forms for that particular bridge.
Some points
This will be for a new module so I dont need to expand on the factory code I provided. I just wanted to show an example of what I have done in the past.
The new module can be associated with: Other Modules (ie globally for any instance of that module data), Other module properties (ie only if the Module instance has a certian value in one of its properties)
I want to make it easy for developers to add associations with other modules and properties easily
Can any one suggest any design patterns or strategy's for achieving this?
If anything is unclear please let me know.
Thank you,
Al
You can use springs Dependency Injection feature. This would help you achieve the flexibility of instantiating the objects using an xml configuration file.
So, my suggestion would be go with the Springs.