Symfony - How to regenerate crud for Entity from a controller - command-line

I would like to regenerate crud for all my Entities from my controller once I enter specific url. The example below runs a command for only one Entity for demonstration purpose. When I navigate to the path '/reCrud', my browser will spin forever but the command never executes. What is quite interesting is that the same code, when I run 'cache:clear' instead, will run just fine.
<?php
namespace AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class CrudController extends Controller
{
/**
* #Route("/reCrud")
*/
public function reCrudAction()
{
$kernel = $this->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new StringInput('doctrine:generate:crud AdminBundle:Klient --overwrite --no-debug');
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
// return new Response(""), if you used NullOutput()
return new Response($content);
}
}
Perhaps this is only an environment configuration issue. Feel free to chunk that code and test it on your machine. Let me know if it works or not.

It spins because underneath it is waiting for you to enter stuff:
Welcome to the Doctrine2 CRUD generator
This command helps you generate CRUD controllers and templates.
First, give the name of the existing entity for which you want to generate a CRUD
(use the shortcut notation like AcmeBlogBundle:Post)
The Entity shortcut name [AdminBundle:Klient]:
Solution:
Try adding -n option which is:
-n, --no-interaction Do not ask any interactive question
So in the end your command would be something like this:
doctrine:generate:crud --entity=AdminBundle:Klient --overwrite --no-debug --no-interaction

Related

removeAll() from repository in scheduler task

For my scheduler task, I want to delete all the existing data from repository before updating it, every time the scheduler runs. I am able to save and add new data from XML File using add().
class FunctionFetcherService {
public function fetchRoomandLesson() {
$path = 'http:abc.dll?type=room&content=xml';
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$roomRepository = $objectManager->get("School\\booking\\Domain\\Repository\\RoomsRepository");
$this->roomRepository->removeAll();
$xml = simplexml_load_file($path);
$json = json_encode($xml);
$xmlArray = json_decode($json, true);
$serialized_array = serialize($xmlArray);
$unserialized_array = unserialize($serialized_array);
An error occurs removeAll() called on Null. I also referred to the already asked question: use removeAll() in scheduler task but it does doe not work.
You create the repository as variable $roomRepository and then try to access it through $this->roomRepository. Changing $this->roomRepository to $roomRepository should fix the error.
You should create an Extbase CommandController as your scheduler task. All registered commands are available in the scheduler as well as CLI commands.
By using CommandControllers you can use the full extbase framework, such as dependency injections and validations.
Please note that CommandController command methods must be suffixed with Command just like the linked example.

New project using Symfony 4 with MongoDB / service not found

I'm trying to create a new Symfony4 project with MongoDB.
First I created a Symfony4 project using this documentation:
https://symfony.com/doc/current/setup.html
Then I included MongoDB using this documentation:
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html
I tried to follow the instructions as exactly as possible (for example I didn't need to add anything to app/AppKernel.php, but MongoDB was automatically added to config/bundles.php).
Now I think everything should work, but my Symfony app doesn't find the MongoDB Service:
You have requested a non-existent service "doctrine_mongodb".
Did you mean one of these: "http_kernel", "request_stack", "router"?
in ServiceLocator.php (line 48)
Controller:
namespace App\Controller;
use App\Document\Chapter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends AbstractController {
public function createAction() {
$test = new Chapter();
$test->setHeadline('Test');
$dm = $this->get('doctrine_mongodb')->getManager();
$dm->persist($test);
$dm->flush();
return new Response('Created product id '.$test->getId());
}
}
However, If I execute this on the console:
php bin/console debug:container
I get a list of services including these:
doctrine_mongodb Doctrine\Bundle\MongoDBBundle\ManagerRegistry
doctrine_mongodb.odm.default_connection Doctrine\MongoDB\Connection
doctrine_mongodb.odm.default_document_manager Doctrine\ODM\MongoDB\DocumentManager
doctrine_mongodb.odm.document_manager alias for "doctrine_mongodb.odm.default_document_manager"
So the service seems to be there, but Symfony can't load it from my app.
Any idea how I could solve this?
Is it possible that the Mongo-DB Server connection doesn't work and for some reason it isn't logged and the service just won't load?
You could use autowiring
use Doctrine\ODM\MongoDB\DocumentManager as DocumentManager;
and
public function createProduct(DocumentManager $dm)
Try extending from "Controller" instead "AbstractController".
class DefaultController extends Controller

Where should I locate the independent php file in symfony2.3 which is being used in my contoller?

I am new to symfony 2.3
I have a problem in running an independent php file from my controller.
I want to run that file from shell_exec() and to use it's output in my code.
But i dont know the right way that where to locate that file I want to run.
my controller code as follows
namespace my\apiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
Class newController extends Controller
{
public function getlibAction($text)
{
$out = shell_exec("php script/data.php");
/*
my rest code to take data from output
*/
$response = new Response();
$response->headers->set('Content-Type', 'text/html');
$response->setContent($out);
return $response;
}
}
I have copied the "script/" folder containing "data.php" to the "my/apiBundle/Resources/public/" but i could not access it .
And I try to copy it independently in "my/apiBundle/" but it was still not successful.
I dont know eher should i locate it.
Please help me out of this issue.
Thanks in advance..
You could obtain the full path of the current file (your controller) with:
dirname(__DIR__)
Based on that you can obtaining the parent directory like:
dirname(dirname(__DIR__))
And so on until you reach the desired path.
As an example, I located the recaptcha lib under a folder named libs inside Resources directory (src/Company/Project/Bundle/Resources/libs/recaptchalib.php) and I require it on my Controller like follows:
require_once dirname(__DIR__).'/Resources/libs/recaptchalib.php';
You could do something similar with the shell_exec command.
Hope it helps.

Setting EObject's resource with a command

I'm using a TransactionalEditingDomain to manage changes on my model. However, I have some problems in creating an empty model. I think that the problem is when I add the model to the model Resource (modelResource.getContents().add(model);), because it should be put within a transaction. Accordingly, I was trying to use the AddCommand to perform such operation, but I am not able to find a EStructuralFeature for the Resource's contents.
In other words, I would like to write something like:
Command cmd = AddCommand.create(editingDomain, modelResource, FEAT_CONTENTS, model);
commandStack.execute(cmd);
The problem is that I cannot find the FEAT_CONTENTS... does anybody have a suggestion?
I have found the "official" solution with using AddCommand on the Eclipse Forum of EMF:
Command cmd = new AddCommand(editingDomain, modelResource.getContents(), model);
commandStack.execute(cmd);
Since removing a root object is also non-trivial, the same approach can be used with RemoveCommand:
Command cmd = new RemoveCommand(editingDomain, modelResource.getContents(), model);
Finally, for completeness, you should also know that DeleteCommand (that also removes all references to the removed object) does not work on root objects at all.
I found a solution, but sincerely I do not like it:
commandStack.execute(new RecordingCommand(editingDomain) {
protected void doExecute() {
modelResource.getContents().add(model);
}
});

Can I do more than one form for the same model class in symfony?

Well, imagine that we have a register form of a class Customer and we only ask three fields (name,surname,email) and after, when this user logged first time we want to complete this information.
First, we have in lib/form/doctrine a file called 'CustomerForm.class.php' wich is generated automatic on command line. In this file we 'setup' only 3 fields and validators and if we wanna use we do something like that:
$this->form = CustomerForm();
Second, we create manual another form named 'CustomerFormStep1.class.php' where we can setup for validate the other fields. But when we do..
$this->form = CustomerFormStep1();
it returns error: Fatal error: Class 'CustomerFormStep1' not found
What is wrong?
Thanks.
Assuming you have the form defined as:
class CustomerFormStep1 extends sfForm
or similar (sfFormDoctrine etc), and named correctly like you say (CustomerFormStep1.class.php) and in lib/form, then Symfony should just pick the definition up fine. Did you clear the cache after creating and placing it in the right place? (symfony cc).
Create the new CustomerFormStep1 class as #richsage instructed. Then, in your actions you can write something like:
public function executeLogin(){
//before login
$this->form = new CustomerForm();
}
public function executeLoggedIn(){
$this->form = new CustomerFormStep1();
//other steps
}
Haven't you read the tutorial? Extending forms is perfectly described in context with reh admin generator and can of course be applied to any case.