Routing condition with parameter in Symfony - symfony

I have a route with a parameter {id} on which I want to apply a condition. Only if {id} contains more than 3 characters, this route should be available. I read about conditions in routes both in the documentation and in a similar question. What I tried:
/**
* #Route("/{id}", name="some_route", condition="strlen(id) > 3")
*/
I also tried with requirements instead of condition and tried {id} instead of id. No luck. The error that is show is:
The function "strlen" does not exist around position 1 for expression strlen(id) > 3.
How to solve this issue?

In this case, using regular expression is the best option. Take a look in the PHP documentation to find out more (Here is the link). And suppose the characters you are referring to are alphanumeric characters (I added the - and _).
<?php
// some code ...
/**
* #Route("/{id}", name="some_route", requirements={"id"="[a-zA-Z0-9_-]{3,}"})
*/

Related

Symfony internalization routes with params

I am developing a project in Symfony 4.3. I am trying to create URLs in different languages. I have tried to use this notation:
/**
* #Route({
* "it": "/{_locale}/rassegna/stampa",
* "bg": "/{_locale}/Статии/в/печата"
* }, name="rassegna_stampa", utf8=true)
*/
The problem is that when I try to create a link in a twig to change language, for example:
GO TO BG LANGUAGE
it is rendered in something like:
http://website.it/it/%D0%A1%D1%82%D0%B0%D1%82%D0%B8%D0%B8/%D0%B2/%D0%BF%D0%B5%D1%87%D0%B0%D1%82%D0%B0
So it seems that the translated final part is ok, but the _locale parameter is not matched, as the {_locale} placeholder is filled with the current locale, and not with the locale that I requested in the link. It is 'it' but it should be 'bg'.

Is it possible to make Symfony ignore a double slash in the URL

I'm writing a new endpoint for 3rd party desktop application, and there are several different functions in the application that post to the same endpoint on my Symfony 2.8 server.
Sometimes the desktop application goes to the correct path - example.com/path/to/endpoint. However sometimes it tries to go to add an extra slash in between the domain name and the path - example.com//path/to/endpoint.
I tried to just add an extra route with the double slash in it like this:
/**
* #Route("/path/to/route", name="example_route")
* #Route("//path/to/route", name="example_route_double_slash")
* #Method({"POST"})
*/
Symfony just ignores the double slash when it compiles the routes though, and I end up with 2 of "/path/to/route" if I check my routes with app/console debug:router
By default, the Symfony Routing component requires that the parameters
match the following regex path: [^/]+. This means that all characters
are allowed except /.
You must explicitly allow / to be part of your parameter by specifying
a more permissive regex path.
Your route definition have to use regex :
/**
* #Route("/{slash}/path/to/route", name="example_route_double_slash", requirements={"slash"="\/?"})
*/
I haven't tested the code but it basically says that you are adding an extra parameter that may or may not be a /.
The code snippet is inspired from this one at official docs :
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DemoController
{
/**
* #Route("/hello/{username}", name="_hello", requirements={"username"=".+"})
*/
public function helloAction($username)
{
// ...
}
}
find more here : http://symfony.com/doc/current/routing/slash_in_parameter.html

Theming view for multiple value field

I know this is probably a n00b question but I've searched everywhere for an answer and havent found anything.
I have a CCK multiple value field for "Features" where a product can have a random number of multiple features entered for it. I am editing the view so I can style the output of the features on the product page.
Right now in my view I can output the entire list of features at once using:
<?php print $fields['field_features_value']->content ?>
This will give me a list all the features given for a product. But what I want to do is loop through and pull out each individual feature and format/style it separately. How exactly would I do this?
I ran into this yesterday again, and spent hours trying to Google the syntax, to no avail.
I was able to get this to work, but I must admit it is not the best way. It is duplicating some of the work that Views has already potentially done for us, and should be considered a brute-force approach.
My use case involved theming each filefield file in a node separately, per node-based row:
<?php
// $Id: views-view-field.tpl.php,v 1.1 2008/05/16 22:22:32 merlinofchaos Exp $
/**
* This template is used to print a single field in a view. It is not
* actually used in default Views, as this is registered as a theme
* function which has better performance. For single overrides, the
* template is perfectly okay.
*
* Variables available:
* - $view: The view object
* - $field: The field handler object that can process the input
* - $row: The raw SQL result that can be used
* - $output: The processed output that will normally be used.
*
* When fetching output from the $row, this construct should be used:
* $data = $row->{$field->field_alias}
*
* The above will guarantee that you'll always get the correct data,
* regardless of any changes in the aliasing that might happen if
* the view is modified.
*/
?>
<?php
$output = explode('|', $output); // I've rewritten the field output in Views like this: [field_portfolio_image-field_name]|[nid]
$paths = $output[0]; // I've set filefield to show file paths rather than the file
$nid = $output[1]; // The NID is all that's really needed for this approach
$node = node_load($nid);
$slots = $node->field_portfolio_image;
foreach($slots as $prop) {
print ''.$prop[data][description].'';
}
?>
I used the Devel module heavily here (image reference for this example attached), in order to get the nested values I needed.
I know there is a better, proper way of doing this, rather than reloading the node data, since views should already have access to this upon page load.
When theming views is too specific I set conditions, relationships, parameters and all the views stuff except fields. The only field I use is node id.
Then when doing the theming I use...
$node = node_load($nid);
... to get the node object. You can inspect the node object with the dpm function that comes with the devel module.
dpm($node);
This "technique" works well for nodes and when you don't care about optimization or speed, because if you are going to do this with 1000 nodes you should load the nodes on batch.

comma separated views list

everyone. I've got a problem with Views 2. I have a view with row's style set to fields (Got only title field). I want to display these titles with comma separated list.
For example:
Kazakhstan, England, China, Korea
tried to do this:
foreach($fields['title']->content as $titles) {
$zagolovki[] = $titles['view'];
}
$title_list = implode(', ', $zagolovki);
print $title_list;
but it doesn't works - says error in argument. Please help me someone to display node titles in views with comma separated list. Thanks!
I quikly took a look in the views-view-fields.tpl.php that comes with the views module and it says
/*
* - $view: The view in use.
* - $fields: an array of $field objects. Each one contains:
* - $field->content: The output of the field.
* - $field->raw: The raw data for the field, if it exists. This is NOT output safe.
* - $field->class: The safe class id to use.
* - $field->handler: The Views field handler object controlling this field. Do not use
* var_export to dump this object, as it can't handle the recursion.
* - $field->inline: Whether or not the field should be inline.
* - $field->inline_html: either div or span based on the above flag.
* - $field->separator: an optional separator that may appear before a field.
* - $row: The raw result object from the query, with all data it fetched.
*/
So I think $fields is what you should iterate over. If you want to debug the structure of your $fields install the devel-module and use dpm() or dsm() to display the content of $field. Maybe take the template you edited (that should be one of the view-module templates in the views/theme folder) and look what happens there.
Where does it say the error occurs, though? nonsenz is probably right that $fields['title']->content is not an array. For debugging only, try adding
print("array content: "+ is_array($fields['title']->content));
before the foreach. If you know that $fields is a small nested structure, you can try a
print(str_replace("\n","<br/>",print_r($fields,true));
to see what exactly is in it, so that you can make verify that what you're trying to iterate over is in fact iterable.
I've created this module:
http://drupal.org/project/views_delimited_list
I'm not too sure about fiddling with the options to create merely a comma-separated list. You should be able to, and if you can't I'll fix it.

How to change the label of the default value (-Any-) of an exposed filter in Drupal Views?

I created a view which has three exposed filters. Everything works fine except the fact that I can neither translate or change the default string (-Any-) for the dropdowns. Is there a way to change this string to something more meaningful like "Please Select" and make it translatable so the German version displays "Bitte wählen"? I have two screen captures that may be helpful:
and
A further improvement would be the ability to change the text "any" to something like "please select a (field name here)" but I am losing hope for that =)
UPDATE
IMPORTANT: On further testing, I found that if you choose to display "-Any-" from "admin/build/views/tools", then THAT IS translatable.
For anyone who wants to just change the value of "- Any -" to something in particular then use a custom module to override that looks like this:
function yourmodulename_form_alter(&$form, $form_state, $form_id) {
if($form_state['view']->name == 'your_view_name_here') {
$form['your_dropdown_name']['#options']['All'] = t('- Type -'); // overrides <All> on the dropdown
}
}
The reason you might want to do this is if you have 3 (for example) dropdowns for 3 separate fields. Then having on them wouldn't be very useful for a user (especially if you are not using labels).
In the code above just remember to change "yourmodulename" to the name of your module.
your_view_name_here should be the name of your view (replace dashes with underscores - for example "property-search-bar" would become "property_search_bar")
And change "your_dropdown_name" to the field name - I found this by using dsm($form) with the devel module installed and enabled. This is usually the field name of your drop down so it might be something like "field_my_custom_value".
Hope this helps anyone who needs it!
Three options:
You could change it with localisation, if you have that enabled already. Introducing localisation only for this string is far too much overhead.
You can change it with a form_alter, if you already alter the form anyway. Introducing a module with a hook_form alter for just one string is way too much (maintainance and performance) overhead.
You coud change it with a simple string override in your settings.php
In Drupal 7 (Drupal6 differs in details only)
/**
* String overrides:
*
* To override specific strings on your site with or without enabling locale
* module, add an entry to this list. This functionality allows you to change
* a small number of your site's default English language interface strings.
*
* Remove the leading hash signs to enable.
*/
$conf['locale_custom_strings_en'][''] = array(
'<Any>' => 'Whatever!',
);
Note though, that this will change every occurrance of the full string <Any> (case sensitive) to Whatever, not just the ones in that single form.
Views exposed filter label is not translatable in D6.
Go to Administer > Site building > Views and select tab tools.
Replace 'Label for "Any" value on optional single-select exposed filters: ' by the translatable '- Any -'.
Important: visit the views with exposed filters in at least one language which isn't your default language.
Then you can translate "- Any -" through Aminister > Site building > Translate interface (case sensitive).
Or you can simply use a line of jQuery code like this:
$(document).ready(function(){
$("#views-exposed-form-url-name-display-name #edit-tid-all a").text("All");
});
The Better Exposed Filter module allows you to change the "-any-" label in a Views exposed filter.
I'd rather go with the simple solution: String Overrides.
With this you simply add a string you want to change on your site, and replace it with anything you want (Strings of course).
May be module https://www.drupal.org/project/views_advanced_labels helps?
I found it, but have not tried it yet.
if ($form['#id'] == 'views-exposed-form-project-search-block-project-search') {
foreach ($form['#info'] as $filter_info) {
$filter = $filter_info['value'];
if ($form[$filter]['#type'] == 'select') {
$form[$filter]['#options']['All'] = $filter_info['label'];
}
}
}
If you use Better Exposed Filters module, go into Exposed Form > Exposed form style: Better Exposed Filters | Settings > look for your field > Advanced Filter Options > put "- Any -|All" in the "Rewrite the text displayed" field.

Resources