Add Entity Managers and Connections width EntityManager::create - symfony

I want to create multiple Entity Managers and connection width This method EntityManager::create but how can get this new entity manager after creation and use doctrine to apply different command like this :
php bin/console doctrine:database:create --connection=newconnection and
$this->getDoctrine()->getManager('newconnection');
$isDevMode = false;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
$conn = [
'driver' => 'pdo_mysql',
'username' => 'username',
'password' => 'password',
'dbname' => $dbname
];
// obtaining the entity manager
return EntityManager::create($conn, $config);

Related

Cakephp 3 - Query Fixture in IntegrationTestTrait

I am having issues querying a loaded Fixture in my TestCase for an IntegrationTestTrait. I want to verify that a record already exist inside of a Fixture, then insert a duplicate record and verify that there is still only 1 record in the database.
During my test case initialization, I set the session variable for authentication.
public function setUp() {
parent::setUp();
$this->loadFixtures(
'Students', 'Users');
// Configure Authentication
$this->session([
'Auth' => [
'User' => [
'id' => 21896,
'institution_id' => 1,
'student_id' => null,
'contact_id' => 91,
'email' => 'AuthenticatedEmail#school.edu',
'role' => 'DSP',
'is_admin' => false
]
]
]);
// Load Tables
$this->Students = TableRegistry::getTableLocator()->get('Students');
}
In my Test Case, I check to see if the Database contains a record, then submit a POST request then test to see if the record did not insert.
public function testAddStudentSuccess() {
$data = [
'institution_id' => 1,
'contact_id' => null,
'id_number' => '200XYZ',
'last_name' => 'Trimor',
'first_name' => 'Paul',
'email' => '1_test#email.com'
];
// Test Pre-condition
$query = $this->Students->find('all')->where([
'id_number' => $data['id_number']
]);
$this->assertEquals(1, $query->count());
$this->post('students/add', $data);
// Test Post-condition
$this->assertResponseSuccess();
$query = $this->Students->find('all')->where([
'id_number' => $data['id_number']
]);
$this->assertEquals(1, $query->count());
}
However, when I run the Test Case, I get the following error:
Notice Error: Undefined variable: _SESSION in/var/www/html/samusg/src/Model/Table/StudentsTable.php, line 206]
A couple things:
The last assertion works! After $this->post('students/add', $data) is submitted, the $query is populated with data.
The first assertion does not work. I debug the Fixture before the $this->post() is called and it returns empty.
In the Test Table, there is a test for $_SESSION variable, which is what line 206 referring to.
Long Story short: The Fixture is not populated with data during the start of the Test Case, but once the integration runs then the Fixture magically contains all the data. I get $_SESSION errors, but I already set the session in the setUp(), so I'm lost.
I greatly appreciate any help. Thank you
I was able to by pass this message by setting the $_SESSION super global directly on my Test:
public function setUp() {
parent::setUp();
$this->loadFixtures(
'Students', 'Users');
// Configure Authentication
$this->session([
'Auth' => [
'User' => [
'id' => 21896,
'institution_id' => 1,
'student_id' => null,
'contact_id' => 91,
'email' => 'AuthenticatedEmail#school.edu',
'role' => 'DSP',
'is_admin' => false
]
]
]);
$_SESSION = [
'Auth' => [
'User' => [
'id' => 21896,
'institution_id' => 1,
'student_id' => null,
'contact_id' => 91,
'email' => 'AuthenticatedEmail#school.edu',
'role' => 'DSP',
'is_admin' => false
]
]
];

How to integrate PowerBI in symfony4

I want to integrate an Advanced statistics in my project symfony 4
so i decide to use PowerBI ( if you have an alternative please let me know),
my question is how to integrate it in my local project symfony4 and in relation with my database MySQL
Untill now , there no Symfony bundle for power bi , but instead you can use :
the adevait/power-bi
In case you don't find options you are looking for , you can using the native power bi rest api
You need to create an account and manage it by creating your dataset etc ...
Requirement :
GuzzleHttp
The point here is to create for example a service that manage calling the api :
example for authentication :
try {
/** #var GuzzleHttp\Client $client **/
$response = $client->post(
'https://login.windows.net/<tenant-id>/oauth2/token',
[
"headers" => [
"Accept" => "application/json"
],
'form_params' => [
'resource' => 'https://analysis.windows.net/powerbi/api',
'client_id' => $this->clientId,
'client_secret' => $this->secret,
'grant_type' => 'password',
'username' => $this->username,
'password' => $this->password,
'scope' => 'openid',
]
]
);
$body = json_decode($response->getBody()->getContents(), true);
return $body['access_token'];
} catch (ClientException $e) {
return ['error' => $e->getMessage()];
}
At this point , you need the token to call other endpoint , so you need to inject the returned token in the header of any request you send like :
try {
/** #var GuzzleHttp\Client $client **/
$client->post(
https://api.powerbi.com/v1.0/myorg/groups/<group-id>/datasets/<dataset-id>/tables/<table-name>/rows,
[
'headers' => [
"Accept" => "application/json",
"Authorization" => sprintf("Bearer %s", $token),
],
'json' => $data
]
);
return true;
} catch (ClientException $e) {
return false;
}
Hope that help you .

Class does not exist symfony

I'm having a problem recovering my entities, the entities are in the AppBundle / Entity folder, but symfony can not find it ...
Here is the error: Class 'Product' does not exist
Here is the function myManager () present in a controller
public function myManager(){
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/AppBundle/Entity"), $isDevMode);
// database configuration parameters
$conn = array(
'dbname' => 'teste',
'user' => 'root',
'password' => '',
'host' => '127.0.0.1',
'driver' => 'pdo_mysql',
);
$entityManager = EntityManager::create($conn, $config);
return $entityManager;
}
the function testAction () that calls the manager and tries to load the Product entity
public function testAction(){
$em = $this->myManager()->getRepository('Product');
return $this->render('toto.html.twig');
}
link of documentation : Doctrine
You need to use the correct notation to make a reference to your entity:
$manager->getRepository('MyBundleName:Product')

Set selected value for symfony2 form with form type entity

I have an Entity named User in my symfony2 application. I have created a form in the controller using Create form builder.
My code in the controller is as follows:
$user = new User();
$form = $this->createFormBuilder($user);
$resultForm = $form->add('username')
->setAction($this->generateUrl('usermanagement_create'))
->setMethod('POST')
->add('email')
->add('roles', 'entity', array(
'class' => 'PortalBundle\Entity\Roles',
'expanded' => true,
'multiple' => true,
'required' => false,
'constraints' => array(
new NotBlank(),
),
))
->getForm()
;
I have to render the form, as selected some values as default for the field roles.
Can I suggest to create the form into Your/Bundle/Path/Form/YourFormType?
That way your form could be used pretty much everywhere and if you need it, you can simply call it. Moreover, your controller will be much clean.
Writing about solution, you can proceed in different ways
Set empty_data attribute
Set the roles explicitly into your object
empty_data explaination
You need to inject (if you define a form as a service) or pass (if you define an external class for your form) or use (in your case) and entity manager to retrieve default choice object. I will show you a solution based onto your snippet
$em = $this
->getDoctrine()
->getManager();
$user = new User();
$form = $this->createFormBuilder($user);
$resultForm = $form
->add('username')
->setAction($this->generateUrl('usermanagement_create'))
->setMethod('POST')
->add('email')
->add('roles', 'entity', array(
'class' => 'PortalBundle\Entity\Roles',
'empty_data' => $em->getReference("PortalBundle:Roles", //put here pk to retrieve default role)
'expanded' => true,
'multiple' => true,
'required' => false,
'constraints' => array(
new NotBlank(),
),
))
->getForm();
If you need more than one role, write a query to return them and pass to empty_data
Set the roles explicitly
$em = $this
->getDoctrine()
->getManager();
$user = new User();
$default_roles = $em
->getRepository("Path/To/Roles/Repo")
->findDefaults(); //maybe a method you need to implement
$user->setRoles($default_roles);
//and leave form code as is

How configure bundle based on other service?

I want to configure my index types of Elastica dynamically based on entity list which I can get from entity repository. To do this I must have instance of repository so doctrine EntityManager must exist so Depedency Inject container must by compiled. But when it is compiled is too late for configure Elastica because container is frozen.
This is what i tried:
#config.yml
fos_elastica:
clients:
default: { host: 127.0.0.1, port: 9200 }
indexes:
app:
types: %elastic_types%
#application bundle
public function build(ContainerBuilder $container){
$types = array(
'tag' => array(
'mappings' => array(
'text' => array()
),
'persistence' => array(
'driver' => 'orm',
'model' => 'Cloud\AdmBundle\Entity\Tag',
'provider' => array(),
'listener' => array(),
'finder' => array()
)
)
);
$container->setParameter('elastic_types', $types);
}
It works but i don't have capabilities to use EntityRepository here.
#application bundle
public function setContainer(ContainerInterface $container = null) {
parent::setContainer($container);
$container->setParameter('elastic_types', array('anything param'));
}
Here is too late to set any params because container is compiled and i get execption:
ParameterNotFoundException in ParameterBag.php line 106:
You have requested a non-existent parameter "elastic_types".
How can i do this ?

Resources