First of all i am very new to Symfony 2 and started to learn.
Is there any possibility for filter a value? Perhaps filter chains too?
I know this concept from Zend Framework 1 and 2.
E.g.:
i have a string "1A- N "
now i want to filter so that only numeric values pass; result "1"
Do i have to implement this on my own i Symfony?
I would like to do something like:
$text = '1A - N';
$numberFilter = new NumberFilter();
$filteredText = $numberFilter->filter($text);
//now in $text i find '1'
But for now i nowhere found something like this in Symfony what surprises me a lot. I thought it is a full stack framework and such function is so basic.
I found something like validators but they only say if a value e.g. contains only numbers or not. Or is the validation concept of symfony like that it does not only say if it is numeric or not but filter all other smybols out, too?
Depending on what you want precisely:
disallow user input not fulfilling certain rules
use validators in forms
use asserts in entities
chenge user input in case it's wrong
use viewransformers in forms
use event listeners in forms
use event listeners for doctrine
change data that already exists in the database
use filters in twig
create a command to execute from commandline
You can also try http://php.net/manual/ro/filter.filters.sanitize.php
I have built quite big apps with Symfony and never needed such a feature. Filters are mostly used in views anyway. Symfony comes with Twig, which has filters, that can be chained, and you can write your own filters. But if you need filters in the backend to do some background processing, you can accomplish it the way you suggested.
I suggest you write an interface and use a factory pattern, so you set a standard if you make many filters, so it will be easier to make the chaining work;)
After the answers and searching i got to the following conclusion.
There is no concept for this for now in Symphony 2.
You have to write it on your own.
Related
I am writing a module(frontend extjs 4.2.1, backend asp.net mvc with the EF). I meet a little problem:
when the user clicks the search button, a panel of extjs will be displayed and he/she can fill some blanks inside the textfield. after the filter information was submitted, the sever side will use appropriate c# code to deal with it to filter some records from the mssql database, here is my problem:
if the user inserts nothing into the field, the standard and best practice will be that this field will be neglected, however, the blank textfield's value will be '' which I can not use this as the filter string, for instance:
there is a textfield named "sex", if the use types nothing into the field, the value passed to server will be '', if i write the lambda expression in this way:
var filter = x=>x.sex ==""; Apparently it will not work. You may say that i can use if-else to condition out the stuff. but if i have numerous fields, using the if-else will be really waste of time.
so, what is the best practice to do this
There are various ways to write this condition, but what you're talking about is a condition so it's not really "a waste of time" to write the code for it.
For example, if you have an IEnumerable<T> and you want to filter it, you might do something like this:
if (string.IsNullOrWhitespace(someFieldValue))
result = result.Where(x => x.SomeField.Equals(someFieldValue));
Or if you're building up expressions, you might conditionally define the expression. Which might look something like this (this is entirely freehand, so I'm not sure it would work like this, but you get the idea):
var filter = string.IsNullOrWhitespace(someFieldValue) ?
x => true :
x => x.SomeField.Equals(someFieldValue);
You can abstract this behind some private helper methods so that consuming code is a bit cleaner, you can refactor commonly-handled filters to reduce duplication, etc. But at the end of the day the logic your code is expressing is:
In a specific known state, do one thing. In other states, do something else instead.
That's a conditional statement.
It can be prevented at client side before request submitted to server.
At server side , You can abstract validation part from service layer.
In my Typical Spring MVC application -
1.Request goes to controller.
2.Controller delegates to Validator.
3.If success, controller delegates to service layer.
4.If failure, controller redirects user to error page.
I'm trying to use custom values in a choice form type which gets its data from a database query that needs post-processing. For this reason I opted to use the choice_list option and extending Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList\ChoiceList. The problem is that I need custom index/value for the resulting dropdown instead of the default 0-indexed style. 0-index doesn't work form me as I will access the values using Javascript and need the data I retrieved from the database.
I already tried replacing the createIndex() method in the ChoiceList class but to no avail :-(
Any tips?
I can't believe it...I have tried the whole day and couldn't find the answer. 5 Minutes after having published the question, I solved it.
For future research:
You need to overwrite the createValue() method in the Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList class.
I am porting a legacy application to Symfony2 and I am struggling because routing doesn't include query string parameters. Some quick examples: Suppose you have a search page for books where you can filter results based on criteria:
http://www.bookstore.com/books?author=Stephen+King&maxPrice=20
The nice thing about query string parameters in a case like this is you can have any number of filters, use the ones you want for any given request, and not crowd the URL with filters you're not using.
Let's say we rewrote the routing for the above query using the Symfony2 routing component. It might look like this:
http://www.mybookstore.com/book/any_title/stephen%20king/any_release_date/max_price_20/any_min_price/any_format/any_category
Even not taking into account how arbitrarily long an unclean that URL is I still don't think it is as intuitive because each 'segment' of that route is not a key value pair but instead just a value (e.g. author=Stephen+King > /stephen%20king/).
You can of course access query string parameters in the controller by passing the Request object into the action method (e.g. indexAction(Request $request) {) but then validating them and passing them into other parts of the application becomes a hassle (i.e. where I find myself now). What if you are using the Knp Menu Bundle to build your sidebar and you want parts to be marked as .current based on query string parameters? There is no functionality for that, just functionality to integrate with Symfony2 routes.
And how to validate that your query string parameters are acceptable? I am currently looking at validating them like a form to then pass them into the database to generate a query. Maybe this is the way the Symfony2 team envisioned handling them? If so I'd just really like to know why. It feels like I'm fighting the application.
I ended up actually asking Fabien this question at Symfony Live San Francisco 2012. There was another talk at the same conference in regards to this question and I will share with you the slides here:
http://www.slideshare.net/Wombert/phpjp-urls-rest#btnNext
Basically in the slides you can see that the author agrees with me in that query string parameters should be used for filtering. What they should not be used for is determining a content source. So a route should point to a product (or whatever) and query string parameters should then be used in your controller to apply whatever logic you require to filter that content source (as per Fabien).
I ended up creating an entity in my application that I bind all my query string parameters to and then manipulate, much the same way forms are handled. In fact when you think about it it's basically the same thing.
Like in Symfony1, query strings are independent from the route parameters.
If you have a path defined as #Route("/page/{id}", name="single_page"), you can create a path in your view like this:
{{ path('single_page', { id: 3, foo: "bar" }) }}
The resulting URL will be /page/3?foo=bar.
I'm currently using Drupal Views 2 to build custom views. This works fine so far, if there wasn't a feature needed: One should be able to filter the results by different fields via URL, in the form of:
http://domain/node/M/[key]:[value],[key2]:[value2],...,[keyN]:[valueN]
The key names are fixed and may not be altered.
I tried hooking hook_views_query_alter() and hook_views_pre_render() to generalize this for all views, evaluating the given filterset, but to no satisfying end, as i could not get hold of the query used to build the view (I could not alter it in the proper way, as i do not know the field names in the query).
The question is, if there is a nicer way to implement such a filterset.
thanks in advance,
flo
Looking at the comments you seem to want not only url arguments but url arguments in a custom format.
I would firstly urge you to drop your format and use the standard views argument format, this will be more standards compliant and save you a lot of headache.
If you want to use that paticular format you are going to have to write some custom code in a module.
Register a callback using hook_menu().
In that callback use arg() and decode your arguments.
Pass the arguments to views_embed_view(). as shown here
I am building a site in which we are making moderate use of email templates. As in, HTML templates which we pass tokens into like {UserName}, {Email}, {NameFirst}, etc.
I am struggling with where to store these, as far as best practice goes. I'll first show the approach I took, and I'd be really excited to hear some expert perspective as a far as alternate approaches.
I created HTML templates in a folder called /Templates/.
I call a static method in my service layer, which takes in the following arguments:
UserName
UserID
Email
TemplatePath ("~/Templates")
Email Subject
Within the service layer I have my static method SendUserEmail() which makes use of a Template class - which takes a path, loads it as a string, and has a AddToken() Method.
Within my static SendUserEmail(), I build the token list off of the method signature, and send the email.
This makes for a quite long method call in my actual usage, especially since I am calling from the web.config the "TemplatePath", and "Email Subject". I could create a utility that has a shorter method call than the ConfigurationManager.AppSettings, but my concern is more that I don't usually see method signatures this long and I feel like it's because I'm doing something wrong.
This technique works great for the emails I have now, which at the most are using the first 3 tokens. However in the future I will have more tokens to pass in, and I'm just wondering what approach to take.
Do I create methods specific to the email needing to be sent? ie. SendNewUserRegistration(), SendMarketingMaterial(), and each has a different signature for the parameters?
I am using ASP.NET Membership, which contains probably the extend of all the fields I'll ever need. There are three main objects, aspnet_User, aspnet_Mebership and aspnet_profile. If it was all contained in one object, I would have just passed that in. Is there performance concerns with passing in all 3, to get all the fields I need? That is versus just passing in aspnet_User.UserID, aspnet_User.Email, etc?
I could see passing in a dictionary with the token entries, but I'm just wondering if that is too much to ask the calling page?
Is there a way to stick these in a config file of it's own called Templates.config, which has tags like -
<Templates>
<EmailTemplate Name="New User Registration">
<Tokens>
<UserName>
<UserID>
<Email>
</Tokens>
<Message Subject="Hi welcome...">
Hi {UserName}...
</Message>
</EmailTemplate>
</Templates>
I guess the main reason I'm asking, is because I'm having a hard time determining where the responsibility should be as far as determining what template to use, and how to pass in parameters. Is it OK if the calling page has to build the dictionary of TokenName, TokenValue? Or should the method take each in as a defined parameter? This looks out of place in the web.config, because I have 2 entries for and , and it feels like it should look more nested.
Thank you. Any techniques or suggestions of an objective approach I can use to ask whether my approach is OK.
First of all I would like to suggest you to use NVelocity as a template engine. As for main problem I think you can create an abstract class MailMessage and derive each one for every needed message (with unique template). So you will use this like following:
MailMessage message = new UserRegistrationMessage(tokens);
//some code that sends this message
Going this way you force each concrete XXXMessage class to be responsible for storing a template and filling it with the given tokens. How to deal with tokens? The simpliest way is to create a dictionary before passing it to the message, so each concrete message class will know how to deal with passed dictionary and what tokens it should contain, but you also need to remember what tokens it should contain. Another way (I like it more) is to create a general abstract type TokenSet and a derived one for every needed unique set of tokens. For example you can create a UserMessageTokenSet : TokenSet and several properties in it:
UserNameToken
SomeUserProfileDataToken
etc. So using this way you will always know, what data you should set for each token set and
UserRegistrationMessage will know what to take from this tokenSet.
There are a lot of ways to go. If you will describe you task better I think I will try suggest you something more concrete. But general idea is listed above. Hope it helps =)