using Symfony 5 and Omines, I have 2 tables sending a request to the same url:
the first table show products sold this month,
the second table show products sold before this month
Therefore, I want to pass as a parameter a date. and then in the query_builder filter it.
I do not find any hint in the documentation.
Any help would be great.
Thanks,
add your desired variable which you want to use in querybuilder like shown in example below
$table->createAdapter(ORMAdapter::class, [
'entity' => Product::class,
'query' => function (QueryBuilder $builder) use ($date) {
$builder
->select('p')
->from(Product::class, 'p')
->where("p.date = :date")
->setParameter("date", $date)
;
},
]);
Related
Is there a way in Drupal 8 to dynamically generate a page for each row in a table in a database?
If I have a database named School, with a table Students, with these columns and rows:
ID |FirstName |LastName |Email |User |HiddenField
-------------------------------------------------------------------------
1 |Adam |Johnson |ajohnson#example.com |ajohn1 |Blah
2 |Bob |Smith |bsmith#example.com |bsmith0 |Foo
Is there a module or setting to create simple pages with these URLs with content like this:
http://mywebpage.com/students/1
First name: Adam
Last name: Johnson
Email address: ajohnson#example.com
Username: ajohn1
http://mywebpage.com/students/2
First name: Bob
Last name: Smith
Email address: bsmith#example.com
Username: bsmith0
Note that there is a HiddenField that isn't displayed, so this solution should include the ability to exclude certain columns.
I've tried using the Views module to create a new page type, but I don't see in there where to specify a table or anything like that.
To fetch data to an associative array with the keys named as the fields, you can write the following:
$query = \Drupal::database()->select('students')
->fields('students', [
'id',
'firstname',
'lastname',
'email',
'user'
]);
$results = $query->execute()->fetchAllAssoc();
After that, you can iterate through $results and create the pages:
foreach ($results as $result) {
// Create node object.
$node = Node::create([
'type' => 'page',
'title' => 'whatever you want',
'field_machine_name' => 'field_value',
'firstname' => $result['firstname'],
]);
$node->save();
}
Please keep in mind to use dependency injection wherever you can. Also you can check for errors like is there a bundle called 'page', and run it only if there is.
I have 3 tables:
Post -> Type -> Category
I need to get the category on the Post entity passing per Type to use this on a filter form
This is possible?
like a join and subjoin
If I understand correctly, you want to be able to filter Post's by Category.
Like with any other field you wish to filter by, you have to add a Form to the filter's FormBuilder. The problem in this case is that the Entity bound to the form doesn't have the property category. It's its property type who does.
Thus, you need to tell the Form how to access the right property. This is achieved by using the property_path option. Here's the documentation for it.
You would do something like this in your filter's Type:
$builder
->add('category', 'entity', array(
'label' => 'Category',
'data_class' => 'Category',
'property_path' => 'type.category',
))
;
The property_path option is very powerful. It will accept any path that the PropertyAccess component does. Read its documentation here.
Multiple joins are possible in doctrine. Please, read this section in doctrine documentation.
This is an existing schema I'm working with and I'm trying to not make any changes for the time being. I have an entity property that represents a university semester, like "fall12", "spring11", etc.
When adding or editing this entity with a form, I want to split that property into two form fields: "Season" (fall or spring") and "Year" (2011, 2012, etc):
...
->add('formSemesterSeason', 'choice', array(
'label' => 'Season',
'mapped' => false,
'choices' => array('fall' => 'Fall', 'spring' => 'Spring'),
))
->add('formSemesterYear', 'choice', array(
'label' => 'Year',
'mapped' => false,
'choices' => $this->courseManager->getYearChoices(),
))
...
When submitting the form, the values need to be combined and saved to the "semester" property on the entity as a string
When viewing the edit form, the existing "semester" value needs to be split between the two.
I don't think data transformers help here, since they apply to transforming just one form item.
Right now I'm using a form event POST_SET_DATA to fill out the two form fields when editing an existing entity:
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) use ($course_manager) {
$course = $event->getData();
$form = $event->getForm();
$semester = $course->getSemester();
$parsed_semester = $course_manager->parseSemesterMachineName($semester);
$form->get('formSemesterSeason')->setData($parsed_semester->season);
$form->get('formSemesterYear')->setData($parsed_semester->yearFull);
});
This works well, but how do I then combine the values back after the form has been submitted? I can do it easily in the controller, but I think I should be able to use form events, and have the data manipulation take place before form validation.
You can combine them back in a POST_SUBMIT listener.
The best way (reuseable) would be to create your own custom form type with a data transformer to split/combine the fields internally.
There are "recipes" in the cookbook but the best way that I found to create it was to rip apart the DateTime field type and associated transformers (DataTransformerChain, DateTimeToArrayTransformer & ArrayToPartsTransformer) for parts and build my own from that.
1.) The Situation (simplified)
I have two entities: a Container-entity, which has exactly 1 Content-entity. The content_id is stored in the Container-entity.
2.) Soft-Delete Content-entities
I implemented a function to soft-delete Content-entities, so I added a "deleted"-attribute to the Content-entity. Everything works fine.
3.) The problem
Now, when I want to create a new Container-entity, the auto-generated choices show ALL the Content-entities - even those ones, which I "marked as deleted" (delete-attribute = 1).
4.) The question
Where is the correct place to add a "filter"/"query" to only show the elements which are not marked as deleted? (delete != 1)
5.) What I've tried
a.) view/twig approach: I tried to modify the rendering of the {{ form_widget(form.contentId) }} with no success
b.) controller approach: I tried to manipulate the form-data in the newAction where the form is being created ($form = $this->createCreateForm($entity)) with no success
c.) type/buildForm approach: I tried to change the buildForm()-method ... again, no success
If would be GREAT if you could give me a hint and/or a short code example of where I could hook into the action to remove the soft-deleted choices.
Thank you very much in advance!
You're looking for the query_builder option of the entity field.
You can create a custom query that filters the resultset in there.
example:
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'query_builder' => function(EntityRepository $repository) {
$qb = $repository->createQueryBuilder('u');
// the function returns a QueryBuilder object
return $qb
// find all users where 'deleted' is NOT '1'
->where($qb->expr()->neq('u.deleted', '?1'))
->setParameter('1', '1')
->orderBy('u.username', 'ASC')
;
},
));
You could go for a more general approach that filters all select statements using doctrine filters, too.
A client requested this. He wants to allow multiple date formats for a birthday field. The documentation didn't give me any clues how to realize it and neither did google.
Anyone who experienced such a request before and has a lead how to achieve this?
Currently it looks like this:
$builder->add('xxx', 'birthday', array('widget' => 'single_text', 'invalid_message' => 'some message (dd-MM-yyyy)', 'format' => 'dd-MM-yyyy'))
If you want to handle different date formats in your form, you ought to look at DataTransformer
It helps you to transform data from one format to another, for example:
2013-03-26 ==transform==> 2013/03/26
2013.03.26 ==transform==> 2013/03/26
26.03.2013 ==transform==> 2013/03/26
Data transformer should NOT be used in this case.
The main point of data transformer is to convert a data back and forth between view <=> norm <=> model.
It's not your case, you don't want a bidirectional transformation.
What you want is to filter the data, and for that, you can use a form event:
$builder->add(
$builder
->create('xxx', 'birthday', [...])
->addEventListener(
FormEvents::PRE_SUBMIT,
function(FormEvent $event) {
$value = $event->getData();
// Do the filtering you want (for example replacement of special chars with a dash)
// $value = preg_replace('[^\d]', '-', $value)
$event->setData($value);
}
)
);
And you are done, the data is filtered on the PRE_SUBMIT event, before validation.
I wrote this example from memory and didn't tested it, maybe you'll should adapt it (and add your field option instead of [...].