How to get value of element in the same array when initialize - php

I Think it's a strange question :
i dont need answer with loop or push to array i'm just wondering about the idea
I'm trying ti initialize an array ,, but i need to read the previous element like this,
return $recourd_list = array(
'clients'=> array(
'route' => 'clients.index',
'title' => 'fullname',
'list' => Clients::orderBy('id', 'desc')->take(5)->get(),
'count' => Clients::count(),
'class' => 'bgm-lightgreen',
'diff' => 5 - $recourd_list['clients']['count'],
),
'sliders'=> array(
'route' => 'sliders',
'title' => 'title',
'list' => Sliders::orderBy('id', 'desc')->take(5)->get(),
'count' => Sliders::count(),
'class' => 'bgm-rightBlue Oil-color',
'diff' => 5 - $recourd_list['sliders']['count'],
),
'sponsors'=> array(
'route' => 'sponsors.index',
'title' => 'title',
'list' => Sponsors::orderBy('id', 'desc')->take(5)->get(),
'count' => Sponsors::count(),
'class' => 'bgm-nave dark-green',
'diff' => 5 - $recourd_list['sponsors']['count'],
),
'packages'=> array(
'route' => 'packages',
'title' => 'title',
'list' => Packages::orderBy('id', 'desc')->take(5)->get(),
'count' => Packages::count(),
'class' => 'bgm-bluegray',
'diff' => 5 - $recourd_list['packages']['count'],
),
'event_schedule'=> array(
'route' => 'event_schedule.index',
'title' => 'title',
'list' => EventSchedule::orderBy('id', 'desc')->take(5)->get(),
'count' => EventSchedule::count(),
'class' => 'bgm-orange',
'diff' => 5 - $recourd_list['event_schedule']['count'],
),
);
I need to read the count element in diff element .. is that way to do that when initialize array
Thanks All

No, this isn't possible as the array technically won't be defined at that point.
One way to achieve this would be to use something like array_map.
http://php.net/manual/en/function.array-map.php
$recourd_list = array(
'clients'=> array(
'route' => 'clients.index',
'title' => 'fullname',
'list' => Clients::orderBy('id', 'desc')->take(5)->get(),
'count' => Clients::count(),
'class' => 'bgm-lightgreen',
),
'sliders'=> array(
'route' => 'sliders',
'title' => 'title',
'list' => Sliders::orderBy('id', 'desc')->take(5)->get(),
'count' => Sliders::count(),
'class' => 'bgm-rightBlue Oil-color',
),
'sponsors'=> array(
'route' => 'sponsors.index',
'title' => 'title',
'list' => Sponsors::orderBy('id', 'desc')->take(5)->get(),
'count' => Sponsors::count(),
'class' => 'bgm-nave dark-green',
),
'packages'=> array(
'route' => 'packages',
'title' => 'title',
'list' => Packages::orderBy('id', 'desc')->take(5)->get(),
'count' => Packages::count(),
'class' => 'bgm-bluegray',
),
'event_schedule'=> array(
'route' => 'event_schedule.index',
'title' => 'title',
'list' => EventSchedule::orderBy('id', 'desc')->take(5)->get(),
'count' => EventSchedule::count(),
'class' => 'bgm-orange',
),
);
then
return array_map(function ($item) {
$item['diff'] = $item['count'] - 5;
return $item;
}, $recourd_list);
Alternatively, you could use map with Collections
https://laravel.com/docs/5.3/collections#method-map
return collect($recourd_list)->map(function ($item) {
$item['diff'] = $item['count'] - 5;
return $item;
})->toArray();
Hope this helps!

short answer:
no.
But since you are, at init time, defining the Count, why not do this:
'diff' => 5 - Clients::count(),
so with the entire example:
return $recourd_list = array(
'clients' => array(
'route' => 'clients.index',
'title' => 'fullname',
'list' => Clients::orderBy('id', 'desc')->take(5)->get(),
'count' => Clients::count(),
'class' => 'bgm-lightgreen',
'diff' => 5 - Clients::count(),
),
'sliders' => array(
'route' => 'sliders',
'title' => 'title',
'list' => Sliders::orderBy('id', 'desc')->take(5)->get(),
'count' => Sliders::count(),
'class' => 'bgm-rightBlue Oil-color',
'diff' => 5 - Sliders::count(),
),
'sponsors' => array(
'route' => 'sponsors.index',
'title' => 'title',
'list' => Sponsors::orderBy('id', 'desc')->take(5)->get(),
'count' => Sponsors::count(),
'class' => 'bgm-nave dark-green',
'diff' => 5 - Sponsors::count(),
),
'packages' => array(
'route' => 'packages',
'title' => 'title',
'list' => Packages::orderBy('id', 'desc')->take(5)->get(),
'count' => Packages::count(),
'class' => 'bgm-bluegray',
'diff' => 5 - Packages::count(),
),
'event_schedule' => array(
'route' => 'event_schedule.index',
'title' => 'title',
'list' => EventSchedule::orderBy('id', 'desc')->take(5)->get(),
'count' => EventSchedule::count(),
'class' => 'bgm-orange',
'diff' => 5 - EventSchedule::count(),
),
);

Related

Can’t filter search result

My Elasticsearch query is like that:
array(
'index' => 'myindex',
'type' => 'myindextype',
'from' => 0,
'size' => 500,
'body' => array(
'query' => array(
'filtered' => array(
'filter' => NULL,
'query' => array(
'query_string' => array(
'default_operator' => 'AND',
'query' => 'atm*',
'minimum_should_match' => '80%',
'default_field' => 'index'
)
)
)
)
)
);
Result is like that:
array(
'took' => 6,
'timed_out' => false,
'_shards' => array(
'total' => 5,
'successful' => 5,
'failed' => 0
),
'hits' => array(
'total' => 492,
'max_score' => 1,
'hits' => array(
0 => array(
'_index' => 'myindex',
'_type' => 'myindextype',
'_id' => 'Branch-571',
'_score' => 1,
'_source' => array(
'indexId' => 'Branch-571',
'objId' => '571',
'index' => 'atm Baki CNaxcivanski lisey Baki sheh Zig shossesi Admiral Naximov kuc 1 ',
'type' => 'Branch',
'title' => 'Bakı C.Naxçıvanski lisey'
)
),
.................................................................................................
196 => array(
'_index' => 'myindex',
'_type' => 'myindextype',
'_id' => 'Page-114',
'_score' => 1,
'_source' => array(
'indexId' => 'Page-114',
'objId' => 'Page-114',
'index' => 'atm Baki CNaxcivanski lisey Baki sheh Zig shossesi Admiral Naximov kuc 1 ',
'type' => 'Page',
'title' => 'Kreditlər'
)
)
.................................................................................................
)
)
);
I want to filter result and get results where 'type' => 'Branch' and I change query like that
array(
'index' => 'myindex',
'type' => 'myindextype',
'from' => 0,
'size' => 10,
'body' => array(
'query' => array(
'filtered' => array(
'filter' => array(
'bool' => array(
'must' => array(
'term' => array(
'type' => 'Branch'
)
)
)
),
'query' => array(
'query_string' => array(
'default_operator' => 'AND',
'query' => 'atm*',
'minimum_should_match' => '80%',
'default_field' => 'index'
)
)
)
)
)
);
But this search return nothing.
array(
'took' => 2,
'timed_out' => false,
'_shards' => array(
'total' => 5,
'successful' => 5,
'failed' => 0
),
'hits' => array(
'total' => 0,
'max_score' => NULL,
'hits' => array()
)
);
I think query is right but no idea why it didn't get any result.
Mapping is
array(
'myindex' => array(
'mappings' => array(
'myindextype' => array(
'properties' => array(
'index' => array(
'type' => 'string'
),
'indexId' => array(
'type' => 'string'
),
'objId' => array(
'type' => 'string'
),
'title' => array(
'type' => 'string'
),
'type' => array(
'type' => 'string'
)
)
)
)
)
)
I have find answer myself. The search query must be like that
POST _search
{
"query": {
"bool" : {
"must" : {
"query_string" :{
"query":"atm*",
"default_operator":"AND",
"minimum_should_match":"80%",
"default_field":"index"
}
},
"filter": {
"term": {
"type.keyword": "Branch"
}
}
}
}
}
All is working good now.

How to create fieldset collection using form factory in zf2

I'm trying to create a form that contains a collection of fieldsets using only array specs and Zend\Form\Factory.
Here is how I create the form using the factory:
$factory = new Zend\Form\Factory();
$fieldset = $factory->createFieldset(array(
'elements' => array(
array(
'spec' => array(
'name' => 'name',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Name',
),
),
),
array(
'spec' => array(
'name' => 'driverClass',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Driver',
),
),
),
),
'input_filter' => array(
'name' => array(
'required' => true,
),
),
));
$form = $factory->createForm(array(
'name' => 'application-form',
'attributes' => array(
'role' => 'form',
),
'elements' => array(
array(
'spec' => array(
'type' => 'Collection',
'name' => 'connection',
'options' => array(
'label' => 'Connections',
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'count' => 2,
'target_element' => $fieldset,
),
),
),
array(
'spec' => array(
'name' => 'security',
'type' => 'Csrf',
'attributes' => array(
'required' => 'required',
),
),
),
array(
'spec' => array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'class' => 'btn btn-sm btn-primary',
),
'options' => array(
'label' => 'Apply',
),
),
),
),
));
The resulting form works fine when I try to set data and render form elements. But when I validate it and retrieve data, like so (in a controller):
$form->setData($this->getRequest()->getPost());
if ($form->isValid() === true) {
$data = $form->getData();
var_dump($this->getRequest()->getPost());
var_dump($data);
}
With this set of data as POST:
object(Zend\Stdlib\Parameters)[141]
private 'storage' (ArrayObject) =>
array (size=3)
'connection' =>
array (size=2)
0 =>
array (size=2)
'name' => string 'orm_default' (length=11)
'driverClass' => string 'Doctrine\DBAL\Driver\PDOMySql\Driver' (length=36)
1 =>
array (size=2)
'name' => string 'blog' (length=4)
'driverClass' => string 'Doctrine\DBAL\Driver\PDOMySql\Driver' (length=36)
'submit' => string '' (length=0)
'security' => string '20d5c146d8874dc804948e962d5de91b-87c9e4097f9140d259efb5c589a05d6b' (length=65)
The array returned by the call to $form->getData() shows an empty collection:
array (size=3)
'security' => string '20d5c146d8874dc804948e962d5de91b-87c9e4097f9140d259efb5c589a05d6b' (length=65)
'submit' => string '' (length=0)
'connection' =>
array (size=0)
empty
What am I missing?
The expected result is a collection, named 'connection' in this example, containing two arrays representing the two fieldsets as specified by the POST data. I have a feeling this has to do with a missing InputFilter (or at least its specs) because I have managed to obtain the expected result when I implement a fieldset class that extends Zend\Form\Fieldset and implements Zend\InputFilter\InputFilterProviderInterface.
Just discovered this class Zend\Form\InputFilterProviderFieldset which does exactly what I missed.
I added a type in the fieldset specs and changed the input filter specs (which is mandatory) like so:
$fieldset = $factory->createFieldset(array(
'type' => 'Zend\Form\InputFilterProviderFieldset',
'elements' => array(
array(
'spec' => array(
'name' => 'name',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Name',
),
),
),
array(
'spec' => array(
'name' => 'driverClass',
'type' => 'Text',
'attributes' => array(
'class' => 'form-control input-sm',
),
'options' => array(
'label' => 'Driver',
),
),
),
),
'options' => array(
'input_filter_spec' => array(
'name' => array(
'required' => true,
),
),
),
));
And it works fine now. Hope this helped someone.

ZF2's custom validator's $context suddenly gives 'bar'=>array() when posting bar[0][foo]='xyz'

I have a custom validator using $context that has been working for over a year.
The $context contains all posted parameters except for "bar" which is an empty array although it is posted as bar[0][description]. The array used to contain one or more arrays with key-value-pairs.
This seems to be the case since updating from version 2.3.2 to 2.5.1
I can't even check the 2.5 documentation since it's not available, Google didn't turn up anything close to the issue, ... was the behaviour changed or is this a bug?
Edit:
In .../Lorem/Form/FooForm.php I include a fieldset:
public function __construct() {
// ...
$this->add(array(
'type' => 'Collection',
'name' => 'bar',
'options' => array(
'label'=> '',
'count' => 1,
'should_create_template' => TRUE,
'allow_add' => TRUE,
'use_as_base_fieldset' => TRUE,
'target_element' => array(
'type' => 'Lorem\Fieldset\BarFieldset'
)
)
));
}
In .../Lorem/Fieldset/BarFieldset.php I have:
public function __construct() {
parent::__construct('bar');
$this->setHydrator(new ReflectionHydrator())
->setObject(new Bar());
$this->add(array(
'name' => 'description',
'type' => 'Textarea',
'attributes' => array(
'rows' => 3,
'cols' => 40,
),
));
$this->add(array(
'name' => 'amount',
'attributes' => array(
'type' => 'Text',
'class' => 'input-bar-amount',
'maxlength' => 9,
),
));
// ...
}
public function getInputFilterSpecification()
{
return array(
'description' => array(
'required' => TRUE,
'filters' => array(
array('name' => 'StripTags'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'break_chain_on_failure' => TRUE,
'options' => array(
'messages' => array(
'isEmpty' => 'Please enter a description.',
),
),
),
),
),
'amount' => array(
'required' => TRUE,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'break_chain_on_failure' => TRUE,
'options' => array(
'messages' => array(
'isEmpty' => 'Please enter amount.',
),
),
),
array(
'name' => 'Float',
'break_chain_on_failure' => TRUE,
'options' => array(
'locale' => 'de',
'messages' => array(
'floatInvalid' => 'Invalid input. String, Integer oder Float expected.',
'notFloat' => 'Input ist not a floating point number.',
),
),
),
array(
'name' => 'Between',
'break_chain_on_failure' => TRUE,
'options' => array(
'min' => -1000000,
'max' => 1000000,
'messages' => array(
'notBetween' => "Only values between '%min%' and '%max%' EUR are allowed.",
'notBetweenStrict' => "Only values between '%min%' and '%max%' EUR are allowed.",
),
),
),
),
),
// ...
);
}

Aggregations are empty with keyword tokenizer

For an aggregation result i have a field (type_name2) in my mapping with a lowercased filter and a keyword tokenizer. But if I set this filter and tokenizer to the field my bucket is now empty. I have set this token and filter to ignoring spaces in words like: Fun X or Viva X.
Here my mapping (in PHP):
'cars' => array(
'properties' => array(
/**'type_name2' => array(
'type' => 'string',
'fields' => array(
'raw' => array(
'type' => 'string',
'analyzer' => 'keyword'
)
)
),**/
'type_name2' => array(
'type' => 'string',
'analyzer' => 'keyword_lower'
),
'type_kw' => array(
'type' => 'float'
),
'type_hp' => array(
'type' => 'float'
)
)
),
and the custom analyzer:
'analysis' => array(
'analyzer' => array(
'keyword_lower' => array(
'tokenizer' => 'keyword',
'filter' => 'lowercase'
),
'nGram_analyzer' => array(
'type' => 'custom',
'tokenizer' => 'whitespace',
'filter' => array(
'lowercase',
'asciifolding',
'nGram_filter'
)
),
'whitespace_analyzer' => array(
'type' => 'custom',
'tokenizer' => 'whitespace',
'filter' => array(
'lowercase',
'asciifolding'
)
)
),
'filter' => array(
'nGram_filter' => array(
'type' => 'ngram',
'min_gram' => 2,
'max_gram' => 20,
'token_chars' => array(
'letter',
'digit',
'punctation',
'symbol'
)
),
)
)
but the result of type_name2 is empty:
'type_name2' =>
array (size=1)
'buckets' =>
array (size=0)
empty
Any ideas, what is wrong?
Thx and regards
Stefan

How to configure ObjectMultiCheckBox to persist an empty element?

I have the following element in my form, and I tried all possible options found in the web to allow empty value for element:
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'name' => 'directPractice',
'options' => array(
'label' => 'A. Check all direct practice field education assignments',
'label_attributes' => array(
'class' => 'label-multicheckbox-group'
),
'required' => false,
'allow_empty' => true,
'continue_if_empty' => false,
'object_manager' => $this->getObjectManager(),
'target_class' => 'OnlineFieldEvaluation\Entity\FieldEducationAssignments', //'YOUR ENTITY NAMESPACE'
'property' => 'directPractice', //'your db collumn name'
'disable_inarray_validator' => true,
'value_options' => array(
'1' => 'Adults',
'2' => 'Individuals',
'3' => 'Information and Referral',
'4' => 'Families',
array(
'value' => 'Other',
'label' => 'Other (specify)',
'label_attributes' => array(
'class' => 'bindto',
'data-bindit_id' => 'otherDirectPracticeTxt_ID'
),
'attributes' => array(
'id' => 'otherDirectPractice_ID',
),
)
),
),
'attributes' => array(
'value' => '1', //set checked to '1'
'multiple' => true,
)
));
And I am always getting the same error message when it is empty:
Validation failure 'directPractice':Array
(
[isEmpty] => Value is required and can't be empty
)
Ok, this is a best what I could come up after researching on it. Solution is inspired by these question.
Form: hidden field and ObjectMultiCheckBox
public function init()
{
$this->setAttribute('method', 'post');
$this->setAttribute('novalidate', 'novalidate');
//hidden field to return empty value. If checkbox selected, checkbox values will be stored with empty value in Json notation
$this->add(array(
'type' => 'Hidden',
'name' => 'otherLearningExperiences[]', // imitates checkbox name
'attributes' => array(
'value' => null
)
));
$this->add(array(
// 'type' => 'Zend\Form\Element\MultiCheckbox',
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'name' => 'otherLearningExperiences',
'options' => array(
'label' => 'C. Check other learning experiences',
'object_manager' => $this->getObjectManager(),
'target_class' => 'OnlineFieldEvaluation\Entity\FieldEducationAssignments',
'property' => 'otherLearningExperiences',
'label_attributes' => array(
'id' => 'macro_practice_label',
'class' => 'control-label label-multicheckbox-group'
),
'value_options' => array(
array(
'value' => 'seminars',
'label' => 'Seminars, In-Service Training/Conferences',
'label_attributes' => array(
'class' => 'bindto',
'data-bindit_id' => 'seminarsTxt_ID'
),
'attributes' => array(
'id' => 'seminars_ID',
),
),
array(
'value' => 'other',
'label' => 'Other (specify)',
'label_attributes' => array(
'class' => 'bindto',
'data-bindit_id' => 'otherLeaningExperiencesTxt_ID'
),
'attributes' => array(
'id' => 'otherLeaningExperiences_ID',
),
)
),
),
'attributes' => array(
//'value' => '1', //set checked to '1'
'multiple' => true,
'empty_option' => '',
'required' =>false,
'allow_empty' => true,
'continue_if_empty' => false,
)
));
Validator
$inputFilter->add($factory->createInput(array(
'name' => 'otherLearningExperiences',
'required' => false,
'allow_empty' => true,
'continue_if_empty' => true,
)));
}
View
//hidden field to be posted for empty value in multicheckbox
echo $this->formHidden($form->get('otherLearningExperiences[]'));
$element = $form->get('otherLearningExperiences');
echo $this->formLabel($element);
echo $this->formMultiCheckbox($element, 'prepend');

Categories