I am trying to run a command from a controller but it does not work. This is my code:
$email = $request->get('email');
if (empty($email))
$email = $request->get('nombres');
if (empty($password))
$password = '123456';
$application = new Application($this->container->get('kernel'));
$application->setAutoExit(false);
$input = new ArrayInput(array(
"command" => "fos:user:create",
"username" => $username,
"email" => $email,
"password" => $password));
$output = new ConsoleOutput();
$retval = $application->run($input, $output);
var_dump(stream_get_contents($output->getStream()));
die();
Simply it does nothing, #retval is 1 and the $output var is empty.
Any help will be appreciated
Thanks
Jaime
Basically you should not use command in controllers. Console command and Controller are two different delivery layers.
Please use services (so you can use it in controllers and in commands) for fos:user:create you can use something like that:
$manipulator = $this->container->get('fos_user.util.user_manipulator');
$manipulator->create($username, $password, $email, $active = true, $superadmin = false);
Related
I'm storing page code in database so that the admin will be able to rearrange sections and edit content.
I'm organizing all the code in the controller before sending a response that has all the code for the page.
I've seen this question: How to render Twig template from database in symfony2 and it is not the same as the one I'm asking
I'd like to be able to have a code in the database like "{% include 'tmp/header.html.twig' %} and have the twig run that.
So far twig gives an error that 'Template "tmp/header.html.twig" is not defined in __string_template__59b79c6909e3d467bcae264ee8ebdf3697db94a9096b7457d0c43bac9c0d8fb1 at line 345.'
Here is a test page:
/**
* #Route("/test/for/conservatoire/of/music", name="test")
*/
public function test(PageRepository $pageRepo, SectionRepository $sectionRepo): Response
{
// this page
$page = $pageRepo->findOneByName('about');
// html is now empty
$html = "<html><body><h1>Hello pal</h1></body></html>";
// THIS IS THE PROBLEMATIC PART
$html .= '{% include("tmp/header.html.twig") %}';
$variables = ['this' => 'that'];
$loader = new \Twig\Loader\ArrayLoader([
'test.html.twig' => '{{ include(template_from_string(html)) }}',
]);
$twig = new \Twig\Environment($loader);
$profile = new \Twig\Profiler\Profile();
$context = new Routing\RequestContext();
$router = $this->get('router');
$routes = $router->getRouteCollection();
$generator = new Routing\Generator\UrlGenerator($routes, $context);
$versionStrategy = new StaticVersionStrategy('v1');
$defaultPackage = new Package($versionStrategy);
$namedPackages = [
'img' => new UrlPackage('http://img.example.com/', $versionStrategy),
'doc' => new PathPackage('/somewhere/deep/for/documents', $versionStrategy),
];
$packages = new Packages($defaultPackage, $namedPackages);
// this enables template_from_string function
$twig->addExtension(new \Twig\Extension\StringLoaderExtension());
// this enables debug
$twig->addExtension(new \Twig\Extension\DebugExtension());
// this enables {{asset('somefile')}}
$twig->addExtension(new AssetExtension($packages));
// this enables {{path('someroute')}}
$twig->addExtension(new RoutingExtension($generator));
// I NEED ONE THAT ENABLES {% include('tmp/header.html.twig') %}
// so far I'm getting this error:
// Template "tmp/header.html.twig" is not defined in __string_template__59b79c6909e3d467bcae264ee8ebdf3697db94a9096b7457d0c43bac9c0d8fb1 at line 345.
$response = new Response();
$response->setContent($twig->render('test.html.twig', ['html' => $html]));
$response->setStatusCode(Response::HTTP_OK);
// sets a HTTP response header
$response->headers->set('Content-Type', 'text/html');
// return response
return $response;
}
It doesn't work even when the include is added separately like so:
$loader = new \Twig\Loader\ArrayLoader([
'test.html.twig' => '{% include("tmp/header.html.twig") %}{{ include(template_from_string(html)) }}',
]);
Error: Template "tmp/header.html.twig" is not defined in test.html.twig at line 1.
I finally found out the way to do it.
I only needed to add the page to be included to the ArrayLoader like so:
use Symfony\Component\Routing;
use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy;
use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\UrlPackage;
use Symfony\Component\Asset\PathPackage;
use Symfony\Component\Asset\Packages;
use Symfony\Bridge\Twig\Extension\AssetExtension;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
/**
* #Route("/test/for/conservatoire/of/music", name="test")
*/
public function test(PageRepository $pageRepo, SectionRepository $sectionRepo): Response
{
// this page
$page = $pageRepo->findOneByName('about');
// html is now empty
$html = "<html><body><h1>Hello from test</h1></body></html>";
// THIS WAS THE PROBLEMATIC PART
$html .= '{{ include("header.html.twig") }}';
$variables = ['this' => 'that'];
// HERE IS THE SOLUTION -> ADD THE NEW TEMPLATE TO THE ARRAY LOADER
$loader = new \Twig\Loader\ArrayLoader([
'test.html.twig' => '{{ include(template_from_string(html)) }}',
'header.html.twig' => "<html><body><h1>Hello from {{name}}</h1></body></html>",
]);
$twig = new \Twig\Environment($loader);
$profile = new \Twig\Profiler\Profile();
$context = new Routing\RequestContext();
$router = $this->get('router');
$routes = $router->getRouteCollection();
$generator = new Routing\Generator\UrlGenerator($routes, $context);
$versionStrategy = new StaticVersionStrategy('v1');
$defaultPackage = new Package($versionStrategy);
$namedPackages = [
'img' => new UrlPackage('http://img.example.com/', $versionStrategy),
'doc' => new PathPackage('/somewhere/deep/for/documents', $versionStrategy),
];
$packages = new Packages($defaultPackage, $namedPackages);
// this enables template_from_string function
$twig->addExtension(new \Twig\Extension\StringLoaderExtension());
// this enables debug
$twig->addExtension(new \Twig\Extension\DebugExtension());
// this enables {{asset('somefile')}}
$twig->addExtension(new AssetExtension($packages));
// this enables {{path('someroute')}}
$twig->addExtension(new RoutingExtension($generator));
$response = new Response();
$response->setContent($twig->render('test.html.twig', ['html' => $html, 'name' => 'header']));
$response->setStatusCode(Response::HTTP_OK);
// sets a HTTP response header
$response->headers->set('Content-Type', 'text/html');
// return response
return $response;
}
I'm stuck. I'm using mailer from symfony with gmail generated password, and i keep on getting this error.
Would anyone have an idea as of why?
here's my controller:
public function new(Request $request): Response
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($contact);
$entityManager->flush();
$name = ($form['Name']->getData());
$email = ($form['Email']->getData());
$subject = ($form ['Subject']->getData());
$content = ($form['Content']->getData());
$transport = new GmailTransport('******#*********.org', '******************');
$mailer = new Mailer($transport);
$entityManager = $this->getDoctrine()->getRepository(Subject::class);
$toEmail = $subject -> getEmail();
$realSubject = $subject -> getName();
$message = (new TemplatedEmail())
->from($email)
->to($toEmail)
->subject($content)
// path of the Twig template to render
->htmlTemplate('mail/newContact.html.twig')
/* pass variables (name => value) to the template
->context([
'expiration_date' => new \DateTime('+7 days'),
'username' => 'foo',*/
;
$mailer->send($message);
return $this->redirectToRoute('home');
}
return $this->render('contact/new.html.twig', [
'contact' => $contact,
'form' => $form->createView(),
]);
}
and i've got this in the .env
###> symfony/mailer ###
MAILER_DSN=smtp://******#*********.org:******************#gmail
###< symfony/mailer ###
does anyone have an idea?
Thank you
Here is the funcion im using
public function sendCredentialsEmailMessage(UserInterface $user)
{
$template = 'Emails/afterRegister.html.twig';
$rendered = $this->templating->render($template, array(
'user' => $user,
));
$this->sendEmailMessage($rendered,
$this->parameters['from_email']['confirmation'], $user->getEmail());
}
Basically I want the auto-mailer to send my template along with the login name. When i create a new user nothing is being sent. My email template is located in app>resources>views>emails>
and this controller file is located in src>myname>userbundle>mailer>
protected function sendEmailMessage($renderedTemplate, $fromEmail, $toEmail)
{
// Render the email, use the first line as the subject, and the rest as the body
$renderedLines = explode("\n", trim($renderedTemplate));
$subject = array_shift($renderedLines);
$body = implode("\n", $renderedLines);
$message = (new \Swift_Message())
->setSubject($subject)
->setFrom($fromEmail)
->setTo($toEmail)
->setBody($body);
$this->mailer->send($message);
}
Also this works for sure:
public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['resetting.template'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()),
UrlGeneratorInterface::ABSOLUTE_URL);
$rendered = $this->templating->render($template, array(
'user' => $user,
'confirmationUrl' => $url,
));
$this->sendEmailMessageCustom($rendered, $this->from, (string)$user->getEmail(),'Password resseting');
}
public function contactAction(Request $request)
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$em = $this->getDoctrine()->getManager();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$name = $form['name']->getData();
$email = $form['email']->getData();
$subject = $form['subject']->getData();
$message = $form['message']->getData();
$contact->setName($name);
$contact->setEmail($email);
$contact->setSubject($subject);
$contact->setMessage($message);
}
$message = \Swift_Message::newInstance()
->setSubject($subject) // here the error
->setFrom('jardisindustrie#gmail.com')
->setTo($email)
->setBody($this->renderView('sendmail.html.twig', array(
'name' => $name,
'message' => $message,
'email' => $email,
'subject' => $subject)), 'text/html');
$this->get('mailer')->send($message);
return $this->render('SDCoreBundle::contact.html.twig', [
'form' => $form->createView()
]);
}
I don't know why but it did work good and this afternoon I try again and I have the error message...
I want to make a contact form with swiftmailer, normally I do like that but here i don't know why there is a trouble.
Thanks for your help
You are missing the complete error message. But from the first look, the code that creates and sends a message should be inside the if($form->isSubmitted() && $form->isValid()) block, otherwise it will try to send a message when the form is not submited but only being displayed.
I want do one functional test over on service Symfony2. The idea is call before to the controller and after that, load the service with the function. The function is this one:
function save($title,$description,$setId,$html,$validate,$articles){
$articles = explode(',', $articles);
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
}else{
$profileId = $this->container->get('security.context')->getToken()->getUser()->getId();
$userName = $this->container->get('security.context')->getToken()->getUser()->getUserName();
}
}
and now my test code is :
$client = static::createClient();
$crawler = $client->request('GET','/sets/save',
array(
"title"=>"rtyui",
"description"=>"aksdjhashdkjahskjdh",
"set_id"=>"",
"html"=>"",
"validate"=>1,
"articels"=>"3,4"
)
);
but doesn't work already that I have this lines:
if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
throw new \Exception("Not allowed");
Now, the question is, how i can do the validation process? I've tried to do this validation process as show the documentation:
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'pa$$word',
));
but I got the same error.
Also you can login user by Security Token:
$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
new UsernamePasswordToken(
$user, null, 'main', $user->getRoles()
)
);
Where:
$user - instance of User entity with role ROLE_USER,
main - your security provider name