add checkbox in select2 to dropdown list in yii2 - yii2

here is code of dropdownlist.. but when I select multiple values it gives validation error "task must be string"
how to save multiple values (array)?
<?php echo $form->field($model, 'task')->widget(Select2::classname(), [
'data' => $companiesList,
'options' => ['placeholder' => 'Select company...','multiple' => true],
'pluginOptions' => ['allowClear' => true,],
]);?>
how to give checkbox for each value in list?

you have to save multiple values in many-to-many tabels ,
after changing the rules to [['task'], 'safe'] from Mr Skull answer , you have to get all data like this :
foreach ( $model->task as $single_task){
$task = new _many_to_many_model();
$task->side_1_id = single_task;
$task->side_2_id = $model->id;
$task->save();
}
after this comment :
all selected value should go in single column
you don't need to use many-to-many !
I use "-" as delimiter,
$all_taskes = "";
foreach ( $model->task as $single_task){
$all_taskes .= single_task."-";
}
$model->task = all_taskes;

Hi there ,
$model->save();
foreach ($model->task as $cat) {
$m = new \common\models\_many_to_many_model();
$m->ads_id = $model->id; // change in to yorr base model ID and use it's put after $model->save
$m->category_id = $cat; // category_id is your many to many model filed id
$m->save();
}

Related

Is there a way to put "subject" into the function:mailto in a Datacolumn in yii2?

The problem is the following: I have an Html::mailto() in my Datacolumn where I wanna give the value of the subject with it.
I can't use swiftmailer or some other extensions because I don't want to generate an email, instead, I want to open outlook, by clicking the hyperlink, and have the subject pre-written there.
This is the function:
public static function mailto($text, $email = null, $options = [])
This is my code:
[
'class'=>'\kartik\grid\DataColumn',
'attribute' => 'email',
'label' => 'E-Mail',
'format' => 'raw',
'value' => function($model){
$email = SucheBiete::find()
->select(['email'])
->join('INNER JOIN', 'user', 'user.user_id = suche_biete.user_user_id')
->scalar();
return Html::mailto('Kontaktaufnahme mit: ' . $email,$email, ['subject' => 'Hi There']);
}
]
It works but without getting the subject:
is the $option parameter the right one to give a subject,textbody or cc?
Try to attach the subject to the second parameter:
return Html::mailto('...: ' . $email,"$email?subject=HiThere" );
Maybe you need to encode() the subject for preserving spaces.

Yii2 dropdown selected value

I want to show selected value in Yii2 dropdown,
$_GET Value:
$id = $_GET["cid"];
Drop down code
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
but this method is not working!
Try this.
$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Basically, you affect the options (your <option> elements) by using the value attribute's actual value as the array key in the dropDownList options array.
So in this case I have an array of states and the value attributes have the state abbreviation, for example value="FL". I'm getting my selected state from the Address table, which stores the abbreviation, so all I have to do is use that as my array key in the options array:
echo $form->field($model, 'state')->dropDownList($listData, ['prompt'=>'Select...', 'options'=>[$address->state=>["Selected"=>true]]]);
The documentation spells it out: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail
i hope this will help you
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::find()->where('id' => $id)->all(), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList(
$items, //Flat array('id'=>'val')
['prompt'=>''] //options
)->label('');
<?php
$selectValue = $_GET['tid']
echo $form->field($model, 'tag_id')
->dropdownList(
ArrayHelper::map(Tag::find()->where(['visibility'=>'1'])->orderBy('value ASC')->all(), 'tag_id', 'value'),
['options' => [$selectValue => ['Selected'=>'selected']]],
['prompt' => '-- Select Tag --'])
->label(false);
?>
This code will Auto Select the selected value received as input.
Where $selectValue will be numeric value received from GET method.
Final output : <option value="14" selected="selected">NONE</option>
Ok, if you are using ActiveForm then value of your model field will be used as the selected value. With Html helper dropDownList function accepts another parameter selection doc. Example:
$id = $_GET["cid"];
\yii\helpers\Html::dropDownList('userid', $id, [ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name'), [......])
This is my S.O.L.I.D approach.
Controller
$model = new User();
$model->userid = $id; #this line does the magick. Make sure the $id has a value, so do the if else here.
return $this->return('view', compact('model'))
But, if you prefer the setter method. Do this...
# Model
class User extends ActiveRecord
{
public function setUserId(int $userId): void
{
$this->userid = $userId;
}
}
# Controller
$model = new User();
$model->setUserId($userId);
View (view is as-is)
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Use this code below:
$category = \backend\models\ProductCategory::find()->WHERE(['deleted'=>'N'])->all();
$listData = ArrayHelper::map($category,'product_category_id','category_name');
echo $form->field($model, 'product_category_id')->dropDownList($listData,['prompt'=>'Select']);
All of the options I've added are unrequired.
What is written in the 'value' index is what dropdown item will be selected as default.
Prompt just displays a first option that doesn't have a value associated with it.
echo $form->field($model, 'model_attribute_name')
->dropDownList($associativeArrayValueToText,
[
'value'=> $valueIWantSelected,
'prompt' => 'What I want as a placeholder for first option',
'class' => 'classname'
]);
You'll find the function that assigns this in the following file:
vendor/yiisoft/yii2/helpers/BaseHtml.php
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
Also from the function you can see that you can add an optgroup to your dropdown, you just need to supply a multidimensional array in where I've put $associativeArrayValueToText. This just means that you can split your options by introducing group headings to the dropdown.

Table which can add, edit ,and delete data dynamically in Drupal

I know that we can add edit and delete data in a table statically in Drupal. But is there any way we can add edit and delete data via clicking a link just near to each row so that on clicking "add " button should generate a new row, and on clicking edit should highlight all the contents of the row as fr editing and delete should remove the row. The basic table I created is this:
<?php
$header = array('Emp ID', 'Emp Name', 'Emp Age');
$rows = array();
$sql = 'SELECT empid, name, age FROM {employee} ORDER BY name';
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$rows[] = $row;
}
print theme('table', $header, $rows);
?>
You can build it. You've already got your Read mode, so you need a Create/Update/Delete... there is some help on the internet for basic CRUD modules. Very basically, the update part, (first having a menu hook using % wildcard which is what arg(1) will be:
function crud_module_edit_form() {
$result = db_select('employee', 'e')
->fields('e', array('empid', 'name'))
->condition('empid', arg(1), '=')
->orderBy('name', 'DESC')
->execute()
->fetch();
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#default_value' => isset($result->name) ? $result->name : '',
'#required' => TRUE,
);
return $form;
}
Then the submit function for the above form to update the record. You could use db_merge here instead and then use the same page for both the Add and the Update functions.
function crud_app_edit_form_submit($form, &$form_state) {
db_update('employees')
->fields(array(
'name' => check_plain($form_state['values']['name']),
))
->condition('empid', arg(1), '=')
->execute();
drupal_set_message(t('Employee updated'));
}

How to set cakephp radio-button from mysql?

This cakephp form used to edit a mysql record needs to load the state of a radio button from a mysql database.
The mysql payment_type is enum('Account', 'Credit').
All of the other non-radio-button form inputs reload from the database and payment_type is correctly displayed on another form using this:
<?php echo h($purchaseOrder['PurchaseOrder']['payment_type']); ?>
Why doesn't this correctly set the radio-button from payment_type?
$options = array('account' => 'Account', 'credit' => 'Credit');
$attributes = array('legend' => false, 'value' => 'payment_type');
echo $this->Form->radio('payment_type', $options, $attributes);
In your attribute array, you should assign value which you want to keep selected by default .
For example you want account to be selected by default then in value you should assign 'account'. So your final attribute will be:
$attributes = array('legend' => false, 'value' => 'account');

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).