Yii mongodbsuite two and more database connections - mongodb

How to make two or more database connections in Yii mongodbsuite?
I added 2 DB components in main.php:
'components' => array(
'mongodb' => array(
'class' => 'common\extensions\MongoDB',
'connectionString' => 'mongodb://localhost:27017/table1',
'dbName' => 'table1',
'fsyncFlag' => false,
'persistentConnection' => 'x',
'replicaSet' => false,
'safeFlag' => true,
'useCursor' => false,
),
'mongodb2' => array(
'class' => 'common\extensions\MongoDB',
'connectionString' => 'mongodb://localhost:27017/table2',
'dbName' => 'table2',
'fsyncFlag' => false,
'persistentConnection' => 'x',
'replicaSet' => false,
'safeFlag' => true,
'useCursor' => false,
),
)
But how to use mongodb2 in query (ex: ->findByAttributes()) i don't know.
Please provide some example queries using the mongodb2 connection above.

I just add 'mongodb2' => array to 'components' => array and add to models (ex: User) who extends EMongoDocument:
public function getMongoDBComponent() {return Yii::app()->mongodb2;}
And it is work!

Have a look at Multiple db support in Yii.
Basically you have to modify your active record class by overriding the getDbConnection() methods. (In the given link you have a better example using an intermediate inheritance layer)

Related

Validation error "This value should not be blank" when submitting a form on production website

I'm developing a website using php 7.4, symfony 5.4 and twig. This website is deployed on several servers.
On one of the servers (RedHat), a form cannot be submitted. I get the following error 4 times : "This value should not be blank.".
The messages appear on top of the form and aren't attached to a particular field.
I can't reproduce this error on another server, nor on my development environment...
The problem might comes from a validator but I'm not sure whether it's a symfony or a doctrine error.
The POST data is identical on production server and dev environment :
report_selection[iFrame]: 1
report_selection[dteFrom]: 2023-01-30 07:00
report_selection[dteTo]: 2023-01-31 07:00
report_selection[reportType]: 1
report_selection[size]: 200
report_selection[product]: 1
report_selection[submit]:
I assume that the empty field submit is not a problem since other forms work fine while having the same field empty.
The database structure is the same on all servers.
Here is the form's code :
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$bDisplaySize = $options['bDisplaySize'];
$bDisplayReportType = $options['bDisplayReportType'];
$bDisplayProduct = $options['bDisplayProduct'];
$defaultValue = $options['defaultValue'];
$em = $options['entity_manager'];
list($H, $m) = explode(":", $iShiftStart);
$initialFromDate = (new DateTime())->modify('-'.$H.' hour');
$initialFromDate = $initialFromDate->modify('-1 day');
$initialFromDate->setTime((int)$iShiftStart, (int)$m, 0);
$initialToDate = clone $initialFromDate;
$initialToDate = $initialToDate->modify('+1 day');
$builder->add(
'iFrame',
ChoiceType::class,
array(
'label' => 'master.preselection',
'choices' => [
'master.yesterday' => false,
'master.today' => false,
'master.thisWeek' => false,
'master.lastWeek' => false,
'master.thisMonth' => false,
'master.lastMonth' => false,
'master.memomryDate' => false,
],
'attr' => ['onchange' => 'refreshPreselectedChoices()'],
'choice_attr' => [
'master.yesterday' => [],
'master.today' => ['selected' => 'selected'],
'master.thisWeek' => [],
'master.lastWeek' => [],
'master.thisMonth' => [],
'master.lastMonth' => [],
'master.memomryDate' => ['disabled' => true],
],
)
);
$builder->add(
'dteFrom',
TextType::class,
array(
'label' => 'form.from',
'data' => $initialFromDate->format('Y-m-d H:i'),
'attr' => array(
'style' => 'width:150px;',
'oninput' => 'dteFromToCustom()',
'onchange' => 'dteFromToCustom()',
),
)
);
$builder->add(
'dteTo',
TextType::class,
array(
'label' => 'form.to',
'data' => $initialToDate->format('Y-m-d H:i'),
'attr' => array(
'label' => 'form.to',
'style' => 'width:150px;',
'oninput' => 'dteFromToCustom()',
'onchange' => 'dteFromToCustom()',
),
)
);
if ($bDisplayReportType) {
$builder->add(
'reportType',
ChoiceType::class,
array(
'label' => 'summaryReport.data',
'choices' => array(
'summaryReport.type1' => '1',
'summaryReport.type2' => '2',
),
)
);
}
if ($bDisplaySize) {
$builder->add(
'size',
EntityType::class,
array(
'class' => ProductsSizeSpecs::class,
'choice_label' => 'rSize',
'choice_value' => 'rSize',
'placeholder' => '',
'label' => 'form.size',
'required' => false,
'mapped' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->groupBy('e.rSize')
->orderBy('e.rSize', 'ASC');
},
)
);
}
if ($bDisplayProduct) {
$builder->add(
'product',
EntityType::class,
array(
'class' => Products::class,
'choice_label' => 'sNumber',
'choice_value' => 'sNumber',
'placeholder' => '',
'label' => 'master.product',
'required' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->groupBy('e.sNumber')
->orderBy('e.sNumber', 'ASC');
},
)
);
}
$builder->add(
'submit',
SubmitType::class,
array(
'label' => 'form.submit',
'attr' => array('class' => 'btn btn-primary'),
)
);
}
Other forms use the exact same code with more or less options.
I search a way to debug this on the production server (list/dump of 'blank' fields?).
Any hint will be appreciated, thanks !
Indeed I had some #Assert\NotBlank on several columns of an Entity.
Why the error was only on this server :
An instance (db record) of this Entity was NULL on those columns (which is an anormal behavior).
All the instances where retrieved to populate the form's dropdowns (as 'default' data).
It looks like the validator is checking the submitted 'data' AND those 'default' values since they are part of the form.
There were 4 asserted columns, so that's why I had 4 errors messages.
What I've done to find this out :
Added a dump($this->form->getErrors()) instruction on the callback processing the submitted form. It displayed the 4 entity's columns giving me hard time.
Went into db to see the corrupted record, and deleted it.
To prevent this in the future I might change the default values of these columns from NULL to something else, a basic string or a 0 value, and search the process that led to this corrupted record in db.
Thanks for your hints guys !

TYPO3 8 dbal mapping with other server

I've a problem.
I just installed a new TYPO3 8 with adodb and dbal extensions.
Now I have an other server with a MySQLi Server and some custom tables in one database.
I want to show and edit the data from that other MySQLi Server Database Table named account in my TYPO3. For that, I have created my own extension with an model named tx_base_domain_model_account with as example 2 fields.
After that I created a dbal mapping with the following configuration:
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['dbal'] = array(
'handlerCfg' => array(
'_DEFAULT' => array(
'type' => 'native',
'config' => array(
'driver' => 'mysqli'
)
),
'_otherServer' => array(
'type' => 'native',
'config' => array(
'username' => 'username',
'password' => 'password',
'host' => '192.168.177.XX',
'database' => 'account',
)
),
),
'table2handlerKeys' => array(
'account' => '_otherServer'
),
'debugOptions' => array(
'enabled' => true,
'printErrors' => true,
'EXPLAIN' => 1,
'parseQuery' => 1,
'joinTables' => 1
),
'mapping' => array(
'tx_base_domain_model_account' => array(
'mapTableName' => 'account',
'mapFieldNames' => array (
'uid' => 'id',
'pid' => 119,
'login' => 'login',
'password' => 'password',
'cruser_id' => 1
)
)
)
);
But I can't see, edit or whatever the data from that other server database table.
Can you help me?
Thank you
With the switch to doctrine-dbal in core v8, the core extensions 'dbal' and 'adodb' have been obsoleted. See https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Database/Configuration/Index.html for configuration details on how to map tables to a different dbms using doctrine-dbal.

TYPO3 list module: custom records not showing

I am using TYPO3 7.6.11.
I wrote an provider extension to add some ts-code, templates, and viewhelpers.
After that, I wanted to add a custom data record (to use in the Backend).
I added the table in the ext_tables.sql.
I have a TCA-config under /[extension]/Configuration/TCA/tablename.php
I added
TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages('tablename');
TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToInsertRecords('tablename');
to my ext_tables.php
Did I miss something?
I get a new record type under "System Records" in the List Module. I can add such an record, and the TCA-config seems to work fine for the record form.
But after saving, I have no record in the list view. The DB is looking fine. The record is saved correctly in my new table. What am I doing wrong?
Thanks
Edit:
crtl:
'ctrl' => array (
'title' => 'LLL:EXT:svkcore/Resources/Private/Language/locallang.xlf:records.title',
'label' => 'title',
'label_alt' => '',
'label_alt_force' => TRUE,
'default_sortby' => 'ORDER BY datetime DESC',
'prependAtCopy' => 'LLL:EXT:lang/locallang_general.php:LGL.prependAtCopy',
'versioningWS' => TRUE,
'versioning_followPages' => TRUE,
'origUid' => 't3_origuid',
'shadowColumnsForNewPlaceholders' => 'sys_language_uid,l18n_parent,starttime,endtime,fe_group',
'dividers2tabs' => TRUE,
'useColumnsForDefaultValues' => 'type',
'transOrigPointerField' => 'l18n_parent',
'transOrigDiffSourceField' => 'l18n_diffsource',
'languageField' => 'sys_language_uid',
'crdate' => 'crdate',
'tstamp' => 'tstamp',
'delete' => 'deleted',
'type' => 'type',
'cruser_id' => 'cruser_id',
'editlock' => 'editlock',
'enablecolumns' => array (
'disabled' => 'hidden',
'starttime' => 'starttime',
'endtime' => 'endtime',
'fe_group' => 'fe_group',
),
'typeicon_column' => 'type',
'typeicons' => array (
'1' => 'EXT:svkcore/res/gfx/svkcore_inturl.gif',
'2' => 'EXT:svkcore/res/gfx/svkcore_exturl.gif',
),
'thumbnail' => 'image',
'iconfile' => 'EXT:svkcore/res/gfx/ext_icon.gif',
'searchFields' => 'uid,title,short,bodytext'),
'interface' => Array (
'showRecordFieldList' => 'title,hidden,datetime_start,starttime,archivedate,category,short,image,record_files'
),
Since Typo3 7 it is possible to mask the list-view. This is configured via PageTSConfig, have a look at your info-Module (select the correct page in the page tree) and check the TSConfig there.
The configuration can be found in the following path:
mod.web_list.allowedNewTables
Check in ext_tables.php if you have everything needed for your new table : Typoscript inclusion, language file, exemple :
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile($_EXTKEY, 'Configuration/TypoScript', 'My TS configuration');
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addLLrefForTCAdescr('tx_myext_domain_model_mytable', 'EXT:my_ext/Resources/Private/Language/locallang_csh_tx_myext_domain_model_mytable.xlf');
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages('tx_myext_domain_model_mytable');
Are you sure the new records are stored in the current page : have a look at the TS "persistence.storagePid".
You can check in the database wich pid is used for your new records.
Regards,
Florian

Magento "visible" config key not recognized in EAV custom attribute

I am using the getDefaultEntities() function which is run from my installer script. It mostly works, almost all of the attribute config keys reflect properly in the Attributes section of the admin. However the "visible," "visible_on_front" and some of the other properties do not work at all. My custom attribute is always set to not visible, not visible on front end. Can anyone spot what I am doing wrong?
class Ia_AdvancedShipping_Model_Resource_Eav_Mysql4_Setup extends Mage_Eav_Model_Entity_Setup
{
/**
* #return array
*/
public function getDefaultEntities()
{
return array(
'catalog_product' => array(
'entity_model' => 'catalog/product',
'attribute_model' => 'catalog/resource_eav_attribute',
'table' => 'catalog/product',
'additional_attribute_table' => 'catalog/eav_attribute',
'entity_attribute_collection' => 'catalog/product_attribute_collection',
'attributes' => array(
'iaadvancedshipping_profile' => array(
'group' => 'Advanced Shipping',
'label' => 'Shipping Profiles',
'type' => 'varchar',
'input' => 'select',
'source' => 'iaadvancedshipping/product_attribute_source_profiles',
'default' => '0',
'class' => '',
'backend' => '',
'frontend' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'visible' => true,
'required' => false,
'user_defined' => false,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => true,
'visible_in_advanced_search' => false,
'unique' => false
),
)
)
);
}
}

How to validate a checkbox in ZF2

I've read numerous workarounds for Zend Framework's lack of default checkbox validation.
I have recently started using ZF2 and the documentation is a bit lacking out there.
Can someone please demonstrate how I can validate a checkbox to ensure it was ticked, using the Zend Form and Validation mechanism? I'm using the array configuration for my Forms (using the default set-up found in the example app on the ZF website).
Try this
Form element :
$this->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'agreeterms',
'options' => array(
'label' => 'I agree to all terms and conditions',
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 'no'
),
));
In filters, add digit validation
use Zend\Validator\Digits; // at top
$inputFilter->add($factory->createInput(array(
'name' => 'agreeterms',
'validators' => array(
array(
'name' => 'Digits',
'break_chain_on_failure' => true,
'options' => array(
'messages' => array(
Digits::NOT_DIGITS => 'You must agree to the terms of use.',
),
),
),
),
)));
You could also just drop the hidden form field (which I find a bit weird from a purist HTML point of view) from the options instead of setting its value to 'no' like this:
$this->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'agreeterms',
'options' => array(
'label' => 'I agree to all terms and conditions',
'use_hidden_element' => false
),
));
I had the same problem and did something similar to Optimus Crew's suggestion but used the Identical Validator.
If you don't set the checked_value option of the checkbox and leave it as the default it should pass in a '1' when the data is POSTed. You can set it if you require, but make sure you're checking for the same value in the token option of the validator.
$this->filter->add(array(
'name' => 'agreeterms',
'validators' => array(
array(
'name' => 'Identical',
'options' => array(
'token' => '1',
'messages' => array(
Identical::NOT_SAME => 'You must agree to the terms of use.',
),
),
),
),
));
This won't work if you use the option 'use_hidden_element' => false for the checkbox for the form. If you do this, you'll end up displaying the default NotEmpty message Value is required and can't be empty
This isn't directly related to the question, but here's some zf2 checkbox tips if you're looking to store a user's response in the database...
DO use '1' and '0' strings, don't bother trying to get anything else to work. Plus, you can use those values directly as SQL values for a bit/boolean column.
DO use hidden elements. If you don't, no value will get posted with the form and no one wants that.
DO NOT try to filter the value to a boolean. For some reason, when the boolean value comes out to be false, the form doesn't validate despite having 'required' => false;
Example element creation in form:
$this->add([
'name' => 'cellPhoneHasWhatsApp',
'type' => 'Checkbox',
'options' => [
'label' => 'Cell phone has WhatsApp?',
'checked_value' => '1',
'unchecked_value' => '0',
'use_hidden_element' => true,
],
]);
Example input filter spec:
[
'cellPhoneHasWhatsApp' => [
'required' => false,
],
]
And here's an example if you want to hide some other form fields using bootstrap:
$this->add([
'name' => 'automaticTitle',
'type' => 'Checkbox',
'options' => [
'label' => 'Automatically generate title',
'checked_value' => '1',
'unchecked_value' => '0',
'use_hidden_element' => true,
],
'attributes' => [
'data-toggle' => 'collapse',
'data-target' => '#titleGroup',
'aria-expanded' => 'false',
'aria-controls' => 'titleGroup'
],
]);
I'm a ZF2 fan, but at the end of the day, you just have to find out what works with it and what doesn't (especially with Forms). Hope this helps somebody!
Very old question, but figured it might still be used/referenced by people, like me, still using Zend Framework 2. (Using ZF 2.5.3 in my case)
Jeff's answer above helped me out getting the right config here for what I'm using. In my use case I require the Checkbox, though leaving it empty will count as a 'false' value, which is allowed. His answer helped me allow the false values, especially his:
DO NOT try to filter the value to a boolean. For some reason, when the boolean value comes out to be false
The use case is to enable/disable certain entities, such as Countries or Languages so they won't show up in a getEnabled[...]() Repository function.
Form element
$this->add([
'name' => 'enabled',
'required' => true,
'type' => Checkbox::class,
'options' => [
'label' => _('Enabled'),
'label_attributes' => [
'class' => '',
],
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 0,
],
'attributes' => [
'id' => '',
'class' => '',
],
]);
Input filter
$this->add([
'name' => 'enabled',
'required' => true,
'validators' => [
[
'name' => InArray::class,
'options' => [
'haystack' => [true, false],
],
],
],
])