Map data from one dictionary into another - json
I have data from two APIs in JSON format and parsing them into 2 dictionaries (d1, d2).
I need to derive two additional fields FieldName(from d1), attrVal (from d2) by mapping subAttrDefId present in d2 ("attrValues") with subAttribDefId present in d2.
I have tried below code, but it's giving me "BoundsError"
resp = HTTP.get(URL1)
resp2 = HTTP.get(URL2)
global dict1, dict2
jsonStr = String(resp.body)
dict1 = JSON.parse(jsonStr)
jsonStr2 = String(resp2.body)
dict2 = JSON.parse(jsonStr2)
field_names = values(dict1)
for item in dict2
# for field_name in field_names
# item[field_name] = missing
# end
attr_vals = item["attrValues"]
for attr_val in attr_vals
field_name = dict1[attr_val["subAttrDefId"]]
item[field_name] = attr_val["attr_val"]
delete!(item,"attrValues")
end
end
Sample data from 1st API(d1):
[
{
"DefId":4327,
"DefVersionId":4326,
"attrValues":[
{
"subAttrValId":4328,
"DefId":4327,
"subAttrDefId":3888,
"attrVal":"276",
"crtUserid":"3456789",
"crtTmstmp":null,
"updtUserid":null,
"updtTmstmp":"2023-01-10T14:08:36.000+00:00"
},
{
"subAttrValId":4329,
"DefId":4327,
"subAttrDefId":3889,
"attrVal":"52",
"crtUserid":"3456789",
"crtTmstmp":null,
"updtUserid":null,
"updtTmstmp":"2023-01-10T14:08:36.000+00:00"
},
{
"subAttrValId":4330,
"DefId":4327,
"subAttrDefId":3890,
"attrVal":"50",
"crtUserid":"3456789",
"crtTmstmp":null,
"updtUserid":null,
"updtTmstmp":"2023-01-10T14:08:36.000+00:00"
},
{
"subAttrValId":4331,
"DefId":4327,
"subAttrDefId":3891,
"attrVal":"24",
"crtUserid":"3456789",
"crtTmstmp":null,
"updtUserid":null,
"updtTmstmp":"2023-01-10T14:08:36.000+00:00"
}
],
"code":"AB",
"typeCode":"00",
"crtUserid":"12345",
"crtTmstmp":null,
"updtUserid":"23456",
"updtTmstmp":"2023-01-10T14:08:36.000+00:00"
}
]
Sample data from 2nd API(d2):
[
{
"subAttribDefId":3886,
"displayLabel":"string",
"attribDesc":"string",
"attribName":"string",
"attribDataType":"string",
"attrFormat":"string",
"crtUserid":"string",
"crtTmstmp":"2022-12-21T19:07:14.000+00:00",
"updtUserid":"string",
"updtTmstmp":"2022-12-21T19:07:14.000+00:00",
"FieldName":null,
"category":null,
"subcategory":null
},
{
"subAttribDefId":3887,
"displayLabel":"string",
"attribDesc":"string",
"attribName":"string",
"attribDataType":"string",
"attrFormat":"string",
"crtUserid":"string",
"crtTmstmp":"2022-12-21T19:08:18.000+00:00",
"updtUserid":"string",
"updtTmstmp":"2022-12-21T19:08:18.000+00:00",
"FieldName":null,
"category":null,
"subcategory":null
},
{
"subAttribDefId":3888,
"displayLabel":"Number of bucket",
"attribDesc":"Number of bucket",
"attribName":"numbuckets",
"attribDataType":"number",
"attrFormat":"",
"crtUserid":"12345",
"crtTmstmp":"2022-12-21T19:08:56.000+00:00",
"updtUserid":null,
"updtTmstmp":"2022-12-21T19:08:56.000+00:00",
"FieldName":null,
"category":null,
"subcategory":null
},
{
"subAttribDefId":3889,
"displayLabel":"Cabin",
"attribDesc":"class Cabin",
"attribName":"aCabin",
"attribDataType":"number",
"attrFormat":"",
"crtUserid":"1234",
"crtTmstmp":"2022-12-21T19:08:56.000+00:00",
"updtUserid":null,
"updtTmstmp":"2022-12-21T19:08:56.000+00:00",
"FieldName":null,
"category":null,
"subcategory":null
}
**Dict1**:
Any[Dict{String, Any}("crtTmstmp" => "2023-01-12T08:17:49.000+00:00", "attribName" => "buckets", "subAttribDefId" => 1, "attrFormat" => "^[\\d]*\$", "updtTmstmp" => "2023-01-12T08:17:49.000+00:00", "displayLabel" => "buckets", "crtUserid" => "23456", "FieldName" => nothing, "attribDesc" => "buckets", "category" => "Seat Attributes",
"updtUserid" => nothing, "attribDataType" => "number", "subcategory" => nothing), Dict{String, Any}("crtTmstmp" => "2023-01-12T08:17:49.000+00:00", "attribName" => "fCabin", "subAttribDefId" => 2, "attrFormat" => "^[\\d]*\$", "updtTmstmp" => "2023-01-12T08:17:49.000+00:00", "displayLabel" => "F Cabin", "crtUserid" => "23456", "FieldName" => nothing, "attribDesc" => "First class Cabin", "category" => "Seat Attributes", "updtUserid" => nothing, "attribDataType" => "number", "subcategory" => nothing), Dict{String, Any}("crtTmstmp" => "2023-01-12T08:17:49.000+00:00", "attribName" => "jCabin", "subAttribDefId" => 3, "attrFormat" => "^[\\d]*\$", "updtTmstmp" => "2023-01-12T08:17:49.000+00:00", "displayLabel" => "J Cabin", "crtUserid" => "23456", "FieldName" => nothing, "attribDesc" => "J Cabin", "category" => "Seat Attributes", "updtUserid" => nothing, "attribDataType" => "number", "subcategory" => nothing), Dict{String, Any}("crtTmstmp" => "2023-01-12T08:17:49.000+00:00", "attribName" => "oCabin", "subAttribDefId" => 4, "attrFormat" => "^[\\d]*\$", "updtTmstmp" => "2023-01-12T08:17:49.000+00:00", "displayLabel" => "O Cabin", "crtUserid" => "23456", "FieldName" => nothing, "attribDesc" => "O Cabin", "category" => "Seat Attributes", "updtUserid" => nothing, "attribDataType" => "number", "subcategory" => nothing), Dict{String, Any}("crtTmstmp" => "2023-01-12T08:17:49.000+00:00", "attribName" => "yPlusCabin", "subAttribDefId"
=> 5, "attrFormat" => "^[\\d]*\$", "updtTmstmp" => "2023-01-12T08:17:49.000+00:00", "displayLabel" => "Y+ Cabin", "crtUserid" => "23456", "FieldName" => nothing, "attribDesc" => "Y Plus Cabin", "category" => "Seat Attributes", "updtUserid" => nothing, "attribDataType" => "number", "subcategory" => nothing)]
**Dict2:**
Any[Dict{String, Any}("proxyCode" => "000", "crtTmstmp" => nothing, "equipCode" => "ABC", "proxyequipCode" => "ABC", "reportequipcode" => "ABC", "userTypeCode" => "ABC", "code" => "AB", "isUserDefined" => 0, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "ftype" => "000", "crtUserid" => "123456", "attrValues" => Any[Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "276", "subAttribValId" => 4328, "crtUserid" => "123456", "subAttribDefId" => 3888, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "52", "subAttribValId" => 4329, "crtUserid" => "123456", "subAttribDefId" => 3889, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "50", "subAttribValId" => 4330, "crtUserid" => "123456", "subAttribDefId" => 3890, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "24", "subAttribValId" => 4331, "crtUserid" => "123456", "subAttribDefId" => 3891, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "46", "subAttribValId" => 4332, "crtUserid" => "123456", "subAttribDefId" => 3892, "subFletDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "202", "subAttribValId" => 4333, "crtUserid" => "123456", "subAttribDefId" => 3893, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "2", "subAttribValId" => 4334, "crtUserid" => "123456", "subAttribDefId" => 3894, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "Normal", "subAttribValId" => 4335, "crtUserid" => "123456", "subAttribDefId" => 3895, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "8", "subAttribValId" => 4336, "crtUserid" => "123456", "subAttribDefId" => 3896, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "180", "subAttribValId" => 4337, "crtUserid" => "123456", "subAttribDefId" => 3897, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "218", "subAttribValId" => 4338, "crtUserid" => "123456", "subAttribDefId" => 3898, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "9", "subAttribValId" => 4339, "crtUserid" => "123456", "subAttribDefId" => 3899, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "181", "subAttribValId" => 4340, "crtUserid" => "123456", "subAttribDefId" => 3900, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "-", "subAttribValId" => 4341, "crtUserid" => "123456", "subAttribDefId" => 3901, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "40000", "subAttribValId" => 4342, "crtUserid" => "123456", "subAttribDefId" => 3902, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "2.71", "subAttribValId" => 4343, "crtUserid" => "123456", "subAttribDefId" => 3903, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "2.96", "subAttribValId" => 4344, "crtUserid" => "123456", "subAttribDefId" => 3904, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "2%", "subAttribValId" => 4345, "crtUserid" => "123456", "subAttribDefId" => 3905, "subDefId" => 4327), Dict{String, Any}("crtTmstmp" => nothing, "updtUserid" => nothing, "updtTmstmp" => "2023-01-10T14:08:36.000+00:00", "attrVal" => "-3%", "subAttribValId" => 4346, "crtUserid" => "123456", "subAttribDefId" => 3906, "subDefId" => 4327)], "bodyType" => "W", "DefVersionId" => 4326, "subDefId" => 4327, "updtUserid" => "456789")]
Related
Logstash aggregate filter skipping records
I am migrating data from mysql to Elasticsearch via logstash. I am using aggregate filter plugin.. I have user, post and post media tables. The scenerio is , a user has many post and post has many media. I want to save object as follow. { "id": "82219", "name": "test", "db_id": 82219, "user_id": "u-48201", "box_user": { "id": 48201, "box_id": 82219, "username": "fasdfasf", "full_name": "fasdf fasd", "is_private": true }, "status": "A", "created_at": "2020-01-06T13:04:00Z", "type": { "name": "box", "parent": "u-82219" }, "box_posts": [{ "box_id": 82219, "post_box_id": 328341, "text_content": "Mango Duck", "created_at": "2017-01-17T20:49:09.000Z", "created_location": { "lon": -0.09, "lat": 51.5 }, "score": 96, "user_id": 48201, "post_media": [{ "bg_color": "#C9273E", "file": "compress_749uyiwl14932043481493204348.jpg", "file_base_name": "compress_749uyiwl14932043481493204348", }, { "bg_color": "#C9273E", "file": "compress_749uyiwl14932043481493204348.jpg", "file_base_name": "compress_749uyiwl14932043481493204348", }, { "bg_color": "#C9273E", "file": "compress_749uyiwl14932043481493204348.jpg", "file_base_name": "compress_749uyiwl14932043481493204348", } ], "post_type_id": 1, "location": { "fs_location_id": "ChIJ03GSCloDdkgRe_s-p2vyvQA", "thumbnail": "", "website": "https://www.the-shard.com/", "other_info": "", }, "id": 2, "place": { "lon": 51.5045, "lat": -0.0865 }, "short_code": "7M" }, { "box_id": 82219, "post_box_id": 328342, "text_content": "" "Exploring canals 🛥" "", "created_at": "2017-01-17T20:53:27.000Z", "created_location": { "lon": -0.66, "lat": 51.8 }, "score": 36, "user_id": 48201, "post_media": [{ "file_width": 1440, "notification_file_width": 1146, "thumb_file_height": 135, "home_file_height": 860, "is_primary": true, }], "post_type_id": 1, "location": { "fs_location_id": "ChIJ33SmFitYdkgR3-ErzH_p6Bw", "thumbnail": "", "website": "", "other_info": "", "rating": 0.0, }, "id": 3, "place": { "lon": 51.992, "lat": -0.66 }, "short_code": "bxvbvxc" }, ], "#timestamp": "2020-02-11T13:26:01.806Z", "#version": "1" } I used following filter. > aggregate { task_id => "%{db_id}" code => " map['db_id'] = event.get('db_id') map['box_posts'] ||= [] model = { 'box_id' => event.get('box_id'), 'score' => event.get('score'), 'post_box_id' => event.get('post_box_id'), 'user_id' => event.get('user_id'), 'text_content' => event.get('text_content'), 'created_at' => event.get('post_created'), 'id' => event.get('post_id'), 'post_type_id' => event.get('post_type_id'), 'short_code' => event.get('short_code'), 'created_location' => { 'lon' => event.get('lon') , 'lat' => event.get('lat') }, } model['post_media'] = { 'id' => event.get('media_id'), 'bg_color' => event.get('bg_color'), 'file' => event.get('media_file'), 'file_base_name' => event.get('file_base_name'), 'file_type' => event.get('file_type'), 'file_type_number' => event.get('file_type_number'), 'file_width' => event.get('file_width'), 'file_height' => event.get('file_height'), 'is_primary' => event.get('is_primary') , 'file_size' => event.get('file_size'), 'medium_file_width' => event.get('medium_file_width'), 'medium_file_height' => event.get('medium_file_height'), 'thumb_file_height' => event.get('thumb_file_height'), 'thumb_file_width' => event.get('thumb_file_width'), 'collage_file_height' => event.get('collage_file_height'), 'collage_file_width' => event.get('collage_file_width'), 'notification_file_width' => event.get('notification_file_width'), 'notification_file_height' => event.get('notification_file_height'), 'home_file_height' => event.get('home_file_height'), 'home_file_width' => event.get('home_file_width'), 'md5_filename' => event.get('md5_filename'), 'bucket' => event.get('media_bucket'), 'bg_color_collage' => event.get('bg_color_collage') } if (event.get('location_id') != nil) model['location'] = { 'fs_location_id' => event.get('fs_location_id') , 'location_name' => event.get('location_name') , 'map_image' => event.get('map_image') , #bool 'address_name' => event.get('address_name') , 'bg_image' => event.get('location_bg_image') , 'thumbnail' => event.get('thumbnail') , 'rating' => event.get('location_rating') , # float 'total_reviews' => event.get('total_reviews') , 'file' => event.get('file') , 'bucket' => event.get('location_bucket') , 'width' => event.get('location_width') != '' ? event.get('location_width') : 0, 'height' => event.get('location_height') != '' ? event.get('location_height'): 0, 'phone' => event.get('location_phone') , 'other_info' => event.get('other_info') , 'website' => event.get('website') } model['place'] = { 'lon' => event.get('location_latitude') , 'lat' => event.get('location_longitude') } end if ( event.get('post_type_id') == 7 ) source_type = event.get('search_post_source_type') model['post_attributes'] = { 'title' => event.get('search_post_title') , 'thumbnail' => event.get('search_post_thumbnail') , 'bg_image' => event.get('search_post_bg_image') , 'source_type' => event.get('search_post_source_type') , 'source_id' => event.get('search_post_source_id') , 'source_link' => event.get('search_post_source_link') , 'item_type' => event.get('search_post_item_type') , 'item_type_number' => event.get('search_post_item_type_number') , 'rating' => event.get('search_post_rating'), } if( source_type != 'google' && source_type != 'web' ) model['post_attributes'].merge! ( { 'source_title' => event.get('post_search_attribute_title'), 'owner' => event.get('post_search_attribute_owner'), 'caption' => event.get('post_search_attribute_caption'), 'description' => event.get('post_search_attribute_description'), 'source_rating' => event.get('post_search_attribute_rating'), 'total_reviews' => event.get('post_search_attribute_total_reviews'), 'total_likes' => event.get('post_search_attribute_total_likes'), 'total_dislikes' => event.get('post_search_attribute_total_dislikes'), 'total_pages' => event.get('post_search_attribute_total_pages'), 'gallery' => event.get('post_search_attribute_gallery'), 'stars' => event.get('post_search_attribute_stars'), 'trailers' => event.get('post_search_attribute_trailers'), 'external_url' => event.get('post_search_attribute_external_url') }) end if( source_type == 'google' && event.get('gallery') != nil ) model['post_attributes'].merge! ( { 'trailers' => event.get('gallery') }) end end map['box_posts'] << model event.cancel()" push_previous_map_as_event => true timeout => 5 }
Update data in Kartik Detailview is not working
I've detail showed using Kartik Detail View. This widget has Edit inline function by clicking pencil icon button in top right side like this. But then the table doesn't be editable : And nothing happen, my data still the same, my update not success. It's possible to solve my problem? Thanks. I have read the official guide and it looks identical: https://demos.krajee.com/detail-view This is my view code: <?php echo DetailView::widget([ 'model' => $modelAnagrafiche, 'responsive' => true, 'mode' => 'edit', 'enableEditMode' => true, 'buttons1' => '{update}', 'panel' => [ 'type' => 'primary', 'heading' => 'Contratto' . ' : ' . $modelAnagrafiche >cognome_ragione_sociale . ' ' . $modelAnagrafiche->nome ], 'attributes' => [ [ 'group'=>true, 'label'=>'Sezione Anagrafica', 'rowOptions'=>['class'=>'table-primary'] ], [ 'columns' => [ [ 'attribute' => 'cognome_ragione_sociale', 'displayOnly' => true, 'valueColOptions' => ['style' => 'width:30%'] ], [ 'attribute' => 'nome', 'format' => 'raw', 'valueColOptions' => ['style' => 'width:30%'], 'displayOnly' => true, 'type' => DetailView::INPUT_TEXT, ], ], ], [ 'columns' => [ [ 'attribute' => 'codice_fiscale', 'displayOnly' => true, 'valueColOptions' => ['style' => 'width:30%'] ], [ 'attribute' => 'partita_iva', 'format' => 'raw', 'valueColOptions' => ['style' => 'width:30%'], 'displayOnly' => true ], ], ], [ 'columns' => [ [ 'attribute' => 'tipo_documento', 'displayOnly' => true, 'valueColOptions' => ['style' => 'width:30%'], 'format' => 'raw', 'value' => $modelAnagrafiche->tipoDocumento, ], [ 'attribute' => 'numero_documento', 'format' => 'raw', 'valueColOptions' => ['style' => 'width:30%'], 'displayOnly' => true ], ], ], [ 'columns' => [ [ 'attribute' => 'data_nascita', 'displayOnly' => true, 'format' => 'date', 'type' => DetailView::INPUT_DATE, 'widgetOptions' => [ 'pluginOptions' => ['format' => 'yyyy-mm-dd'] ], ], [ 'attribute' => 'id_provincia_nascita', 'displayOnly' => true, 'valueColOptions' => ['style' => 'width:30%'], 'format' => 'raw', 'value' => $modelAnagrafiche->provinciaNascitaNome, 'label' => 'Provincia Nascita' ], ], ], [ 'columns' => [ [ 'attribute' => 'id_comune_nascita', 'displayOnly' => true, 'format' => 'raw', 'value' => $modelAnagrafiche->comuneNascitaNome, 'label' => 'Comune Nascita' ], ], ], ], ]); ?> This is the action in my controller: public function actionUpdateAnagrafica() { $post = Yii::$app->request->post(); if (empty($post['Anagrafiche']['id'])) { throw new NotFoundHttpException('Non esiste nessuna anagrafica.'); } $modelAnagrafiche = Anagrafiche::findOne($post['Anagrafiche']['id']); if ($modelAnagrafiche->load($post) && $modelAnagrafiche->save()) { return $this->redirect(['view', 'id' => $modelAnagrafiche->id]); } else { return $this->render('update-anagrafica', [ 'modelAnagrafiche' => $modelAnagrafiche, ]); } }
You have to remove all the displayOnly attributes. According to the official guide: displayOnly: boolean|Closure, if the input is to be set to as display only in edit mode. If set to true, no editable form input will be displayed, instead this will display the formatted attribute value.
Removing unwanted header of ActionColumn
I'm using ActionColumn of kartik, which creates unwanted header(see my attachement) This header is nowhere coded!! Any ideas how to remove it? Here is code [ 'class' => 'kartik\grid\ActionColumn', 'dropdown' => false, 'headerOptions' => ['width' => '80'], 'vAlign' => 'top', 'template' => '{rename_folder}<br>{create_folder}', 'buttons' => [ 'create_folder' => function ($model) { $bez = "erzeugen"; return Html::a('<span class="glyphicon glyphicon-folder-close"></span>', ['/mail/mail-eingang/createfolder', 'bez' => $bez], ['title' => 'Ordner erzeugen', 'data' => ['pjax' => '0']]); }, 'rename_folder' => function ($model) { $bez = "umbenennen"; return Html::a('<span class="fa fa-folder-open"></span>', ['/mail/mail-eingang/renamefolder', 'bez' => $bez], ['title' => 'Ordner umbenennen', 'data' => ['pjax' => '0']]); }, ],
If you want remove header add this to your column config: 'header' => '',
Yii2: Select2, How to set initValueText in Gridview or Tabularform?
I need to set initValueText for Select2, which is in loop, like gridview or Tabularform. but I don't know how to set right value for each. <?= TabularForm::widget([ 'dataProvider' => $dataProvider, 'form' => $form, 'actionColumn' => false, 'checkboxColumn' => false, 'attributeDefaults' => [ 'type' => TabularForm::INPUT_RAW, ], 'attributes' => [ 'test' => [ 'type' => Form::INPUT_WIDGET, 'widgetClass' => Select2::className(), 'options' => [ 'name' => 'test', 'options' => [ 'class' => 'test-to-select', ], 'pluginOptions' => [ 'allowClear' => true, 'minimumResultsForSearch' => 'Infinity', 'ajax' => [ 'url' => Url::to(['/test/get-list']), 'dataType' => 'json', 'data' => new JsExpression('function(term,page) { return {term : term.term}; }'), 'results' => new JsExpression('function(data,page) { return {results:data.results}; }'), 'cache' => true ] ], 'initValueText' => 'Selected Text' /// how can I set this in gridview or Tabularform? ], ], ] ]) ?> Of course this is not working, 'initValueText' => function($model){ retur $model->textValue; } Any help would be appreciated.
Into tabularform if you want dynamic initValueText, you can use options closure in this manner: 'test' => [ 'type' => Form::INPUT_WIDGET, 'widgetClass' => Select2::className(), 'options' => function($model, $key, $index, $widget) { $initValueText = empty($model['textValue']) ? '' : $model['textValue']; return [ 'name' => 'test', 'options' => [ 'class' => 'test-to-select', ], 'initValueText' => $initValueText, 'pluginOptions' => [ 'allowClear' => true, 'minimumResultsForSearch' => 'Infinity', 'ajax' => [ 'url' => Url::to(['/test/get-list']), 'dataType' => 'json', 'data' => new JsExpression('function(term,page) { return {term : term.term}; }'), 'results' => new JsExpression('function(data,page) { return {results:data.results}; }'), 'cache' => true ] ], ]; } ],
If for example attribute for city, so try this.. $cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description; 'initValueText' => $cityDesc, // set the initial display text For init value first assign value to $model attribute, if you should not assign so this attribute can take value.
Set the data parameter with the array including the option you want to show. For example for cities: 'options' => [ 'data' => \yii\helpers\ArrayHelper::map(\app\models\City::find()->orderBy('id')->asArray()->all(), 'id', 'name'), ]
try to put inside the options instead ouside 'widgetClass' => Select2::className(), 'options' => [ 'initValueText' => 'Selected Text'
Don't use isset it return error if more the one filter are use there. [ 'attribute' => 'ad_partner_id', 'value' => function ($model, $key, $index, $widget) { return $model->partner->name; }, 'filter' => Select2::widget([ 'model' => $searchModel, 'initValueText' => !empty($searchModel->ad_partner_id) ? $searchModel->partner->name : "", 'attribute' => 'ad_partner_id', 'options' => ['placeholder' => Yii::t('app', 'Search Partner ...')], 'pluginOptions' => ['allowClear' => true, 'autocomplete' => true, 'ajax' => ['url' => Url::base() . '/partner/get-partners', 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }'), ], ], ]), ],
CakePHP 3 hasMany will not pass parent ID to associated children
/* ShootsTable.php Meta Table */ public function initialize(array $config) { $this->table('shoots'); $this->displayField('title'); $this->primaryKey('id'); $this->hasMany('ShootMeta'); } /* ShootMetaTable.php Meta Table */ public function initialize(array $config) { $this->table('shoot_meta'); $this->displayField('id'); $this->primaryKey('id'); $this->belongsTo('Shoots'); } public function buildRules(RulesChecker $rules) { $rules->add($rules->existsIn(['shoots_id'], 'Shoots')); return $rules; } /* Shoots.php Controller */ public function add() { $shoot = $this->Shoots->newEntity(null); if ($this->request->is('post')) { $this->Shoots->patchEntity($shoot, $this->request->data,[ 'associated' => ['ShootMeta'] ]); $shoot->set('created_by', 1); debug($shoot); if ($this->Shoots->save($shoot,['associated' => ['ShootMeta']])) { $this->Flash->success('The shoot has been saved.'); // return $this->redirect(['action' => 'index']); } else { $this->Flash->error('The shoot could not be saved. Please, try again.'); } } $this->set(compact('shoot')); $this->set('_serialize', ['shoot']); } /* Add.ctp Template */ <div class="shoots form large-10 medium-9 columns"> <?= $this->Form->create($shoot); ?> <fieldset> <legend><?= __('Add Shoot') ?></legend> <?php echo $this->Form->input('title'); echo $this->Form->input('content'); echo $this->Form->input('datetime', ['label' => 'Date/Time Of Shoot']); echo $this->Form->input('shoot_meta.0.meta_key', ['type' => 'hidden', 'value' => 'photographer_spaces']); echo $this->Form->input('shoot_meta.0.meta_value',['label' => 'Photographer Spaces', 'type' => 'number']); ?> </fieldset> <?= $this->Form->button(__('Submit')) ?> <?= $this->Form->end() ?> </div> /* debug($shoots) output */ object(App\Model\Entity\Shoot) { 'new' => true, 'accessible' => [ 'created_by' => true, 'title' => true, 'content' => true, 'datetime' => true, 'shoot_meta' => true ], 'properties' => [ 'title' => '123', 'content' => '123', 'datetime' => object(Cake\I18n\Time) { 'time' => '2015-03-19T07:04:00+0000', 'timezone' => 'UTC', 'fixedNowTime' => false }, 'shoot_meta' => [ (int) 0 => object(App\Model\Entity\ShootMetum) { 'new' => true, 'accessible' => [ 'shoots_id' => true, 'meta_key' => true, 'meta_value' => true, 'shoot' => true ], 'properties' => [ 'meta_key' => 'photographer_spaces', 'meta_value' => '123' ], 'dirty' => [ 'meta_key' => true, 'meta_value' => true ], 'original' => [], 'virtual' => [], 'errors' => [ 'shoots_id' => [ '_required' => 'This field is required' ] ], 'repository' => 'ShootMeta' } ], 'created_by' => (int) 1 ], 'dirty' => [ 'title' => true, 'content' => true, 'datetime' => true, 'shoot_meta' => true, 'created_by' => true ], 'original' => [], 'virtual' => [], 'errors' => [], 'repository' => 'Shoots' } As you can see, the field shoots_id is required, which I would have thought would be automatically passed down (although at this point it hasn't executed any MySQL). I feel I may have gone about this the wrong way but have spent 2 full days trying to get it right. One of those days was me trying to work out why after baking it had named a lot of the references to ShootMeta to ShootMetum, I thought it had actually corrupted it. One of the biggest issues I have is knowing where to use shoot_meta, ShootMeta, shootmeta, shootmetum, ShootMetum etc. It feels like a bit of a minefield! /Update A dump of the save object below. It is clearly assigning it, it just seems to not be executing it in the SQL? 'shoot_meta' => [ (int) 0 => object(App\Model\Entity\ShootMetum) { 'new' => false, 'accessible' => [ 'shoots_id' => true, 'meta_key' => true, 'meta_value' => true ], 'properties' => [ 'meta_key' => 'photographer_spaces', 'meta_value' => '123', 'shoot_id' => '2', 'id' => '3' ], 'dirty' => [], 'original' => [], 'virtual' => [], 'errors' => [], 'repository' => 'ShootMeta' },
Found it. It is referring to shoot_id when i debug the save 'shoot_meta' => [ (int) 0 => object(App\Model\Entity\ShootMetum) { 'new' => false, 'accessible' => [ 'shoots_id' => true, 'meta_key' => true, 'meta_value' => true ], 'properties' => [ 'meta_key' => 'photographer_spaces', 'meta_value' => '123', 'shoot_id' => '2', 'id' => '3' ], 'dirty' => [], 'original' => [], 'virtual' => [], 'errors' => [], 'repository' => 'ShootMeta' }, for some reason it was using the singular name for the association. Changed in the Shoots.php model. From $this->hasMany('ShootMeta'); To $this->hasMany('ShootMeta',[ 'foreignKey' => 'shoots_id' ]);
Remove the validation rule for shoots_id. Validation is for data that is posted from the form, and in this case the foreignKey cannot be posted from the Form. You already have rules in your buildRules() method for making sure that value is passed before saving, so removing the validation is 100% safe.
i have same problem like this to, for now my solution is sending associated data to other function/methode and save it. eg ** public function add() { $kantor = $this->Kantor->newEntity($this->request->data); if ($this->request->is('post')) { $kantor = $this->Kantor->patchEntity($kantor, $this->request->data); $rgndata = $this->request->data['Telpkantor']; $this->request->session()->write('rgndata', $rgndata); if ($this->Kantor->save($kantor)) { $result = $this->Kantor->save($kantor); $this->addTelpKantor($rgndata, $result->id); $this->Flash->success('The kantor has been saved.'); return $this->redirect(['action' => 'index']); } else { $this->Flash->error('The kantor could not be saved. Please, try again.'); } } $reffKota = $this->Kantor->ReffKota->find('list', ['limit' => 200]); $statusKantor = $this->Kantor->StatusKantor->find('list', ['limit' => 200]); $pimpinan = $this->Kantor->Pimpinan->find('list', ['limit' => 200]); $jenisTelp = $this->Kantor->Telpkantor->Jenistelp->find('list', ['limit' => 200]); $this->set(compact('kantor', 'reffKota', 'statusKantor', 'pimpinan', 'jenisTelp')); $this->set('_serialize', ['kantor']); } public function addTelpKantor($rgndata = null, $kantor_id=null) { if (!empty($rgndata[0]['noTelp'])) { $this->loadModel('Telpkantor'); foreach ($rgndata as $rgndata) { $rgndata['kantor_id'] =$kantor_id; $rgndatasave = $this->Telpkantor->newEntity($rgndata); $this->Telpkantor->save($rgndatasave); } } } **