Conditionally change field widget type with Drupal hook_form_alter - widget

I want to conditionally change the widget of a plain text field attached to a node by using hook_form_alter in Drupal 8.7.6.
function mymodule_form_node_article_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$options=[
'test1' => 'AAA',
'test2' => 'BBB',
'test3' => 'CCC',
'test4' => 'DDD',
];
$form['field_testdrop']['widget'][0]['#type']='select';
$form['field_testdrop']['widget'][0]['#options'] = $options;
}
However, when trying to save the node, I get the following error:
Error: Cannot create references to/from string offsets in Drupal\Component\Utility\NestedArray::setValue() (line 155 of core/lib/Drupal/Component/Utility/NestedArray.php).
What can I do to prevent this?

This Works:
$form['field_priority_email_id']['widget'][0]['value']['#type'] = 'select';
$form['field_priority_email_id']['widget'][0]['value']['#options'] = $options;
$form['field_priority_email_id']['widget'][0]['value']['#size'] = NULL;
You have to set '#size' to NULL or the select widget will not render correctly.

Related

Yii2, how to work with the checkboxlist field

As I needed a checkbox list I decided to use the checkboxlist , but I cant seem to add the values into the DB, if im using the list it only stores the first value from the list instead of all checked checkboxes.
[['sort_abc'], 'string']//not working
[['sort_abc'], 'integer']//not working
<?=$form->field($model, 'sort_abc[]')->checkBoxLIst( ['1' => 'Item A', '2' => 'Item B', '3' => 'Item C'])->label($model->getAttributeLabel('sort_abc'));?>
DB field
sort_abc | varchar(255) | yes | NULL
Also how can I add a image before every checkbox.
Yii wont magically convert your array to string or (worse) integer. You may use virtual attributes defined by getters/setter to simplify whole thing:
public function getSortAbcArray() {
if (empty($this->sort_abs)) {
return [];
}
return explode(',', $this->sort_abc);
}
public function setSortAbcArray($value) {
$this->sort_abs = implode(',', array_filter($value));
}
Then use this new attribute in form:
<?= $form->field($model, 'sortAbcArray')
->checkBoxList(['1' => 'Item A', '2' => 'Item B', '3' => 'Item C'])
->label($model->getAttributeLabel('sort_abc')); ?>
And in model rules:
['sortAbcArray', 'each', 'rule' => ['integer']]
Then $model->sortAbcArray returns values as array and $model->sort_abc as string, where values are separated by commas.
You don't need to name as array the field: sort_abc[] -> sort_abc
Simply doing it, the model will store in its attribute the checked checkboxes values.
To save the selected values, in your controller you can put:
$post = Yii::$app->request->post();
if (count($post) > 0) {
$post['YourModel']['sort_abc'] = implode(",", $post['YourModel']['sort_abc']);
}
if ($model->load($post) && $model->save()) {
...
}

Drupal db_insert('node') promote to front page equel to 1 not working

I'm using the following code for promoting to front page but it's not working. It is inserting entry in node table only. I need to insert entry into another table to promote it.
Node table showing promote=1 value in the table but the issue is while checking it through drupal admin and editing article, it's not showing checked check box or not displaying to front page.
$insert = db_insert('node')
->fields(array(
'title' => $rtitle,
//'vid' => '',
'type' => 'article',
'language' => 'und',
'uid' => '1',
'created' => $pubdate,
//'comment' => '',
'promote' => '1',
//'sticky' => '',
//'tnid' => '',
'status' => '1',
))
->execute();
So the promote=1 is not display to front page. also all the variables are working fine and query is also working correctly.
enter image description here
Have you tried using the native Drupal method for creating a node in code?
global $user;
$node = new stdClass();
$node->title = "My Cool Article";
$node->type = "article";
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->uid = $user->uid;
$node->status = 1;
$node->promote = 1;
$node->comment = 0;
node_save($node);

Laravel - Create or Update by defined attributes

I have this this table:
--Votes--
id: Integer
post_id: Integer
user_id: Integer
positive: Boolean
Now I would like to create a record only if it not exists. It is working until someone wants to click on dislike after he clicked on like(on the other side exactly equivalent).
For example someone likes a post a record will be created with positive=true. Now if the user clicks on the same post but this time on dislike, it will be created another record, but i want that it only updates the existing record.
Is there a simple solution?
Here is my Code to create the record:
$vote = Vote::firstOrCreate(array(
'post_id' => $request->input('post_id'),
'user_id' => Auth::user()->id,
'positive' => $request->input('positive')
));
Note: If someone knows how to do that, maybe he could show me how a deletion would be. For example someone clicks on like two times. The record should be created an deleted.
You can use updateOrCreate method:
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
have a look: https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L605
EDIT:
Example
$attributes = [
'name' => 'Christian',
'email' => 'christian#example.com'
];
$values = [
'name' => 'Christian',
'email' => 'christian#example.com',
'phone' => '123456789'
];
MyModel::updateOrCreate($attributes, $values);
In the example above I will search if in my table I have an entry which match name and email, if it exists I will update the records, otherwise I will insert a new entry with the $values infos

Retrieving and posting static dropdown data into mysql database in Zend 2

I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine
The official documentation for zend 2 is not really clear on how to deal with posting data from a dropdown menu into the database
Here's what i have:
my addAction in the controller
public function addAction()
{
$form = new UsersForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
my form
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('users');
//other form elements...
//the dropdown menu
$this->add(array(
'type' => 'Select',
'name' => 'groupid',
'options' => array(
'label' => 'Group',
'value_options' => array(
'0' => 'Not Selected',
'1' => 'Super Admin',
'2' => 'Company Admin',
),
),
));
//...
}
}
the view
<?php
$form->setAttribute('action', $this->url('user', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('groupid'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
When i run my application for the addAction, i get an error message:
Statement could not be executed (23000 - 1048 - Column 'GroupID' cannot be null)
where 'GroupID' is the column in my table that takes the value from the dropdown which means the field is not being posted
I need help on this
If the column in your database is GroupID, the form element should also be named that. Yours is groupid (i.e. lowercase). If that doesn't fix the issue, please edit your question to include the DB structure and the code for the saveUser() function.

Trouble insert date form to mysql in drupal 7

hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?
From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin
i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D