Can not use CRUDController - php

I'm using sonata Mongodb AdminBundle for my back-end, in my case I need to create a new action for my user model ( sending a mail to him ), I followed the documentation literally
https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_custom_action.html
but I got a weird error :
Compile Error: Cannot use Sonata\AdminBundle\Controller\CRUDController as Controller because the name is already in use
and this is my CRUDController Code :
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Session\UserBundle\Document\User;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
class CrudController extends Controller
{
public function inscriptionAction()
{
$mail = 'towho#someone.com';
$pinCode = '1klm8';
$sender = 'Mymail#gmail.com';
$dm = $this->get('doctrine_mongodb')->getManager();
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->createUser();
$user->setEmail($mail);
$user->setUsername($mail);
$user->setPlainPassword($pinCode);
$user->setEnabled(true);
$userManager->updateUser($user, true);
$message = \Swift_Message::newInstance()
->setSubject('Test de recrutement')
->setFrom($sender)
->setTo($mail)
->setCharset('utf-8')
->setContentType('text/html')
->setBody(
$this->renderView(
'ATSQuizzBundle:Default:SwiftLayout/createUser.html.twig',
array('user' => $user, 'pinCode' => $pinCode)
)
);
$this->get('mailer')->send($message);
$this->addFlash('sonata_flash_success', 'mail sent to the candidate');
return new RedirectResponse($this->admin->generateUrl('list'));
}
}
any one knows the origin of this error please ?

You have already imported the Controller class. And so you need to rename it in the second case. Override your use-block with next:
use Session\UserBundle\Document\User;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
As you see I deleted first occurrence of Controller class that is not used in your code. But if you have some other code in this file that can use "old" Controller I would recommend you to rename last Controller to BaseController and extend your class from BaseController.

Related

Symfony 5 NormalizerInterface not found

i'm following a tutorial online on how to use Symfony
i followed all the step but for some reason when is try to use NormalizeInterface i get this error :
Cannot determine controller argument for "App\Controller\ApiPostController::index()": the $normalizer argument is type-hinted with the non-existent class or interface: "App\Controller\NormalizerInterface". Did you forget to add a use statement?
I tried multiple solutions and none of them worked
My code is
<?php
namespace App\Controller;
use App\Repository\PostRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer;
class ApiPostController extends AbstractController
{
/**
* #Route("/api/post", name="api_post_index", methods={"GET"})
*/
public function index(PostRepository $postRepository, NormalizerInterface $normalizer )
{
$posts = $postRepository->findAll();
$postsNormalises = $normalizer->normalize($posts, null, ['groups' => 'post:read']);
return $this->render('api_post/index.html.twig', [
'controller_name' => 'ApiPostController',
]);
}
}
Thank you for taking the time to read and thank you for you help in advance
Add use line:
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

laravel mail how to properly implement into the system

So I am trying to implement a command that notifies all users that are subscribes to an event with command that does an check every day. I was reading Laravel mail docs 7.x so there example is about order system where they send the mail with this peace of code
foreach (['taylor#example.com', 'dries#example.com'] as $recipient) {
Mail::to($recipient)->send(new OrderShipped($order));
}
what as it looks takes the email of of the loop and then send an email toward that adress.
So I made a mail class php artisan make:mail NotifyUserOfEvents
and where I made this code
<?php
namespace App\Mail;
use App\Event;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class NotifyUserOfEvents extends Mailable
{
use Queueable, SerializesModels;
protected $event;
public function __construct(Event $event)
{
$this->event = $event;
}
public function build()
{
return $this->view('mails.NotifyUserOfEvents')
->with([
'name' => $this->event->name,
'date' => $this->event->settings->start_date,
]);
}
}
but when I try to call this class with this function
<?php
namespace App\Console\Commands;
use App\Event;
use App\RegistrationEvents;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class NotifyUsersForEvents extends Command
{
protected $signature = 'NotifyUsersForEvents';
protected $description = 'Notify the user for the event. test run with -> php artisan schedule:run';
public function __construct()
{
parent::__construct();
}
public function handle()
{
Log::debug('this works every minute');
$events = Event::query()
->with('settings')
->has('settings')
->get();
foreach ($events as $event) {
$week = Carbon::now()->addWeek();
$sixDays = $week->copy()->subDay();
if (Carbon::create($event->settings->date_start)->between($week, $sixDays)) {
$subscriptions = RegistrationEvents::query()
->where('event_id', $event->id)
->get();
foreach ($subscriptions as $subscription) {
var_dump($subscription->user_id);
$user = User::findOrFail($subscription->user_id);
Mail::to($user->email)->send($event);
var_dump($user->email);
}
}
}
}
}
it returns this error: Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given, called in so do I need to change the way I call the mail class or do I need to add something to the Event Model?
also the event.php
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Event extends Model implements Mailable
{
use SoftDeletes;
public function settings(){
return $this->hasOne('App\EventSettings', 'event_id');
}
}
You must pass to send function an object of your NotifyUserOfEvents, not an Event object.
Try this:
Mail::to($user->email)->send(new NotifyUserOfEvents($event));
Referring to this line:
Mail::to($user->email)->send(new Event($event));
you are creating a new Event passing to the constructor another Event... you probably never define a constructor that accept as first parameter an Event...
But despite that, what's the sense of doing this? To Mail::send you have to pass a Mailable, not an event, and i'm pretty sure you don't need a new event, so i believe you would want to do something like this:
use App\Mail\NotifyUserOfEvents; // or whatever namespace you have to the mail
Mail::to($user->email)->send(new NotifyUserOfEvents($event));
$user = User::find($id);
$email = $user->email;
if(Helper::isValidEmail($email))
{
Mail::send('emails.applicant_reference',
$emailParameters, function($message) use ($email, $name, $subject){
$message->to($email, $name)
->subject($subject);
});
$applicantName = null;
$subject = " Application received for ".$applicantName;
$emailParameters = ["applicantName" => $applicantName, "proposerName" => $proposerName, "seconderName" => $seconderName];
try
{
Mail::send('emails.application', $emailParameters, function($message) use ($applicantName, $subject){
$message->to(['test#gmail.com','test#gamil.com'], " Test Email Function ")
->subject($subject);
});
} catch (Exception $ex){ Log::error("UserController".$ex->getMessage());
}

PHP Cannot redeclare class - Require error - Silex Framework

I'm working on a project, but I have a very annoying problem. I use a PHP file rb.php that contains several important classes for the project (File rb.php of the RedBean ORM, all in one).
The problem is that I can use the file correctly with a require in a special location, but not in another location.
This is my arborescence:
When I go to index.php, everything goes well, i can do require('rb.php');
<?php
require_once 'vendor/autoload.php';
require('rb.php');
R::setup('mysql:host=localhost;
dbname=silex','root','');
require('Model_Bandmember.php');
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$srcDir = __DIR__;
$app = new Application();
$app['debug'] = true;
$app->register(new DDesrosiers\SilexAnnotations\AnnotationServiceProvider(), array(
"annot.controllerDir" => $srcDir."\controllers"
));
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => $srcDir.'\views',
));
$bandmember = R::dispense('bandmember');
$bandmember->name = 'Fatz Waller';
$id = R::store($bandmember);
$bandmember = R::load('bandmember',$id);
R::trash($bandmember);
echo $lifeCycle;die();
$app->run();
I have the good value of $lifeCycle. But I would like to use this file in a controller for functions add (), updates () etc .. So I try this :
<?php
namespace App\Controllers;
use DDesrosiers\SilexAnnotations\Annotations as SLX;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
require(__DIR__.'/../rb.php');
/**
* #SLX\Controller(prefix="article")
*/
class ArticleController
{
/**
* #SLX\Route(
* #SLX\Request(method="GET", uri="/"),
* #SLX\Bind(routeName="articleIndex")
* )
*/
public function index(Application $app)
{
$articles = R::findAll('article');
return $app['twig']->render('Article/index.twig', array(
'articles' => $articles,
));
}
...
...
But i have this error :
Cannot redeclare class RedBeanPHP\RedException in C:\wamp64\www\SilexTest\rb.php on line 6737
Very well, I think that the file must already be present! But if i comment it i have this error :
Class 'App\Controllers\R' not found
This is normal because this class is in the rb.php file that I just commented on.
If I do a require, I have a class redeclare , but if I do not put it, it lacks a class.
Any help will be appreciated.
Since the rb is already included so no need to include it anywhere. To use it from the global scope , you've to use \R:
$articles = \R::findAll('article');
Because, it seems like that, the R is available in the global scope. In this case, you can use use R; at the top of your class, for example:
namespace App\Controllers;
use DDesrosiers\SilexAnnotations\Annotations as SLX;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use R; // <-- Notice this
/**
* #SLX\Controller(prefix="article")
*/
class ArticleController
{
// Use: R::findAll('article') in any method in this class
}
You should read about namespace in PHP.

Can't use a namespace in a Controller

I have this Controller :
namespace FacilitaTripBundle\Controller;
use FacilitaTripBundle\Api\models\GuideDestination\GuideDestinationModel;
use FacilitaTripBundle\Api\models\Destination\DestinationModel;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
/**
* #Route("/api/v1", name="api")
*/
class ApiController extends Controller
{
/**
* #Route("/destinations/get_all_minimal/", name="destination_get_minimal")
*/
public function getMinimalAction()
{
$model = new DestinationModel();
$data = $model->getAllMinimal();
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* #Route("/guideDestination/getLastAddDestination/", name="destination_last_add_destination")
*/
public function getLastAddDestinationAction()
{
$guide_destination_model = new GuideDestinationModel();
$data = $guide_destination_model->getLastAddDestination();
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I got this error :
Attempted to load class "GuideDestinationModel" from namespace "FacilitaTripBundle\Api\models\GuideDestination".
Did you forget a "use" statement for another namespace
I define the class GuideDestinationModel in this file :
namespace FacilitaTripBundle\Api\models\GuideDestination;
class GuideDestinationModel {
}
How you got an idea why I got this error ?
What is the physical path to file containing GuideDestinationModel class?
According to PSR-0, which Symfony is using, you are supposed to put class definitions in path which corresponds to your namespace like in following example.
\Symfony\Core\Request =>
/path/to/project/lib/vendor/Symfony/Core/Request.php
I notice you have lowercase models in your FacilitaTripBundle\Api\models\GuideDestination namespace. Is your directory models also lowercase? If not this might be the issue here if you are using system which is case sensitive when it comes to path resolving (i.e. Linux)

Send email from command line in symfony2

I need to render a twig template from a command class in symfony2.
namespace IT\bBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class CronCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('send:emails')
->setDescription('Envio programado de emails');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$message = \Swift_Message::newInstance()
->setSubject('bla bla')
->setFrom('x#x.com')
->setTo('x#gmail.com')
->setCharset('UTF-8')
->setContentType('text/html')
->setBody($this->renderView('mainBundle:Email:default.html.twig'));
$this->getContainer()->get('mailer')->send($message);
$output->writeln('Enviado!');
}
}
But when I execute the command php app/console send:emails I get the following error:
Fatal error: Call to undefined method IT\bBundle\Command\CronCommand::renderView()
How can I render the view?
It's because renderView is method of class Controller. Instead of that try:
$this->getContainer()->get('templating')->render(...);
Change
$this->renderView()
to
$this->getContainer()->get('templating')->render()
Maybe, not exactly the question you ask, but for sure - important.
Please, do remember that if you want to send emails via Command call, you need to flushQueue.
$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$spool->flushQueue($transport);

Categories