This is going to be a short, nevertheless complicated question. Let me try and explain what I am trying to accomplish.
I've got a config file config.yml
# src/Company/HappyBundle/Resources/config/config.yml
company_happy:
import:
attachments_path: "#CompanyHappyBundle/Resources/public/attachments"
I'm trying to get the attachments_path parameter in a Command. I do this using the following line:
$this->container->getParameter('company_happy.import.attachments_path');
Now, how can I convert #CompannyHappyBundle to the actual path?
Update
If you have any information on better ways to do this, this is always welcome. What I'm trying to do is to save attachments to the bundle's public folder.
You don't need to store your attachments at the bundle's home directory. Also you have wrong definition for parameter. All parameters in Service container must be located under parameters section.
As you can see here you need to create Form with file field. Then fill this form with Request data and then use move() method upon it to move file in any location you need. The most popular place for it - web/uploads directory.
public function uploadAction()
{
$form = $this->createFormBuilder()
->add('attachment', 'file')
->getForm();
if ($form->isValid()) {
$dir = $this->container->getParameter('kernel.root_dir').'/../web/uploads';
$someNewFilename = '...';
$form['attachment']->getData()->move($dir, $someNewFilename);
// ...
}
// ...
}
Set a value in your parameters.yml as following:
# parameters.yml
parameters:
company_happy.import.attachments_path: "#CompanyHappyBundle/Resources/public/attachments"
Then call it the same in your controller as you currently are.
Related
I have a controller with a supprimer action.
I can add files and delete them from the database.
As I followed the Symfony doc to create an uploader file, I also created in my services.yml this route
parameters:
repertoire_soumissions: '%kernel.project_dir%/public/uploads/LettresSoumissios'
My problem
When I delete my file with my supprimer action, it's fine it deletes it in my database. But not in my folder /public/uploads/LettresSoumissions. I tried to find a way to be able to delete them in my folder too, but couldn't succeed it.
I tried also with a Filesystem() to remove them, but I've must have written it badly.
Here is my action in my controller class
/**
* #Route("admin/soumission/{id}/supprimer", name="supprimer_soumission")
*/
public function supprimerSoumission(Soumission $soumission, ObjectManager $manager){
$lettresoumission= $soumission->getLettreSoumission();
$filesystem = new Filesystem();
$path='%kernel.project_dir%/public/uploads/LettresSoumissios/'.$lettresoumission;
$filesystem->remove($path);
$manager->remove($soumission);
$manager->flush();
$this->addFlash('success','Soumission supprimer !!');
return $this->redirectToRoute('soumission');
}
Could it be due to a mispelling in the path name?
$path='%kernel.project_dir%/public/uploads/LettresSoumissioNs/'.$lettresoumission;
Missing a N letter.
Your problem is this line:
$path='%kernel.project_dir%/public/uploads/LettresSoumissios/'.$lettresoumission;
The parameter above is simply a string with value:
%kernel.project_dir%
You need a way to retrive the value of the parameter.
A clean way would be to inject the parameter value in the controller.
Define your Controller as a service in your service.yaml:
Namespace\NameOfTheController:
arguments:
- '%kernel.project_dir%'
tags: [controller.service_arguments]
Inject the value in the Constructor of your Controller:
private $kernelRoot;
public function __construct(string $kernelRoot)
{
$this->kernelRoot = $kernelRoot;
}
Now change your code-line to:
$path=$this->kernelRoot.'/public/uploads/LettresSoumissios/'.$lettresoumission;
to clarify:
You said:
I also created in my services.yml this route
parameters:
repertoire_soumissions: '%kernel.project_dir%/public/uploads/LettresSoumissios'
This is no service or route declaration, this is just a parameter => value mapping.
I have a random name.yml file inside lets say my src/AppBundle/Controller folder. The content inside the YML file is simple:
name: utkarsh
I need to access this from my controller, and have tried to fetch them with
$name = $this->getName('name');
from within my controller file. When I try this, I get this error message:
Attempted to call an undefined method named "getName" of class "AppBundle\Controller\DefaultController".
What is the correct way to do this?
If it's just going to be a general file, and wouldn't better be part of the framework's configuration (for example, in the parameters.yml file), you can parse/read the file using the Yaml component, which is already used by the Symfony framework.
use Symfony\Component\Yaml\Yaml;
$values = Yaml::parse(file_get_contents('/path/to/name.yml'));
echo $values['name'];
If the file you are loading is in the same directory as the code that is running it, you can use the PHP Automagic constants - __DIR__, file_get_contents(__DIR__ . '/name.yml'), or use it as a relative base to work from.
Don't just put your YML file in the Controllers folder. Instead, move your YML file into your bundles' config directory. See below,
AppBundle\Resource\config\abc.yml
Then, import this file in your services.yml file. See below,
imports:
- { resource: abc.yml }
And, make sure you abc.yml file will have a structure like this,
parameters:
name: utkarsh
Finally, you can access this parameter inside the Controller by calling like this,
$this->container->getParameter('name');
I hope this helps :)
Cheers!
I'm using Symfony2 to access an API. I have a controller that initializes the Oauth and another that is for the Callback. Instead of manually typing out the api key, and other variables into these controllers, I want to have a single "configuration" file that I can include in all relevant locations (ie, the Oauth controller and OauthCallback controller).
How do I go about doing this? Should I add more lines to the config.yml or should I just create a new file called config.php and include it? With normal ol' php it'd be an easy require_once but since this is a framework, I want to make sure I'm doing it the "right" way.
Thanks!
Use parameters in parameters.yml or config.yml file.
parameters:
my_api_key: 1234
In controller get like that:
$apiKey = $this->container->getParameter('my_api_key');
IMO, you should write it in the config.yml. Remember that you can write other parameters and include it in the main config.yml with
imports:
- { resource: mi-file.extension}
In the controller, you can get this parameters with
$var= $this->container->getParameter('name_parameter');
For my AppBundle (THE APPLICATION ITSELF, NOT A REUSABLE BUNDLE) I have a configuration parameter that is a path.
I'd like to be sure the path ends with a /.
In this moment I have a method in the entity that uses this path (yes is an entity and not a controller) adjust the configuration parameter with a code like this:
public function buildLogoFolder($folder)
{
// Replace the placeholder with the current Entity's URL
$folder = str_replace('{entity_domain}', $this->getDomain()->getCanonical(), $folder);
$folder = rtrim(ltrim($folder, '/'), '/') . '/';
return $folder;
}
As the $folder parameter comes from the config.yml file I'd like to move outside of the entity this adjustment.
I think I should use a solution similar to the one suggested here, that is the use of the DependencyInjection component.
I think the process is very similar to the loading of a configuration file for a new bundle as explained in the Symfony's documentation but I'm not sure on how to proceed.
Is there someone who can put me on the right way?
I'd like to automate the process. I want read the folder configuration parameter value and then adjust it with the method I wrote above.
I want to be sure that the folder parameter configured ever ends with a trailing slash, also if the developer didn't write it in the configuration.
So, If the developer write something like path/to/folder the resulting configuration parameter is automatically adjusted to path/to/folder/.
I'm trying to send a variable to a twig file which is not in the typical location, Usually I'm loading views by specifying their path through the Bundle but the file I want to send a variable to is not, hierarchically, on the same level as the other twig templates.
I've a controller which looks like the following:
public function fooAction(Request $request)
{
*//Query*
return $this->render('Bundle:file.html.twig', array('varToSend' => $queryResult));
}
I'm pretty sure the Bundle:file.html.twig is wrong but I don't know how else to specify the relevant path in twig.
Twig you would get from container would not work with arbitrary paths, but you can initialize your own twig:
$twig = new \Twig_Environment(new \Twig_Loader_String());
$rendered = $twig->render(
file_get_contents('/path/to/your/file.html.twig'),
array('varToSend' => $queryResult)
);
If you need this in more than one place, consider making it a Symfony service in order to not initialize Twig Environment every time.
Note that renderer in this case won't have any of Symfony's Twig Extensions, you'll have to add them manually.
If possible, try to avoid this, and put templates into app/Resources/views or src/AppBundle/Resources/views directories.
You have to use a path like that :
return $this->render('Bundle:Something:file.html.twig', array(
'varToSend' => $queryResult
));
And put your file in this folder :
src/Bundle/Resources/views/Something/file.html.twig