Sonata date picker month resets to 1 - symfony

I use sonata_type_datetime_range_picker. I works correct on the frontend side. But when I submit form it remakes month value to 1. I.e. my submitted value is "2017-02-02 03:14:00" and value after submit is "2017-01-02 03:14:00". According to the profiler date is correct in the Request object but is wrong in Symfont Form Component.
My admin code
$datePickerOptions = [
'format' => "YYYY-MM-DD HH:mm:SS",
'datepicker_use_button' => false,
'dp_use_minutes' => false,
'dp_use_seconds' => false,
'dp_side_by_side' => true,
'dp_language' => 'en',
];
$datagridMapper
->add(
'dateTime',
'doctrine_orm_datetime_range',
[
'show_filter' => true,
'field_type' => 'sonata_type_datetime_range_picker',
'field_options' => [
'field_options_start' => $datePickerOptions,
'field_options_end' => $datePickerOptions,
],
]
);
What am I doing wrong?

Ok, I kinda found the working solution myself. Maybe it helps someone other sometime:
$now = new \DateTime();
$historyStart = new \DateTime('Dec 20 2016');
$dateFormat = 'd.m.y H';
$datagridMapper
->add(
'dateTime',
'doctrine_orm_datetime_range',
['show_filter' => true,],
'sonata_type_datetime_range_picker',
[
'field_options_start' => [
'dp_min_date' => $historyStart->format($dateFormat),
'dp_max_date' => $now->format($dateFormat),
'dp_default_date' => $now->format($dateFormat),
'dp_language' => 'en',
'format' => 'dd.MM.yy HH',
'datepicker_use_button' => false,
'dp_use_minutes' => false,
'dp_use_seconds' => false,
'dp_side_by_side' => true,
],
'field_options_end' => [
'dp_min_date' => $historyStart->format($dateFormat),
'dp_max_date' => $now->format($dateFormat),
'dp_default_date' => $now->format($dateFormat),
'dp_language' => 'en',
'format' => 'dd.MM.yy HH',
'datepicker_use_button' => false,
'dp_use_minutes' => false,
'dp_use_seconds' => false,
'dp_side_by_side' => true,
]
]
);

Related

Symfony - How i can get all selected files from request with bellow the name

enter image description here
<input type="file" id="admin_novelty_NoveltyGrants_0_file" name="admin_novelty[NoveltyGrants][0][file]" required="required" multiple="multiple" class="form-control-file">
I have a table grantProduct with 2 mainly properties are title and URL
this is my formType.php. but this is just sub-form. it is included in another form.
$builder
->add('title', InputType\TextType::class, [
'label' => 'novelty.common.title',
'required' => true,
'trim' => true,
'attr' => array(
'placeholder' => 'タイトルを入力ください'
),
'constraints' => [
new Assert\NotBlank(),
]
])
->add('url', InputType\TextType::class, [
'label' => 'novelty.common.url',
'required' => true,
'trim' => true,
'constraints' => [
new Assert\NotBlank(),
]
])
->add('file', FileType::class, [
'multiple' => false,
'mapped' => false,
'attr' => [
'multiple' => 'multiple'
],
])
;
How i can get file input value after selecting some local files?
You can get your file(s) as such $files = $form['file']->getData();
You can loop over each and do what you want
$files = $form['file']->getData();
foreach($files as $file) {
//do what you want with file
}

How to getData() on a collectionType field - Symfony 4

I have a collectionType (Equipements) on a Symfony 4 ORM form (intervention).
For example, this equipement field :
<input type="file" id="intervention_equipements_0_photoGraffiti" name="intervention[equipements][0][photoGraffiti]">
I try to get the data of this field with :
$fileToTransfer = $form['intervention_equipements_0_photoGraffiti']->getData();
or
$fileToTransfer = $form['intervention[equipements][0][photoGraffiti]']->getData();
I have the error Child "intervention[equipements][0][photoGraffiti]" does not exist.
Here is my intervention Type :
$builder
->add('idInstallation', EntityType::class, [
'class' => Installation::class,
'choice_label' => 'numeroInstallation',
'required' => false,
])
->add('equipements', CollectionType::class, array(
'entry_type' => EquipementInterventionType::class,
'entry_options' => array('label' => false),
))
And the equipement entity:
$builder
->add('nom', TextType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => true
))
->add('numero', TextType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => true
))
->add('etatEquipement', ChoiceType::class, array(
'choices' => $choices_controle,
'expanded' => false,
'multiple' => false,
'required' => false,
'error_bubbling' => true,
))
->add('photoEquipement', FileType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => false,
'data_class' => null
))
->add('graffiti', CheckboxType::class, array(
'required' => false,
'error_bubbling' => true,
))
->add('photoGraffiti', FileType::class, array(
'error_bubbling' => true,
'required' => false,
'disabled' => false,
'data_class' => null
))
...
How can I fix this, please ?
Directly use $form->getData(). This will return the array with all your form datas that you are looking for.
in your form controller
$equipements = $intervention->getEquipement();
will return the array of collections then
foreach ($equipements as $equipement) {
$fileToTransfer = $equipement->getPhotoGraffiti()
}
Hope you have getter and setter in your entity class

Symfony 4 : Property App\Entity\Ad::$site does not exist (but impossible to find in the code ?)

I had a class Site link to my class Annonce.
I deleted everything about "Site", did the migration with doctrine.
Then this error appeared.
So i did a find in all the file to see if "site" it's somewhere and delete everywhere.
And i still have this error.
I don't know what to do ?
Can have a cache problem ?
This is the stack Trace
ReflectionException:
Property App\Entity\Annonce::$site does not exist
at vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php:63
at ReflectionProperty->__construct('App\\Entity\\Annonce', 'site')
(vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php:63)
at Doctrine\Common\Persistence\Mapping\RuntimeReflectionService->getAccessibleProperty('App\\Entity\\Annonce', 'site')
(vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:970)
at Doctrine\ORM\Mapping\ClassMetadataInfo->wakeupReflection(object(RuntimeReflectionService))
(vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:750)
at Doctrine\ORM\Mapping\ClassMetadataFactory->wakeupReflection(object(ClassMetadata), object(RuntimeReflectionService))
(vendor/doctrine/persistence/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:181)
at Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor('App\\Entity\\Annonce')
(vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:283)
at Doctrine\ORM\EntityManager->getClassMetadata('App\\Entity\\Annonce')
(vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2692)
at Doctrine\ORM\UnitOfWork->createEntity('App\\Entity\\Categorie', array('id' => 1, 'nom' => 'Bar Tabac PMU'), array('deferEagerLoad' => true, 'fetchAlias' => 'e'))
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:271)
at Doctrine\ORM\Internal\Hydration\ObjectHydrator->getEntity(array('id' => 1, 'nom' => 'Bar Tabac PMU'), 'e')
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:492)
at Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateRowData(array('id_0' => '1', 'nom_1' => 'Bar Tabac PMU'), array())
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php:162)
at Doctrine\ORM\Internal\Hydration\ObjectHydrator->hydrateAllData()
(vendor/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php:152)
at Doctrine\ORM\Internal\Hydration\AbstractHydrator->hydrateAll(object(PDOStatement), object(ResultSetMapping), array())
(vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:976)
at Doctrine\ORM\AbstractQuery->executeIgnoreQueryCache(null, null)
(vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:922)
at Doctrine\ORM\AbstractQuery->execute()
(vendor/symfony/doctrine-bridge/Form/ChoiceList/ORMQueryBuilderLoader.php:50)
at Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader->getEntities()
(vendor/symfony/doctrine-bridge/Form/ChoiceList/DoctrineChoiceLoader.php:85)
at Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader->loadChoiceList(array(object(IdReader), 'getIdValue'))
(vendor/symfony/form/ChoiceList/LazyChoiceList.php:62)
at Symfony\Component\Form\ChoiceList\LazyChoiceList->getChoices()
(vendor/symfony/form/ChoiceList/Factory/DefaultChoiceListFactory.php:53)
at Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory->createView(object(LazyChoiceList), array(), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), null, null)
(vendor/symfony/form/ChoiceList/Factory/PropertyAccessDecorator.php:193)
at Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator->createView(object(LazyChoiceList), array(), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), null, null)
(vendor/symfony/form/ChoiceList/Factory/CachingFactoryDecorator.php:127)
at Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator->createView(object(LazyChoiceList), array(), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), null, null)
(vendor/symfony/form/Extension/Core/Type/ChoiceType.php:410)
at Symfony\Component\Form\Extension\Core\Type\ChoiceType->createChoiceListView(object(LazyChoiceList), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/Extension/Core/Type/ChoiceType.php:185)
at Symfony\Component\Form\Extension\Core\Type\ChoiceType->buildView(object(FormView), object(Form), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/ResolvedFormType.php:148)
at Symfony\Component\Form\ResolvedFormType->buildView(object(FormView), object(Form), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/ResolvedFormType.php:145)
at Symfony\Component\Form\ResolvedFormType->buildView(object(FormView), object(Form), array('block_name' => null, 'disabled' => false, 'label_format' => null, 'label_translation_parameters' => array(), 'attr_translation_parameters' => array(), 'translation_domain' => null, 'auto_initialize' => true, 'trim' => false, 'property_path' => null, 'mapped' => true, 'by_reference' => true, 'inherit_data' => false, 'method' => 'POST', 'action' => '', 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'allow_file_upload' => false, 'help_translation_parameters' => array(), 'error_mapping' => array(), 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => array(), 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', 'csrf_protection' => true, 'csrf_field_name' => '_token', 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => object(CsrfTokenManager), 'csrf_token_id' => null, 'multiple' => false, 'expanded' => false, 'block_prefix' => null, 'label' => 'Catégorie de commerce *', 'row_attr' => array(), 'attr' => array(), 'data_class' => null, 'empty_data' => '', 'required' => true, 'error_bubbling' => false, 'label_attr' => array(), 'compound' => false, 'upload_max_size_message' => object(Closure), 'help' => null, 'help_attr' => array(), 'help_html' => false, 'validation_groups' => null, 'constraints' => array(), 'choices' => null, 'query_builder' => null, 'class' => 'App\\Entity\\Categorie', 'em' => object(EntityManager), 'id_reader' => object(IdReader), 'choice_loader' => object(DoctrineChoiceLoader), 'choice_label' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceLabel'), 'choice_name' => array('Symfony\\Bridge\\Doctrine\\Form\\Type\\DoctrineType', 'createChoiceName'), 'choice_value' => array(object(IdReader), 'getIdValue'), 'choice_attr' => null, 'preferred_choices' => array(), 'group_by' => null, 'placeholder' => 'Choisir une catégorie', 'choice_translation_domain' => false))
(vendor/symfony/form/Form.php:1030)
at Symfony\Component\Form\Form->createView(object(FormView))
(vendor/symfony/form/Form.php:1033)
at Symfony\Component\Form\Form->createView()
(src/Controller/AnnonceController.php:60)
at App\Controller\AnnonceController->newFree(object(Request))
(vendor/symfony/http-kernel/HttpKernel.php:151)
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
(vendor/symfony/http-kernel/HttpKernel.php:68)
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
(vendor/symfony/http-kernel/Kernel.php:198)
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
(public/index.php:22)
Thanks
It is definitely a cache issue. Try the following in order and see if it helps:
bin/console cache:clear
rm the var/cache folder
manually clear any additional PHP cache you might have enabled
I also has this same issue. I can confirm that it is an issue with the DB cache.
Before running migrations you should run this commands:
bin/console doctrine:cache:clear-query --flush
bin/console doctrine:cache:clear-result --flush
bin/console doctrine:cache:clear-metadata --flush
If you are using redis to store the DB cache you might also need to flush that before executing migrations. You can do this from the redis-cli by typing FLUSHALL

How to set min value for field in form?

I have form with integer field - price.
$builder->add('list',
CollectionType::class,
[
'required' => false,
'allow_add' => true,
'error_bubbling' => true,
])
->add('price',
IntegerType::class,
[
'required' => false,
'error_bubbling' => true,
]);
How to set, for example, for validation i need min value for price 0 or greater?
I tried this one, but it's not work:
'constraints' => [
new GreaterThanOrEqual(50)
],
Thanks for all help.
controller Action
public function getProductAction(Request $request)
{
$variables = $request->get('list');
$price = $request->get('price');
$form = $this->createForm(ProductForm::class, null, ['csrf_protection' => false, 'allow_extra_fields' => true]);
$form->submit(['variables' => $variables, 'prices' => $price]);
if(!$form->isValid()) {
$errors = '';
foreach ($form->getErrors() as $error) {
$errors = $error->getMessage();
}
return new JsonResponse([
'errors' => $errors
],Response::HTTP_BAD_REQUEST);
} else {
$product = $this->getDoctrine()
->getRepository(Product::class)
->findByListAndPrice($list, $price);
if (!$product) {
return new JsonResponse([
'errors' => 'Product not found.'
],Response::HTTP_BAD_REQUEST);
}
return new JsonResponse($product);
}
}
Form not validate, and don't show errors, $form->isValid() === true
According to https://github.com/symfony/symfony/issues/3533 you can use min and max for the IntegerType even though the documentation might not mention this.
$builder->add('list',
CollectionType::class,
[
'required' => false,
'allow_add' => true,
'error_bubbling' => true,
])
->add('price',
IntegerType::class,
[
'required' => false,
'error_bubbling' => true,
/*'min' => 50*/
'attr' => [
'min' => 50
]
]);
EDIT: According to the documentation the 'min' property has to be inside 'attr' tag. This will add the min inside the input in the HTML.
You can use RangeType instead of IntegerType.
use Symfony\Component\Form\Extension\Core\Type\RangeType;
// ...
$builder->add('list',
CollectionType::class,
[
'required' => false,
'allow_add' => true,
'error_bubbling' => true,
])
->add('price',
RangeType::class,
[
'required' => false,
'error_bubbling' => true,
'min' => 0,
'max' => 50
]);

How to create a Drupal 8 view programmatically

I am trying to create a view programmatically in Drupal 8. Something similar to the crud log module in Drupal 7. I couldn't find any references on the internet either.
I was successful in creating a view programatically----I did the following--
1. Create a folder--C:\xampp\htdocs\Drupal Instance\modules
2. Create a YML info file --first_view.info and add the following code to it----
name: First View
type: module
description: My First Drupal 8 View
package: Custom
core: 8.x
3. Create an install file---first_view.install
And add the following code to it
<?php
/**
* #file
* Install, schema, and uninstall functions for the First View module.
*/
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\taxonomy\Entity\Term;
/**
* Implements hook_install().
*/
function first_view_install() {
}
/**
* Implements hook_uninstall().
*/
function first_view_uninstall() {
}
/**
* Implements hook_schema().
*/
function first_view_schema() {
$schema['first_view_table'] = [
// Example (partial) specification for table "node".
'description' => 'The base table for first_view.',
'fields' => [
'id' => [
'description' => 'The primary identifier for a node.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
],
'name' => [
'description' => 'The name of Employee.',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => '',
],
'age' => [
'description' => 'The age of employee.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
],
'is_active' => [
'description' => 'The activity of employee.',
'type' => 'int',
'not null' => TRUE,
'default' => 0,
],
'timestamp' => [
'description' => 'The timestamp of employee.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
],
'project_code' => [
'description' => 'The project code of employee.',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => 0,
],
],
'unique keys' => [
'id' => ['id'],
],
// For documentation purposes only; foreign keys are not created in the
// database.
'primary key' => ['id'],
];
return $schema;
}
4. Create a file---first_view.views.inc
And add the following code to it--
<?php
/**
* Implements hook_views_data().
*/
function first_view_views_data() {
$data = [];
$data['first_view_table'] = [];
$data['first_view_table']['table'] = [];
$data['first_view_table']['table']['group'] = t('First View table');
$data['first_view_table']['table']['provider'] = 'first_view_module';
$data['first_view_table']['table']['base'] = [
'field' => 'id',
'title' => t('First View table'),
'help' => t('First View table contains example content and can be related to nodes.'),
'weight' => -10,
];
$data['first_view']['table']['join'] = [
'node_field_data' => [
'left_field' => 'id',
'field' => 'id',
'extra' => [
0 => [
'field' => 'published',
'value' => TRUE,
],
1 => [
'left_field' => 'age',
'value' => 1,
'numeric' => TRUE,
],
2 => [
'field' => 'published',
'left_field' => 'is_active',
'operator' => '!=',
],
],
],
];
$data['first_view_table']['table']['join']['node_field_data'] = [
'left_table' => 'foo',
'left_field' => 'id',
'field' => 'id',
'extra' => [
['left_field' => 'project_code', 'field' => 'project_code'],
['field' => 'age', 'value' => 0, 'numeric' => TRUE, 'operator' => '>'],
],
];
$data['first_view_table']['id'] = [
'title' => t('Example content'),
'help' => t('Relate example content to the node content'),
'relationship' => [
'base' => 'node_field_data',
'base field' => 'id',
'id' => 'standard',
'label' => t('Example node'),
],
];
$data['first_view_table']['name'] = [
'title' => t('Name'),
'help' => t('Just a Name field.'),
'field' => [
'id' => 'standard',
],
'sort' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'argument' => [
'id' => 'string',
],
];
$data['first_view_table']['project_code'] = [
'title' => t('Project Code'),
'help' => t('Just a Project code field.'),
'field' => [
'id' => 'standard',
],
'sort' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'argument' => [
'id' => 'string',
],
];
$data['first_view_table']['age'] = [
'title' => t('Age'),
'help' => t('Just a numeric field.'),
'field' => [
'id' => 'numeric',
],
'sort' => [
'id' => 'standard',
],
'filter' => [
'id' => 'numeric',
],
'argument' => [
'id' => 'numeric',
],
];
$data['first_view_table']['is_active'] = [
'title' => t('Is Active'),
'help' => t('Just an on/off field.'),
'field' => [
'id' => 'boolean',
],
'sort' => [
'id' => 'standard',
],
'filter' => [
'id' => 'boolean',
'label' => t('Published'),
'type' => 'yes-no',
'use_equal' => TRUE,
],
];
$data['first_view_table']['timestamp'] = [
'title' => t('Timestamp'),
'help' => t('Just a timestamp field.'),
'field' => [
'id' => 'date',
],
'sort' => [
'id' => 'date',
],
'filter' => [
'id' => 'date',
],
];
$data['views']['area'] = [
'title' => t('Text area'),
'help' => t('Provide markup text for the area.'),
'area' => [
'id' => 'text',
],
];
return $data;
}
By following the above steps....when we install and enable the module a table gets created in the database...You will have to populate it in order to see some data in the view...don't forget to add dummy data in the table.....After that go to Structure/views--- And click on "Add View"----Give a name to your View---and then you will be able to see the table name in "Show" Drop Down box---In this case the table name is "First View Table"...I hope this article would be helpful....
Although it is not created from scratch programatically, here is a simple method:
create a view using the back office
export that single view using the configuration manager module
copy that yml file and place it in a basic custom module /config/install folder
remove the first line containing the uuid
(optional )modify the file manually if needed and if understood how it work
activating your custom module will import the view
You can create a new View through the ConfigEntityStorage.
Create the View in the UI. Export the View's YAML config file to a path in your module, removing the UUID.
// view config is in `my_module/config/install/views.view.my_view.yml`
// (uuid removed!)
$dir = drupal_get_path('module', 'my_module');
$fileStorage = new FileStorage($dir);
$config = $fileStorage->read('views.view.my_view');
/** #var \Drupal\Core\Config\Entity\ConfigEntityStorage $storage */
$storage = \Drupal::entityTypeManager()
->getStorage('view');
/** #var \Drupal\views\Entity\View $view */
$view = $storage->create($config);
$view->save();

Resources