(If this is not the right place to post this kind of question I'd happily post it somewhere else)
I'm trying to build an interactive web application to manage company resources.
I have experience with Symfony2 but I kind of hit a wall with this new application.
I'd like to make this application quite interactive on the client side. Almost a full single webpage application.
My previous web applications would normally just use a typical MVC pattern with CRUD pages.
In those simple applications I would have
/employees/
/employees/create
/employees/detail/45
/employees/update/45
/employees/delete/45
Using symfony in this kind of application would give me a lot of advantages:
Routing
Security (CSRF tokens)
FormTypes and Form handling
Validation
Integration with Doctrine
Twig
Especially functionality like this in Twig was very refreshing (since my models were build as Doctrine entities):
<p>{{ employee.getCurrentTask().description }}</p>
The problem I'm facing now is that I feel like Symfony2 isn't really build for single webpage applications. As soon as I try to add some Ajax functionality I'm faced with these problems:
CSRF tokens invalid
Too much non reusable view/presentation logic in jQuery
Adding data-attributes in html to get id's etc...
I then looked into Knockout.js and Angularjs but then I feel like lose all of the advantages of Doctrine and Twig. I have to rebuild my models on the client side anyway and have to maintain them in two different locations then.
So I came up with this idea:
Use Symfony2 models and controllers to persist data to the database but let controllers in symfony just send out JSON and receive JSON (FOSRestBundle maybe?)
Use a framework like AngularJS or KnockoutJS to rebuild that JSON data on the client side to use 2-way binding.
But then how would I tackle the issues like Doctrine2 Relationships, Form Validation, CSRF which Symfony already solved but are unusable if I use a frontend js framework?
All suggestions are welcome!
Some words about JSON, Serialization and Models
Simon, I faced exactly the same questions and problems. First like ken already mentioned. You don't need to rebuild any model. Better use FosRestBundle and/or JMS Serializer. It turns you entities with relations into JSON objects. This objects are transferred via api to your frontend and you can work with them just like in twig, when you use angular.js like this
{[{ user.username }]}
is as same as in twig. But remember that you have to set custom brackets for angular because by default it uses the same as twig.
Routing
You talk of a single page application, so symfony's routing is kept on a low level to have few page refresh. Instead you have to use routing of your frontend framework, because I am only familiar with angular.js, I give an angular example:
app.config(function($routeProvider, $interpolateProvider) {
//here you go, custom brackets
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
$routeProvider.when('/user', {
controller: UserController,
templateUrl: Routing.generate('suser_list')
}).when('/ticket', {
controller: TicketController,
templateUrl: Routing.generate('ticket_list')
});
});
When you hit a link like
Go to tickets
AngularJs will know which frontend controller to trigger. Pretty great stuff, without page reload. Also have a look at FosJSRoutingBundle. It allows you to generate symfony routes in javascript, I use them to link js controllers with html templates where data is pushed in.
FormTypes, Form handling, Validation
Well, when you use a frontend framework like angularjs, your symfony form types are pretty useless. But I am not sure. Remember data is pushed and pulled via api as json, I think this would be a hard job for form types to handle this kind of compexity.
For validation you can use angular's live validation or have you symfony's validation in the backend, no problem. It might be a good thing to use both, client and server side validation.
Twig
Twig is out of the race. All data is rendered on the client side, and not pre rendered on server side like with twig. But that is only the case if your application is really a single page application. Of course you can use twig, but it will only refresh if you reload the entire page.
Integration with Doctrine
You can still use doctrine in the backend. Do you have a specific question regarding doctrine and SPA?
You don't need to rebuild the model in client. I normally just create a service in angularjs that provides json data. Data manipulation still happens server side using ajax.
For forms that requires csrf, I normally just send the html rendered by twig via json. Or you can serialize $form->createView() with jms serializer. However you will need some client script to transform the json data to actual form controls.
Related
I was browsing the typo3 core Forms framework documentation but with no relevant answer to my requirements which are:
The form has to be displayed in a frontend overlay.
The filling process involves multiple steps where the user would be able to go back and forth.
The form fields must still be editable by a redactor.
I'm not sure about how the form framework behaves, so far I remember I think that multiple steps are configurable from the backend module but I don't know if it sends request to the controller after each step or if it sends everything only on submit.
I have an idea about how to implement it though, it's based on this question how to get a typo3 form framework html via ajax. Which would just let me provide the whole html content to the frontender and let him split the whole form into steps. The separation would be based on the addition of some special tags via the editor that would surround the fields you want in each step.
What do you think about that approach?
The form framework proceeds each form step seperately. So without developing your own form runtime, you have to keep proceeding every step seperate.
I see two possibilities:
1. Send each form step from frontend to the form controller and replace the response (html form) in the frontend.
That is the fast and easy way, as you use the existing form runtime.
Prepare a page which returns the rendered form as html
Fetch this page by JavaScript
Send the form data back to the given form action
The form controller proceeds the form with all its validators, rules and finishers and returns the next step, previous step, the current step with existing errors or the finishers response on success
Replace your form in the frontend with the already rendered html response of the form framework
The advantage of this way: Less effort and you can rely on the already existing validators, as you get an already validated response.
The disadvantage of this way --> it is more difficult to implement frontend validation, as you have a mix between frontend and server side validation.
2. Make the form framework kind of headless and work json based
In my opinion the better approach, but with a lot more effort to take.
You have to extend / overwrite the controller and the form runtime. This allows you more flexibility in handling the form by JavaScript and e.g. return the errors in a json object. It makes life easier when you want the form render and handle with a JS framework like react or vue.
To your question:
What do you think about that approach?
If I got it right, you want to keep ONE form step in the backend, but let the editor divide this form step into multiple steps by adding tags? You can try, but I don't see any real advantage in keeping the original form steps and proceed every step by sending the step to the controller and handle the response (like mentioned in 1.)
Summary:
In the past, I was thinking a lot about handling forms by JavaScript and came to the conclusion:
Keep the form framework's behaviour completely untouched with server side processing or make it frontend driven, with an own runtime. All mixtures between client and server side rendering will sooner or later run into bigger problems or at least a high effort. The form framework is pretty complex with a lot of possibilities, hook driven behaviour, etc. From my experience, you have to know it pretty good to develop without loosing control. In smaller projects with just one or two basic forms, I would try to avoid special cases with lots of JS. In bigger projects (with more budget), I would definitely go with my second mentioned approach (currently, I'm developing vue.js based rendering and handling of the form frontend). But these are just my five cents...
I've done almost all of my web projects using Java(Spring MVC + Thymeleaf) and it's MVC technologies. Recently I've heared about REST and started learning some stuff about it. I realized that it is one of the coolest things I've ever seen in my whole life!(I'm just joking around, it's definitely not)
All we need is just to parse data to json type and then return it to the frontend. And in frontend we no longer need to use Model and it's objects. Frontend can get all required data in nice-to-work-with json type using one single GET request!
We don't need to use some weird Thymeleaf constructions to handle errors or to iterate through the list in our template! We can handle all events and process all data using javascript and it's frameworks. It is much more powerful.
Does there exist something I missed? When to use Model? When to use json-type data?
These are two (somewhat overlapping) approaches to frontend development: generating pages on the backend and on the frontend.
Using a backend model and Thymeleaf templates (or any other HTML templates), you generate your web page on the server side. This means the following benefits
you can write frontend and backend logic in one language (Java);
you can enforce data and security constraints in one place - on the backend, using Java code or configuration;
in many cases, it's faster for the user to get their first page, since the rendering happens on the server, and the user gets an already rendered page;
But this approach has the following drawbacks:
the server has to render the pages, which means more load on the server;
most of the modern web sites and applications use JavaScript anyway, so you'll have to write at least some JavaScript;
server-generated pages don't even come close to what's possible to render in the browser.
Providing a REST API for a JavaScript frontend, you have the following benefits:
you unload your server, since most of the UI related work happens on the user's device;
you can achieve much more with modern frontend frameworks;
navigating on an already rendered UI is faster, since you don't need for the server to render every page, you only need to get a relatively small JSON response and then update the page dynamically.
But this approach has the following tradeoffs:
the user generally waits longer to see their first page, as the browser needs to download a lot of scripts and then spend time on dynamic rendering of the page;
in a large application, you need to either have a full-stack developer team, or two teams working on frontend and backend separately;
you have to write your UI logic in JavaScript. Make of it what you will :)
you have to sometimes duplicate the constraints both on the frontend and on the backend: e.g., if a user can't edit a field, you have to both show it as read-only on the frontend, and add validation in your REST service, since the user may try to access your REST API directly and bypass the frontend validation;
you have to be more aware of securing your REST API in general.
As far as i understand it right JMSSerializerBundle's deserialisation does the same same as the symfony form component when a controller gets an post/put/patch request?
So either i create a symfony custom formType for e.g. an UserType and when i get a request i do something like $form->handleRequest($request) or i use JMSSerializerBundle to unserialize the request to a document/entity which gets finally stored.
Does anyone have experience with both methods? Currently i'm only familiar with the form way... Which one should i choose?
The Application i'm talking about is purely Restful, there are no twig html templates and FOSRestbundle is doing all the RESTful routing.
In our restfull API we usually use the Symfony Serializer component to handle the deserialization of entities, then the Symfony Validator component to ensure that the entities fulfill all the required conditions before pushing/updating them in database. Works pretty well, lighter than the form component.
Anyway The Form component would not be able to deserialize the json/xml so you'll have to use a serializer.
The benefit of the Symfony\Form component over the JMS Serializer is that the validation is done before deserialization which fits into PHP 7 strict typing. Example case - you pass an array instead of a string, JMS creates and object and the getter raises a \TypeError instead of a validation error from the validator.
Is there a way (using JQuery or Java Script) to force an MVC2 form to perform validation on it's fields with Data Annotation validation without posting back to the server?
I have a MVC2 form that is quite complex. Many of the fields are hidden or displayed depending on other selections. Given this, some of the fields are validated using Data Annotations and some are validated using custom JQuery.
In the case that one of the fields with custom validation fails it's validation I wish to prevent the form from posting back however this stops any of the fields with Data Annotation Validation from working.
Thanks.
IMHO mixing jquery validate with MSAjax is a bad thing. For complex forms with many custom validation rules I would recommend using only jquery validate and on the server a more powerful validation framework than DataAnnotations such as FluentValidation.NET which works nicely with ASP.NET MVC.
Will be starting a web app that will have to provide many different HTML forms for data entry, so I was wondering if there is a web framework out there that does this in a clever way. generally when you have forms you have many considerations like navigation, validation, etc. that are not handled very efficiently by he frameworks I've seen so far.
Has someone taken the pain out of forms?
Have you tried looking at Grails? It can take your domain classes and dynamically scaffold them into web forms and apply server-side validation. The default scaffolding provides navigation, pagination, validation, and all kinds of other -ations that are pretty good!
Here's a good tutorial.
Try Qcodo.com, It is written in PHP (but fully OOP). It manages both database layer with nice Form templating system.
I think forms are handled pretty cleverly in Ruby on Rails. And also in .Net. The latter goes pretty far in letting you reuse the database logic for validating data and also has "automatic" handling of security issues like XSS and XSRF.