I have three tables like this :
objects (id , name , tags , ...)
tags (id , name , ...)
object_tags(id , objectID , tagID)
I used krajee treeView input and in my "objects" form I have :
$form->field($model, 'tags')->
widget(\kartik\tree\TreeViewInput::className(),[
'name' => 'kvTreeInput',
'value' => 'false', // preselected values
'query' => Tags::find()->addOrderBy('root, lft')->name,
'headingOptions' => ['label' => 'تگ'],
'rootOptions' => ['label'=>'<i class="fa fa-building"></i>'],
'fontAwesome' => true,
'asDropdown' => true,
'multiple' => true,
'options' => ['disabled' => false]
]);
But I have no idea how should I write the codes in my controller or in my model!!!
In your action you should iterate over the post result
This is just a brief suggestion you must add the code related to your specific need
public function actionYourAction()
{
$post = Yii::$app->request->post();
if (!empty($post)){
$postTags = $post['tags'];
foreach ($postASCCId as $key => $value) {
$modelNew = new YourModel();
$modelNew->tag = $value;
$modelNew->save();
}
}
.....
}
Related
I am using agile toolkit code for developing an application , i do have dropdown that get values from database, I want to show selected value from field 1 to field 2 without submit any thing.
$form->addField('field1', ['caption' => 'Field 1', 'DropDown', 'values'=> $arra1,'isMultiple' => true ,'readonly' => false, ['dropdownOptions' => ['fullTextSearch' => true]]]);
$form->addField('field2', ['caption' => 'Select Specfic Values', 'DropDown','model' => new view_values($db),'dependency' => function (view_values $model, $data)
{isset($data['field1']) ? $model->addCondition($model->fieldName()->id, 'like', '%' . $data['field1'] . '%') : null;}
,'isMultiple' => true ,'readonly' => false, ['dropdownOptions' => ['fullTextSearch' => true]]]);
issue is Fatal Error atk4\ui\Exception: Unable to add form field (), object: atk4\ui\FormField\DropDown () property: "dependency" value: {}. Looking for Help. maybe my logic is wrong.
I have managed to find a solution for 2 field multi selection scenario:
$values = new view_table($db);
$values->addCondition($db->dsql()->orExpr()->where($db->dsql()->
andExpr()->where('field_status','<>','1')));
$Array = array();
reset($Array);
foreach($values as $row){
$Array[$row['id']] = $row['field_1'].": ".$row['field_2'];
}
$fieldvalue_1 = $form->addField('fieldvalue_1', ['caption' => 'fieldvalue_1', 'DropDown', 'values'=> $Array,'isMultiple' => true ,'readonly' => $readonly, ['dropdownOptions' => ['fullTextSearch' => true]]]);
$fieldvalue_2 = $form->addField('fieldvalue_2', ['caption' => 'fieldvalue_2', 'DropDown', 'values'=> $Array,'isMultiple' => true ,'readonly' => $readonly, ['dropdownOptions' => ['fullTextSearch' => true]]])->set($_GET['val'] ?? 'No value');
$fieldvalue_1->js('change' ,new \atk4\ui\JsReload($fieldvalue_2,['val' => $fieldvalue_1->jsInput()->val()]));
So what I want to do is populate a dropdown in Yii framework with ajax using my database values in drop down. I using Kartik widget in it here is my dropdown code,
<?php $primaryfield = [1 => 'Business Development(Sales)', 2 => 'Graphic Design', 3 => 'Social Media Marketing', 4 => 'Web Development']; ?>
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data' => $primaryfield,
'options' => ['placeholder' => 'Enter Your Primary Field', 'multiple' => false], 'pluginOptions' => ['tags' => false, 'tokenSeprators' => [',', ' '], 'maximumInputLength' => 20],])->label(false); ?>
I know everything about Ajax in PHP but don't know how to use it in Yii framework using Kartik widget I have all the primary fields value in my database but unfortunately, I am only able to display them in static basis not dynamic basis using ajax
If I get you clear, you want to have a drop-down list in which their items are dynamically generated by your database.
This is the way you can achieve with kartik dropdown widget.
I'll first create active form field which contains predefined categories as follows
<?php $form = ActiveForm::begin();
//Initialize predefined categories
$data = [
'1' => 'Business Development(Sales)',
'2' => 'Graphic Design',
'3' => 'Social Media Marketing',
'4' => 'Web Development',
];
?>
These field will prompt database to retrieve items for particular category via AJAX
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Enter your primary field'],
'pluginOptions' => [
//'allowClear' => true
],
'pluginEvents' => [
"change" => "function() {
var id = $(this).val(); //extract the id of selected category
$.ajax({
method : 'GET',
dataType : 'text',
url : '../yourcontroller/populate?id=' + id,
success : function (response) {
var response = JSON.parse(response);
var myDropDownList = document.getElementById(\"model-item\");
$.each(response, function(index, value) {
var option = document.createElement(\"option\");
option.text = value;
option.value = index;
try {
myDropDownList.options.add(option);
}
catch (e) {
alert(e);
}
});
}
});
}",
],
]);
?>
<?= $form->field($model,'item')->dropdownList(
['prompt'=>'Select Item']
);
?>
Now create action in your controller that will query items from your database based on the category selected and return it to the Item field via ajax.
<?php
public function actionPopulate($id)
{
// the id above is the one selected from the category field so you can use
// that Id now to retrieve items from your item-field with ajax
/* in you case */
$results = Category::find()
->select('items')
->where(['id' => $id])
->asArray()
->all();
//these hard-coded values are for the demonstration
$results = [
'1'=>'maziwa',
'2'=>'ugali',
'3'=>'samaki',
'4'=>'kuku',
'5'=>'mtetea',
];
return json_encode($results);
}
?>
Hope this helps!
I'm working on a view with lots of invoices.
Users can filter them by 'Customer', 'Date' and also by 'Referent'.
An invoice is linked to a customer, and a customer can have a 'referent' or not.
So in my 'referent' select list, the default value is 'All' to not filter by 'referent', and the rest is the list of all referents got by QueryBuilder.
Now, I need help to know how can I insert an option 'No Referent' in the select list to get all invoices for which the customer has no referent.
Here is my referent field in my 'InvoiceSearchType':
->add('referent', 'genemu_jqueryselect2_entity', array(
'label' => 'Referent',
'class' => 'GeocalUserBundle:User',
'query_builder' => function (UserRepository $ur) {
return $ur->getEmployesQueryBuilder();
},
'empty_value' => '',
'configs' => array(
'placeholder' => 'All',
'width' => '100%',
'allowClear' => true,
),
'required' => false,
))
Here, my QueryBuilder:
public function getEmployesQueryBuilder()
{
$queryBuilder = $this->createQueryBuilder('u')
->leftJoin('u.groups', 'g')
->where('u.enabled = 1')
->andWhere('g.id NOT IN(1)')
->orderBy('u.nom', 'ASC')
;
return $queryBuilder;
}
And I just display the field like that:
<td class="label">Chargé d'affaire</td>
<td colspan="2">{{ form_widget(form.referent) }}</td>
Thanks in advance ! :)
[SOLVED]
First I added a method which get the result (array) of the query, add another referent and return it:
public function getReferentWithNull()
{
// Get the list of referents
$referents = $this->doctrine->getRepository('GeocalUserBundle:User')->getEmployesQueryBuilder()->getQuery()->getResult();
// Create a new instance
$nobody = new User();
$nobody->setName("No Referent");
// Put it in the array result with the key -1
$referents[-1] = $nobody;
return $referents;
}
Then, I modified my form field type to 'choice' type and call my previous function:
->add('referent', 'genemu_jqueryselect2_choice', array(
'label' => 'Referent',
'choices' => $this->getReferentWithNull(),
'empty_value' => '',
'configs' => array(
'placeholder' => 'All',
'width' => '100%',
'allowClear' => true,
),
'required' => false,
))
Finally, I have my last option 'No Referent' with a key of -1.
Hope that it helps someone :)
I am using cakephp 3.3
I have in the controller
$employee = TableRegistry::get('employees');
$allNames = $employee->find('list', array('employee_name' => array('employee_name') ) );
$allNames = $allNames->toArray();
$this->set('name', $allNames);
and in my template
<?= $this->Form->input('employee', array('type'=>'select','label' => false,
'options' => $name,'value'=>$name));?>
The only thing being retrieved and displayed is the number of entries i have in the database, $name only contains an array(1,2,3,4) when it should be actual people names.
Did you read the documentation about how find('list') works?'
$allNames = $employee->find('list', [
'keyField' => 'employee_name'
'valueField' => 'employee_name'
]);
$this->set('name', $allNames);
<?= $this->Form->input('employee', ['type'=>'select','label' => false,
'options' => $name]);?>
You can map id and value by keyField and valueField in list query
in your controller
$employee = TableRegistry::get('employees');
$allNames = $employee->find('list', array('valueField' =>employee_name','keyField'=>'employee_id' )); // correct employee_id with your table id field.
$this->set('name', $allNames);
In your View
<?= $this->Form->input('employee', array('type'=>'select','label' => false,
'options' => $name));?>
My issue is the following.
I am trying to insert multiple items to mysql database table. I use Kartik-Select2 widget for item selection.
The following code is working for me and I can select multiple items with it.
<?= $form->field($model, 'categories')->widget(Select2::className(), [
'data' => $model->availableCategories(),
'model' => $model,
'attribute' => 'categories',
'language' => 'en',
'options' => ['placeholder' => 'Select a site...'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
],
]) ?>
But how now to save selected items to DB table. Where selected items stored (is there some array for them inside the widget)?
My 'categories' attribute defined in Model class as:
public $categories = [];
I thought selected items will populate to it. But it does not work (array is empty after form submition). I read many similar topics but did not find complete and full explanation how it works. I am new in Yii2 and maybe lost smth. Thx for any help.
Normally a multi select items is saved this way ( this is a simplified way )
public function actionYourAction()
{
$post = Yii::$app->request->post();
if (!empty($post)){
$postModel = $post['YourModel'];
$postModelMulti= $postModel['your_multi_attribute'];
if ( !empty( $postModelMulti) ){
foreach ($postModelMulti as $key => $value) {
$newModel = new YuorModelToAdd();
$newModel->your_attribute = $value;
$newModel->save();
}
}
}
......