Get object from form with errors in play framework 2.0 - scala

I am getting an error when I try to extract a user from a form with validation errors.
I have the following route configured in my routes file:
GET /users/:user controllers.UsersController.viewUser(user: models.User)
GET /users/:user/edit controllers.UsersController.editUser(user: models.User)
This is fine at this point, and I can render a link to the user view from my scala templates:
routes.UsersController.viewUser(myUserObject)
My problem is that in my user edition form I need to get myUserObject from a Form[User] object. What I am currently doing is:
routes.UsersController.viewUser(userForm.get)
However, when the userForm has any errors, the get method raises an exception, as shown in the documentation.
The approach I have taken is passing an additional User parameter to the scala view, together with the Form[User] parameter I was passing up to now, I mean,
userEdit.render(user, userForm)
instead of just
userEdit.render(userForm)
However, I would like to know if there is a more suitable solution that does not involve including an additional parameter.

The documentation states that you can prefill a form with existing data:
val filledForm = userForm.fill(User("Bob", 18))
Given the preexisting User, it should be trivial to adapt to your example.

Related

Access related model fields from ModelAdmin actions for exporting to excel

I am desperately waiting for someone attention to get my question answered.... please help..
ModelAdmin model has to export to Excel action method.
I need to access related model fields in action method. That means I can not pass any arguments therefore I tried relatedmodel_set but ModelAdmin action method shows memory location and fails when I try to access values through attributes:
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager..RelatedManager object at 0x7f8eea904ac0>
model.py
class EnrolStudent(models.Model):
def get_trn_activity(self):
return self.studenttraininactivities_set
class StudentTraininActivities(models.Model):
trainin_activities = models.ForeignKey(EnrolStudent,
on_delete=CASCADE, null=True )
<other fields...>
admin.py
#admin.register(EnrolStudent)
class EnrolAdmin(admin.ModelAdmin):
form = CityInlineForm
inlines = [CohortTraininActivitiesInline]
...
actions = [export_as_txt_action_0120("File NAT00120 data Export"
, fields=['information_no', 'get_trn_activity',
'student_enrol__student_code'])]
I need to access related model fields to export to excel.
I can not pass parameter to get_trn_activity as you have noticed.
Therefore selected rows only data from Django admin change_list page will only need bit of work using its queryset in actions method used in separate actions.py file that I can do!
Please help me with this issue. I am new to Python / Django.
I also tried property decorator in related model then access in a method in main model then call it inside action but same problem with memory address not the direct value and then how to get data of memory location here .... I don't know.
If I can access the related fields then I can do it no issue.
Another question:
I had same situation with model/related model before, but they were connected through OneToOneField relationship and I was able to use dundor to access related model fields but in this case of ForiegnKey relationship I can not see related model in queryset.
In other case this is what I can do easily; here cohortdetails is related model and when I debug I saw it was listed in queryset that was great.
actions = [export_as_txt_action_0080("File NAT00080 txt Export",
fields=['rto_student_code', 'first_name', 'family_name'
,'cohortdetails__highest_school__highestschool_levelcode',
'cohortdetails__cohort_gender'
, 'cohortdetails__student_dob' ])]

How to use delta trigger in flink?

I want to use the deltatrigger in apache flink (flink 1.3) but I have some trouble with this code :
.trigger(DeltaTrigger.of(100, new DeltaFunction[uniqStruct] {
override def getDelta(oldFp: uniqStruct, newFp: uniqStruct): Double = newFp.time - oldFp.time
}, TypeInformation[uniqStruct]))
And I have this error:
error: object org.apache.flink.api.common.typeinfo.TypeInformation is not a value [ERROR] }, TypeInformation[uniqStruct]))
I don't understand why DeltaTrigger need TypeSerializer[T]
and I don't know what to do to remove this error.
Thanks a lot everyone.
I would read into this a bit https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/types_serialization.html sounds like you can create a serializer using typeInfo.createSerializer(config) on your type info. Note what you're passing in currently is a type itself and NOT the type info which is why you're getting the error you are.
You would need to do something more like
val uniqStructTypeInfo: TypeInformation[uniqStruct] = createTypeInformation[uniqStruct]
val uniqStrictTypeSerializer = typeInfo.createSerializer(config)
To quote the page above regarding the config param you need to pass to create serializer
The config parameter is of type ExecutionConfig and holds the
information about the program’s registered custom serializers. Where
ever possibly, try to pass the programs proper ExecutionConfig. You
can usually obtain it from DataStream or DataSet via calling
getExecutionConfig(). Inside functions (like MapFunction), you can get
it by making the function a Rich Function and calling
getRuntimeContext().getExecutionConfig().
DeltaTrigger needs a TypeSerializer because it uses Flink's managed state mechanism to store each element for later comparison with the next one (it just keeps one element, the last one, which is updated as new elements arrive).
You will find an example (in Java) here.
But if all you need is a window that triggers every 100msec, then it'll be easier to just use a TimeWindow, such as
input
.keyBy(<key selector>)
.timeWindow(Time.milliseconds(100)))
.apply(<window function>)
Updated:
To have hour-long windows that trigger every 100msec, you could use sliding windows. However, you would have 10 * 60 * 60 windows, and every event would be placed into each of these 36000 windows. So that's not a great idea.
If you use a GlobalWindow with a DeltaTrigger, then the window will be triggered only when events are more than 100msec apart, which isn't what you've said you want.
I suggest you look at ProcessFunction. It should be straightforward to get what you want that way.

Event xforms-model-construct-done behaviour

In my form I would like to call web service after to form is loaded after publishing. I've created custom XBL control for it, where I have :
<xf:group id="component-group">
<xf:action ev:event="xforms-enabled" ev:target="component-group">
<xf:send ev:event="xforms-enabled" submission="my-submission"/>
</xf:action>
</xf:group>
But it doesn't work as expected : my submission is sent everytime when I add new element in FormBuilder or change a name of some other controls. Generally speaking submission is sent when my form is changing in some way.
Now I want submission to be sent ONLY when I publish my form and someone would open it to fill (and of course when I press "Test" in FormBuilder, but I guess it's the same as filling form after publishing).
I was trying something like this :
<xf:group id="component-group">
<xf:action ev:event="xforms-model-construct-done" ev:target="component-group">
<xf:send ev:event="xforms-model-construct-done" submission="my-submission"/>
</xf:action>
</xf:group>
Unfortunately it's not working, this way submission is not sent at all. Any thoughts ?
This is due to the fact that XBL components are live at design time too. So you need a way to test whether the component is running within Form Builder or not.
There should be a function for this, really, but there isn't (I added this to the list of functions we should add to the API here). You can do:
<xf:group id="component-group">
<xf:var name="fr-params" value="xxf:instance('fr-parameters-instance')"/>
<xf:action
event="xforms-enabled"
target="component-group"
if="not($fr-params/app = 'orbeon' and $fr-params/form = 'builder')">
<xf:send submission="my-submission"/>
</xf:action>
</xf:group>
A few minor comments:
you don't need to (in fact shouldn't) place event attributes on nested actions
you don't even need the ev prefix

Symfony form gets messy when calling getObject() in form configuration

I have a Strain model that has a belongsTo relationship with a Sample model, i. e. a strain belongs to a sample.
I am configuring a hidden field in the StrainForm configure() method this way:
$defaultId = (int)$this->getObject()->getSample()->getTable()->getDefaultSampleId();
$this->setWidget('sample_id', new sfWidgetFormInputHidden(array('default' => $defaultId)));
Whenever I create a new Strain, the $form->save() fails. The debug toolbar revealed that it tries to save a Sample object first and I do not know why.
However, if I retrieve the default sample ID using the table it works like a charm:
$defaultId = (int)Doctrine_Core::getTable('Sample')->getDefaultSampleId();
$this->setWidget('sample_id', new sfWidgetFormInputHidden(array('default' => $defaultId)));
My question here is what can be happening with the getObject()->getSample()... sequence of methods that causes the StrainForm to think it has to save a Sample object instead of Strain.
I tried to debug with xdebug but I cannot came up with a clear conclusion.
Any thoughts?
Thanks!!
When you call getSample its creating a Sample instance. This is automatically attached to the Strain object, thus when you save you also save the Sample.
An altenrative to calling getSample would be to chain through Strain object to the Sample table since i assume youre only doing this so your not hardcodeing the Sample's name in related form:
// note Sample is the alias not necessarily the Model name
$defaultId = Doctrine_Core::getTable($this->getObject()->getTable()->getRelation('Sample')->getModel())->getDefaultId();
Your solution probably falls over because you can't use getObject() on a new form (as at that stage the object simply doesn't exist).
Edit: Why don't you pass the default Sample in via the options array and then access it from within the form class via $this->getOption('Sample') (if I remember correctly)?

Validation / Error Messages in ASP.Net MVC 2 View Unrelated to a Property

What pattern can I use to display errors on an MVC 2 view that are not related to a single property?
For example, when I call a web service to process form data, the web service may return an error or throw an exception. I would like to display a user-friendly version of that error, but have no logical means to relate the error to any given property of the model.
UPDATE:
Trying to use this code as suggested, but no summary message is displayed:
MyPage.spark:
Html.ValidationSummary(false, "Oopps it didn't work.");
Controller:
ViewData.ModelState.AddModelError("_FORM", "My custom error message.");
// Also tried this: ViewData.ModelState.AddModelError(string.Empty, "My custom error message.");
return View();
UPDATE 2
What does this mean?
next to each field.
Instead of always displaying all
validation errors, the
Html.ValidationSummary helper method
has a new option to display only
model-level errors. This enables
model-level errors to be displayed in
the validation summary and
field-specific errors to be displayed
next to each field.
Source: http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc#_TOC3_14
Specifically, how does one add a model level error (as opposed to a field-specific error) to the model?
UPDATE 3:
I noticed this morning that Html.ValidationSummary is not displaying any errors at all, not even property errors. Trying to sort out why.
Simply adding a custom error to the ModelState object in conjunction with the ValidationSummary() extension method should do the trick. I use something like "_FORM" for the key... just so it won't conflict with any fields.
As far as patterns go, I have it setup so that my Business Logic Layer (called via services from the controller) will throw a custom exception if anything expected goes wrong that I want to display on the view. This custom exception contains a Dictionary<string, string> property that has any errors that I should add to ModelState.
HTHs,
Charles