I'm trying to build an array and while doing so, I was wondering if it makes any difference in how you create such array. Things I have in mind are performance, maintainability, readability,...
Declaration 1:
$data = array(
'my_array' => array(
'table' => array(
'group' => t('My group'),
'join' => array(
'commerce_product' => array(
'left_field' => 'sku',
'field' => 'artc',
),
),
);
Declaration 2:
$data['my_array']['table']['group'] = 'My group';
$data['my_array']['table']['join']['commerce_product'] = array(
'left_field' => 'sku',
'field' => 'artc',);
Because for some reason, my Drupal site accepts the first declaration but not the second. Since it's about creating arrays in PHP I don't think it has something to do with Drupal, rather with the way the array is created...
The feature of automatically creating an array with the second syntax (assigning a value to a key in a non-existent variable) is a more recent feature than using the array syntax.
Check the PHP version installed on your two servers.
Related
I am trying to implement the 'InArray' validator in Zend 2 on a form and it keeps on returning invalid. Here is the code:
The Form Element setup:
$enquiryType = new Element\Select('enquiryType');
$enquiryType->setLabel('* What is your enquiry about?')
->setLabelAttributes(array('class' => 'sq-form-question-title'))
->setAttribute('class', 'sq-form-field required')
->setValueOptions($enquiryTypes);
The Filter/Validator setup:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes));
And here is the array that gets passed into $enquiryTypes via the module.config.php file
'enquiryCategories' => array(
'empty_option' => 'Please select an option',
array(
'label' => 'General enquiries',
'options' => array(
'skype' => 'Skype with your library feedback',
'question' => 'Ask a question',
'feedback' => 'Library feedback',
'eresource' => 'Electronic resources (e.g. e-book, e-journal, database)',
'webbridge' => 'WebBridge Problems',
'dro' => 'DRO'
)
),
array(
'label' => 'Application to review',
'options' => array(
'10400' => 'I\'ve returned the item',
'10401' => 'I didn\'t know about overdue points but now I have some',
'10402' => 'Why did I get this invoice?',
'10403' => 'The item I borrowed is lost',
'10404' => 'The item I borrowed has been damaged',
'10405' => 'I never got/had the book',
'10406' => 'Other'
)
)
),
I have tried different variations of this (using the recursive validation also) but have not been able to work this out.
One thing that I'd try, is as follows:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes['enquiryCategories']));
The reason I say that, is that it looks like you might be creating an array inside of the array perhaps. Unless I've misunderstood the description.
If that isn't working for you then maybe you might need to explore the Explode option as pointed out in the following question
ZF2: How do I use InArray validator to validate Multiselect form element?
Good luck.
I finally got a working solution for this. I feel there should be a better solution but I could not find one.
Here is the filter I used:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => array_keys(
$enquiryTypes[0]['options']+$enquiryTypes[1]['options']
)));
$enquiryType->getFilterChain()
->attach(new Filter\StringToLower())
->attachByName('StripTags');
Basically I had to disect the array options into a straight associative array. As the array remains static in this instance then this works well.
If the data becomes dynamic then something more would be required (loop through and find the 'option' key, add children to filter array etc...)
I have this situation where I could pre-define the array in this way:
$packages = array(
'0' => array(
'name' => 'Hotel1', //pcg name
'curr' => '$',
'amount' => '125',
'period' => 'NIGHT', //pcg duration
'client_data' => array(
'Name' =>'Adrien',
'Addr' =>'Sample Street',
'Payment' =>'Credit Card',
'Nights' =>'6',
)
),
);
Or
$packages = array();
$packages[] = array(
'name' => 'PREMIUM', //pcg name
'curr' => '$',
'amount' => '3.95',
'period' => 'MONTH', //pcg duration
'features' => array(
'Clients' =>'100',
'Invoices' =>'300 <small>MONTH</small>',
'Products' =>'30',
'Staff' =>'1',
)
);
The data will be static always so I wont be fetching this from
a sql query or a dynamic search. Would it make any difference
in terms of performance (the slightest difference could be helpful)
by using the first or the second "method" or they're actually 100%
identical in terms of performance.
Theorically the "dynamic" array creation might be slower because
it needs to check the size of the array, the last array index and
maybe other things such as those.
Thank you.
One simple task like that takes absolutely no resources in current hardware reality. Even in my first PC, a 386DX 20MHz it would not make that difference ;)
Anyway, I executed 1k times both options:
FIRST OPTION average:
0.000114s
SECOND OPTION average:
0.000108s
Be happy!
I have an array of models that looks something like this. The models are extensions of the base Yii model class (BazClass), so that's a little bit of a custom solution, but I don't see why it shouldn't work.
$list = array
(
0 => FooClass#1
(
[BazClass:_attributes] => array
(
'FOO_ATTRIBUTE' => '4567'
'BAZ_ATTRIBUTE' => '1234'
'NAME' => 'FOO BAR'
)
[BazClass:_related] => array()
[_md] => null
[CModel:_errors] => array()
[CModel:_validators] => null
[CModel:_scenario] => ''
[CComponent:_e] => null
[CComponent:_m] => null
),
)
I made this a data provider by doing so:
$dataProvider = new CArrayDataProvider($list, array(
'pagination'=>array(
'pageSize'=>10,
),
));
$dataProvider->setData($list);
And try to render it in the view like so. Basically I'm just trying to show a list of the names, with the column named "Name".
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'header' => 'Name',
'value' => $data->NAME,
),
),
));
The examples in the CGridView documentation make it look like that is possible, but the error I get is:
Either "name" or "value" must be specified for CDataColumn.
Well, I did specify a value, obviously, but it seems to be null. I also tried $data['NAME'] (because I somewhere read that the CArrayDataProvider doesn't return models), but it still evaluates to null.
I also checked that $dataProvider->getData() returns the same list as I passed it.
What gives?
you should place quotes around your value otherwise it gets interpreted in the wrong context
array( 'header' => 'Name', 'value' => '$data->NAME', ),
The following query returns an array containing the proper ids, but null for all values.
If I remove the aggregation function (AVG()), it returns values (not the averaged ones of course), if I choose e.g. find('all') it returns the average, but not in the list format I want (I could work with that, but I want to try to do it with 'list' first).
$progress = $this->Trial->find('list', array(
'fields' => array(
'Trial.session_id',
'AVG(Trial.first_reaction_time_since_probe_shown) AS average_reaction_time'
),
'group' => 'Trial.session_id',
'conditions' => array(
'Trial.first_valid_response = Trial.probe_on_top',
'TrainingSession.user_id IS NOT NULL'
),
'contain' => array(
'TrainingSession' => array(
'conditions' => array(
'TrainingSession.user_id' => $this->Auth->user('id')
)
)
),
'recursive' => 1,
));
The generated SQL query returns exactly the result I want, when I send it to the DB via PhpMyAdmin.
SELECT
`Trial`.`session_id`,
AVG(`Trial`.`first_reaction_time_since_probe_shown`) AS average_reaction_time
FROM
`zwang`.`trials` AS `Trial`
LEFT JOIN
`zwang`.`training_sessions` AS `TrainingSession` ON (
`Trial`.`session_id` = `TrainingSession`.`id` AND
`TrainingSession`.`user_id` = 1
)
WHERE
`Trial`.`first_valid_response` = `Trial`.`probe_on_top`
GROUP BY
`Trial`.`session_id`
I've examined the source for find('list'). I think it's due to the "array path" for accessing the list getting screwed up when using functions in the query, but I couldn't fix it yet (or recognise my abuse of CakePHP logic).
Once I posted the question, Stackoverflow started relating the correct answers to me.
Apparently, it can't be done with 'list' without virtualFields.
I didn't expect that because it worked using the other find-types.
$this->Trial->virtualFields = array(
'average_reaction_time' => 'AVG(Trial.first_reaction_time_since_probe_shown)'
);
$progress = $this->Trial->find('list', array(
'fields' => array('Trial.session_id','average_reaction_time')
/* etc... */
));
I'm using the containable behavior to look at several tables.
$this->paginate = array(
'contain' => array(
'Co' => array('fields' => array('ref')),
'CoItemType' => array('fields' => array('name')),
'Casing' => array(
'fields' => array('id','barcode','CONCAT(plant_dot,size_dot,product_line_dot,production_week) as dot'),
'Customer' => array('fields' => array('company_name')),
)
)
);
This works as expected. However I am integrating this with jQuery datatables and the way dataTables passes over conditions it does not specifiy a field. So I'd like to do conditions outside of the contains like so...
'conditions' = array(
'OR' => array(
array("Table.field_name LIKE " => '%'.$parameter.'%'),
array("Table.field_name LIKE " => '%'.$parameter.'%'),
array("Table.field_name LIKE " => '%'.$parameter.'%')
)
)
Of course this is not possible since the containable behavior wants you to include the conditions under the tables key in the contain array. This is frustrating, does anyone have a solution or workaround around to this problem?
I am using CakePHP 2.x
Use Linkable Behavior as noted in comments.