How to set external environment variable as array?
If I have environment variable
SYMFONY__NSQLOOKUPD__HOSTS=["localhost:4161"]
and in config.yml:
socloz_nsq:
lookupd_hosts: %nsqlookupd.hosts%
Then I got an error:
Invalid type for path "socloz_nsq.lookupd_hosts". Expected array, but got string
I've found solution. Here it is:
in config.yml add to the imports section:
imports:
- { resource: parameters.php }
then create parameters.php file at the same directory where config.yml exists, and look at the following example:
<?php
$nsqlookupdhosts = getenv('SYMFONY__NSQLOOKUPD__HOSTS');
$nsqdhosts = getenv('SYMFONY__NSQD__HOSTS');
$container->setParameter('nsqlookupd.hosts.parsed', explode(',', $nsqlookupdhosts));
$container->setParameter('nsqd.hosts.parsed', explode(',', $nsqdhosts));
use comma as delimiter in environment variable (you are not restricted to comma, use any)
SYMFONY__NSQLOOKUPD__HOSTS=localhost:4161,some.server:2222
You can use a built-in "json" environment variable processor to decode a JSON string into an array:
SYMFONY__NSQLOOKUPD__HOSTS='["localhost:4161"]'
$nsqlookupdhosts: '%env(json:SYMFONY__NSQLOOKUPD__HOSTS)%'
Related
I have a specific variable in my .env.dev.local
SRV_INST=s01
Is there a way to use custom env variables in services.yaml in a conditional way similar to when#dev ? I would like to define some services only when SRV_INST=s01 (something like when %env(SRV_INST)% === 's01').
I can use services.php, but I wanted to know if there's a way to do this in services.yaml
you found a solution - but for anyone else, there are multiple other solutions for this:
services:
App\Mailer:
# the '#=' prefix is required when using expressions for arguments in YAML files
arguments: ["#=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"]
or
services:
# ...
App\Mail\MailerConfiguration: ~
App\Mailer:
# the '#=' prefix is required when using expressions for arguments in YAML files
arguments: ['#=service("App\\Mail\\MailerConfiguration").getMailerMethod()']
you can find more information at https://symfony.com/doc/current/service_container/expression_language.html
Okay, I solved this by importing a .php additional configuration file.
// config/services.yaml
imports:
- { resource: 'services_conditional.php' }
And the services_conditional.php file:
// config/services_conditional.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
use SomeCustom\Service\CustomDoubleBla;
return function (ContainerConfigurator $configurator) {
$services = $configurator->services();
if (!empty($_ENV['SRV_INST']) && $_ENV['SRV_INST'] === 's01') {
$services->set(CustomDoubleBla::class)
->decorate('custom_single_bla.service')
// pass the old service as an argument
->args([service('.inner')]);
}
};
I currently have a value that is stored as an environment variable the environment where a jupyter server is running. I would like to somehow pass that value to a frontend extension. It does not have to read the environment variable in real time, I am fine with just using the value of the variable at startup. Is there a canonical way to pass parameters a frontend extension on startup? Would appreciate an examples of both setting the parameter from the backend and accessing it from the frontend.
[update]
I have posted a solution that works for nbextentions, but I can't seem to find the equivalent pattern for labextensions (typescript), any help there would be much appreciated.
I was able to do this by adding the following code to my jupter_notebook_config.py
from notebook.services.config import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'variable_being_set': value})
Then I had the parameters defined in my extension in my main.js
// define default values for config parameters
var params = {
variable_being_set : 'default'
};
// to be called once config is loaded, this updates default config vals
// with the ones specified by the server's config file
var update_params = function() {
var config = Jupyter.notebook.config;
for (var key in params) {
if (config.data.hasOwnProperty(key) ){
params[key] = config.data[key];
}
}
};
I also have the parameters declared in my main.yaml
Parameters:
- name: variable_being_set
description: ...
input_type: text
default: `default_value`
This took some trial and error to find out because there is very little documentation on the ConfigManager class and none of it has an end-to-end example.
How can i get the base path of drupal installation in twig file?
For example i need to get http://localhost/drupal/.
I have tried
{{ base_path }}
But it's returning empty.
{{ directory }}
This is returning the theme path. but i need the base path to complete the url. Is there any way to do this?
#Ditto P S To get base path on twig you declare a variable in .theme file inside a preprocess
andthen simply use 'base_path_success' variable in twig as
{{ base_path_success }}
You can declare variable inside any of the preprocess like
function ttnd_preprocess_node(&$variables) {}
OR
function ttnd_preprocess_block(&$variables) {}
Here ttnd is themename.
For more information you can use the below link
https://drupal.stackexchange.com/questions/205289/base-path-drupal-8
You can get the hostname, "localhost/drupal/", directly from the getHost() request:
$host = \Drupal::request()->getHost();
In some cases you might want to get the schema as well, fx http://localhost/drupal/:
$host = \Drupal::request()->getSchemeAndHttpHost();
Source : https://drupal.stackexchange.com/a/202811/
My config is
jms_serializer:
metadata:
auto_detection: true
directories:
NameOfBundle:
namespace_prefix: ""
path: "#VendorNameOfBundle/Resources/config/serializer"
My YML file named Entity.Project.yml contains
Vendor\NameOfBundle\Entity\Project:
exclusion_policy: ALL
properties:
id:
expose: true
I am loading the serializer like so from within a Controller
$serializer = SerializerBuilder::create()
->configureListeners(function(EventDispatcher $dispatcher) {
$dispatcher->addSubscriber(new ProjectSubscriber($this->container));
})
->addDefaultListeners()
->build();
This completely ignored my YML file and exposes all fields from the Project. I have cleared the cache.
But if I use this instead without the custom subscriber, then the exclusions work
$serializer = $this->get("jms_serializer");
Even explicitly adding a dir does not work either
$serializer = SerializerBuilder::create()
->configureListeners(function(EventDispatcher $dispatcher) {
$dispatcher->addSubscriber(new ProjectSubscriber($this->container));
})
->addDefaultListeners()
->addMetadataDir(realpath($this->get('kernel')->getRootDir()."/../") . '/src/Vendor/NameOfBundle/Resources/config/serializer')
->build();
The docs are not clear on how this path should befined. The above method does not error, but does not pull in the YML files. The below method errors and says the directory does not exist;
$serializer = SerializerBuilder::create()
->configureListeners(function(EventDispatcher $dispatcher) {
$dispatcher->addSubscriber(new ProjectSubscriber($this->container));
})
->addDefaultListeners()
->addMetadataDir('#VendorNameOfBundle/Resources/config/serializer')
->build();
How do I make the JMS Serializer look at my YML file in order to exclude the fields and also use the Subscriber?
As i see from documentation you need to setup your Yaml files:
it is necessary to configure a metadata directory where those files are located:
$serializer =
JMS\Serializer\SerializerBuilder::create()
->addMetadataDir($someDir)
->build();
For more information read manual.
This was helpful Using JMSSerialize to serialize Doctrine2 Entities that follow SimplifiedYamlDriver convention
It would appear that the file names needs to be completely different if you do not specify a namespace. I never thought to specify a namespace as this is not mentioned in the main docs.
If there is no namespace then the addMetaDir usage is fine but you also need to make sure your file names look like this
Vendor.NameOfBundle.Entity.Project.yml
How do i refer to a data file in the services.yml, which is located in the same or any bundle?
Im shipping a csv-file which i would like to inject as argument.
It works when i use the direct path:
mybundle.data.csv: %kernel.root_dir%/../vendor/mybundle/my-bundle/mybundle/MyBundle/Resources/data/data.csv
This is pretty verbose and unflexible and thus i am looking for a resolver like:
data.csv: "#MyBundle/Resources/data/data.csv"
But this is not working:
... has a dependency on a non-existent service
"mybundle/resources/data/data.csv".
any ideas?
#-escaping in yaml is supported now
https://github.com/symfony/symfony/issues/4889
You can use it like this
data.csv: "##MyBundle/Resources/data/data.csv"
First of all: in the YAML service and parameter definitions # also refers to another service. That is why your code does not work.
Basically you have two possibilities. The first and simple one is to use a relative path in your bundles services.yml and append it in your CSV class.
For example:
# src/Acme/DemoBundle/Resources/config/services.yml
parameters:
data.csv: "Resources/data/data.csv"
In the class you want to read the CSV file:
// src/Acme/DemoBundle/Import/ReadCsv.php
...
class ReadCsv
{
...
public function __construct($csvFile)
{
$this->csvFile = __DIR__.'/../'.$csvFile;
}
...
}
The other possibility is to make the filename of the CSV file configurable via config.yml (see this article in the Symfony2 cookbook) and insert a special placeholder in the config value that you replace in your AcmeDemoBundleExtension class:
// src/Acme/DemoBundle/DependencyInjection/AcmeDemoBundleExtension.php
...
public function load(array $configs, ContainerBuilder $container)
{
...
$container->setParameter('acme_demo.csv_file', str_replace('__BUNDLE_DIR__', __DIR__'./.., $config['csv_file']);
}
...
Your config.yml would look like:
# app/config/config.yml
acme_demo:
csv_file: __BUNDLE_DIR__/Resources/data/data.csv