Drupal 8: how to generate options based on Ajax callback - drupal

In Drupal 8, I want to generate options of second select-box based on Ajax call of first select-box. The result generate a third new select box but I don't need to generate a new one. I want to replace the options of the second select-box. Please see my codes below:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['example_select'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'wrapper' => 'first',
'#options' => [
'1' => $this->t('One'),
'2' => $this->t('Two'),
'3' => $this->t('Three'),
'4' => $this->t('From New York to Ger-ma-ny!'),
],
'#ajax' => [
'callback' => '::myAjaxCallback',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
$form['example_select2'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'#prefix' => '<div id="first">',
'#suffix' => '</div>',
'#options' => [
],
'#ajax' => [
'callback' => '::myAjaxCallback2',
'disable-refocus' => FALSE,
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
return $form;
}
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('example_select')) {
$arr = array('1' => 'Nice way', '2' => 'Good way');
$form['example_select2']['#options'] = $arr;
}
return $form['example_select2'];
}

The below code is working well forme.
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
if ($selectedValue = $form_state->getValue('example_select')) {
$arr = array('1' => 'Nice way', '2' => 'Good way');
$form['example_select2']['#options'] = $arr;
}
$form_state->setRebuild(TRUE);
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand("#first", ($form['example_select2'])));
return $response;
}

Related

How to add text that there are no search results for such entered word to a custom block?

I have a view that searches for indexed entity fields using context filters. I added a custom block to the view like this:
{{ drupal_block('result_entity_product_categories', {arguments}) }}
This block displays categories that match the entered word in the search. If you enter something for which there are no search results, for example, bbbbb, I need to display something like this:
Sorry
No results for: "bbbbb"
But here are some of our most popular products
P.S. The option to add text to the No Results Behavior view setting is not suitable. It is necessary to add text in the custom block.
The build() method code of my custom block:
public function build() {
$configuration = $this->getConfiguration();
$term = $configuration['arguments']['0'] ?: '';
if (empty($term)) {
return '';
}
$index = $this->entityTypeManager->getStorage('search_api_index')->load('entity_product_index');
$parse_mode = $this->parseModeManager->createInstance('terms');
$parse_mode->setConjunction('AND');
$search_query = $index->query();
$search_query->setParseMode($parse_mode)
->keys($term);
$search_result = $search_query->execute();
$rows = [];
foreach ($search_result->getResultItems() as $item) {
if (($node = $item->getOriginalObject()->getEntity()) && ($node instanceof NodeInterface)) {
$categoryKey = $node->get('field_entity_product_category')->getString();
if ($categoryKey) {
++$rows[$categoryKey];
}
}
}
$build['container'] = [
'#type' => 'container',
'#attributes' => [
'class' => ['category-counter-wrapper'],
],
];
foreach ($rows as $key => $count) {
if ($node = $this->entityTypeManager->getStorage('node')->load($key)) {
$build['container'][$key] = [
'#type' => 'container',
'#attributes' => [
'class' => ['item'],
],
'label' => [
'#type' => 'container',
'#markup' => $node->getTitle(),
'#attributes' => [
'class' => ['label'],
],
],
'count' => [
'#type' => 'container',
'#markup' => $count,
'#attributes' => [
'class' => ['count'],
],
],
'link' => [
'#type' => 'link',
'#url' => Url::fromUserInput($node->get('field_custom_url')->getString(), ['query' => ['text' => $term]]),
'#attributes' => [
'class' => ['link'],
],
],
];
}
}
return $build;
}

ZF3 Multiple Controllers in same Module

I am learning ZF3, i am trying to add InfoController to the Album module. would my URL be ....../album/info? I am getting 404 error occurred. I have seen John Deck's post and implemented exactly the same, but still not working
This is my module.config.php
<?php
namespace Album;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return array(
'controllers' => [
'factories' => [
Controller\InfoController::class => function($container) {
return new Controller\InfoController(
$container->get(\Album\Model\InfoTable::class)
);
},
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController(
$container->get(\Album\Model\AlbumTable::class)
);
},
],
'aliases' => [
'index' => AlbumController::class,
'info' => InfoController::class,
]
],
'router' => array(
'routes' => array(
'album' => array(
'type' => Segment::class,
'options' => array(
'route' => '/album[/:action[/:id]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\AlbumController',//Controller::class,
'action' => 'index',
),
),
),
'info' => array(
'type' => Segment::class,
'options' => array(
//'route' => 'Album/Controller/Info[/:action[/:id]]',
'route' => '/InfoController[/:action[/:id]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Info',//::class
'action' => 'index',
),
),
),
),
),
'view_manager' => [
'display_not_found_reason' => false,
'display_exceptions' => false,
'doctype' => 'HTML5',
'template_map' => [
'layout/album' => __DIR__ . '/../view/layout/album_layout.phtml',
'album/album/index' => __DIR__ . '/../view/album/album/index.phtml',
'layout/album' => __DIR__ . '/../view/layout/info_layout.phtml',
'info/info/index' => __DIR__ . '/../view/info/info/index.phtml',
],
'template_path_stack' => [
'Album' => __DIR__ . '/../view',
'Info' => __DIR__ . '/../view',
],
],
);
Here's my Module.php
<?php
namespace Album;
use Album\Model\InfoTable;
use Album\Model\Info;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
Model\AlbumTable::class => function($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new Model\AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
Model\InfoTable::class => function($container) {
$tableGateway = $container->get(Model\InfoTableGateway::class);
return new Model\InfoTable($tableGateway);
},
Model\InfoTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Info());
return new TableGateway('info', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
public function getControllerConfig()
{
return array(
'factories' => array(
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController(
$container->get(Model\AlbumTable::class)
);
},
Controller\InfoController::class => function($container) {
return new Controller\InfoController(
$container->get(Model\InfoTable::class)
);
},
),
);
}
}

Add checkboxes in fieldset

i have this fieldset and these checkboxes inside...
function repository_search_filter_form($form, &$form_state){
$form['global_fieldset_container']['global_fieldset_by_metadata'] = array (
'#type' => 'fieldset',
'#title' => t('By Metadata'),
'#collapsible' => '1',
'#weight' => '99',
'#tree' => true,
'#collapsed' => 'true',
);
$form['global_fieldset_container']['global_fieldset_by_case_study'] = array (
'#type' => 'fieldset',
'#title' => t('By case study'),
'#collapsible' => '1',
'#weight' => '99',
'#tree' => true,
'#collapsed' => 'true',
);
$by_casestudy_options = array(
'1' =>'option1',
'2' => 'option2',
);
}
$form['global_fieldset_container']['global_fieldset_by_case_study']['bycasestudy'] = array(
'#type' => 'checkboxes',
'#options' => $by_casestudy_options
);
return $form;
}
i want in fieldset "global_fieldset_by_metadata" to add some dynamic checkboxes but in a callback function....
function ajaxforms_basic_callback($form, $form_state) {
$commands = array();
$form_filter = drupal_get_form('repository_search_filter_form');
$by_metadata_options = array(
'1' => 'Metadata1',
'2' => 'Metadata2',
);
$form_filter['global_fieldset_container']['global_fieldset_by_metadata']['bymetadata'] = array(
'#type' => 'checkbox',
'#options' => $by_metadata_options,
);
$form_filter = drupal_render($form_filter);
$commands[] = ajax_command_replace(".filter", $form_filter);
}
But the results are a empty checkbox...
PS. I tried and "checkboxes" in "#type" but i havent results in fieldset.

My Node Type wont Show It's Fields

I am trying to create my first drupal module that creates a simple node type wcNames. This node type has two fields, firstname & lastname.
I could get my module create the DB table for node type and add it in node_type table, but when I open node/add/wc-name fields firstname and lastname don't appear.
Below is my code. Please suggest.
<?php
// wc_name.install file
/*
* hook_schema Implementation: Creates the DB and it's fields
*/
function wc_name_schema(){
$schema['wc_name_names'] = array(
'fields' => array(
'nmid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
'firstname' => array('type' => 'varchar', 'length' => 50, 'not null' => FALSE),
'lastname' => array('type' => 'varchar', 'length' => 50, 'not null' => FALSE),
),
'primary key' => array('nmid'),
'unique keys' => array(),
'indexes' => array(
'nmid' => array('nmid'),
),
);
return $schema;
}
//function wc_name_install(){ } // Use this function to set variables for the module.
function wc_name_uninstall(){
//unset variables if any set
// Delete all wc_name nodes
db_delete('node')->condition('type', 'wc_name')->execute();
// Delete all wc_name tables
db_drop_table('wc_name_names');
}
?>
<?php
// wc_name.module
/*
* Implementation of _node_info(): define node
*/
function wc_name_node_info(){
return array(
'wc_name' => array(
'name' => t('wcName'),
'base' => 'wc_name',
'base' => 'page',
'description' => t("A smaple module to save names."),
'has_title' => TRUE,
'title_label' => t('Title'),
'has_body' => FALSE,
)
);
}
function wc_name_menu() {
$items = array();
$items['wc_name'] = array(
'title' => 'wcNames',
'page callback' => 'wc_name',
// 'access arguments' => array('access wcNames'),
);
}
?>
<?php
// wc_name_form.inc
function wc_name_form($node, &$form_state){
// Add fields
$form['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => FALSE,
'#default_value' => $node->wc_name['firstname'],
);
$form['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => FALSE,
'#default_value' => $node->wc_name['lastname'],
);
return $form;
}
?>
What am I missing?
Try this:
function createTextFieldByName($type, $fieldname, $fieldlabel)
{
$field = field_info_field($fieldname);
if (empty($field)) {
$field = array(
'field_name' => $fieldname,
'type' => 'text',
'entity_types' => array('node'),
'translatable' => TRUE,
);
$field = field_create_field($field);
}
$instance = field_info_instance('node', $fieldname, $type);
if (empty($instance)) {
$instance = array(
'field_name' => $fieldname,
'entity_type' => 'node',
'bundle' => $type,
'label' => $fieldlabel,
);
$instance = field_create_instance($instance);
return $instance;
}
return null;
}
$type =
array(
'type' => 'MY_TYPE',
'name' => t('NAME'),
'base' => 'node_content',
'description' => t("DESCRIPTION"),
'custom' => 1,
'modified' => 1,
'locked' => 0,
);
$type = node_type_set_defaults($type);
node_type_save($type);
createTextFieldByName($type,'firstname','First name');
createTextFieldByName($type,'lastname','Last name');

Drupal first module -- 500 Internal Server Error

This is my first module. I have been trying to successfully install my module since a week now.
I have gone through every line. Even the schema is being installed and entry is made at system table. But still after enabling the module It shows 500 Internal Server Error until I delete the entry from system table.
Please guide me what I am doing wrong.
Note: sisattribute table is already created in drupal database
My .install file
<?php
/**
* #file
*/
function sisinstitute_install() {
drupal_install_schema('sisinstitute');
variable_set('node_options_sisinstitute', array('status'));
$attributes = array();
$attributes['Country'] = array(
'US' => 'United States of America',
'AD' => 'Andorra',
'AE' => 'United Arab Emirates',
'AF' => 'Afghanistan',
);
$s = "INSERT INTO {sisattribute} (domain, akey, avalue, weight) VALUES ('%s', '%s', '%s', %d)";
$prevdomain = '';
$weight = 0;
foreach ($attributes as $domain => $attribute) {
if ($domain != $prevdomain) $weight=0;
foreach ($attribute as $key => $value) {
db_query($s, $domain, $key, $value, $weight);
$weight++;
}
$prevdomain = $domain;
}
}
function sisinstitute_disable() {
drupal_set_message(t('Please note that they will now have reduced functionality, and will not be protected by previous access controls.'), 'warning');
}
function sisinstitute_uninstall() {
drupal_uninstall_schema('sisinstitute');
db_query($s = "DELETE FROM {sisattribute} WHERE domain IN ('Country')");
}
function sisinstitute_schema() {
$schema['sisinstitute'] = array(
'fields' => array(
'vid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'nid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
'country' => array('type' => 'varchar', 'length' => 100),
'www' => array('type' => 'varchar', 'length' => 100),
'phone' => array('type' => 'varchar', 'length' => 100),
'email' => array('type' => 'varchar', 'length' => 50),
'provstate' => array('type' => 'varchar', 'length' => 50),
'zip' => array('type' => 'varchar', 'length' => 10),
'city' => array('type' => 'varchar', 'length' => 100),
'address' => array('type' => 'varchar', 'length' => 100),
'orglanguage' => array('type' => 'varchar', 'length' => 100),
'isactive' => array('type' => 'int', 'default' => 1),
),
'primary key' => array('vid'),
'indexes' => array(
'nid' => array('nid')
),
);
return $schema;
}
And my .module file:
<?php
// $Id$
/**
*#File
*Module for Institution support in SIS package
*/
/**
*hook_help()
*/
/**
*hook_menu()
*/
/**
*hook_perm()
*/
function sisinstitute_perm() {
return array('access institute', 'create institute', 'edit institute', 'delete institute', 'view belonged institute', 'view all institutes');
}
/**
*hook_access()
*/
function sisinstitute_access($op, $node. $account=NULL) {
if (empty($account)) {
global $user;
$account = $user;
}
if (is_numeric($node)) $node = node_load($node);
if (!isset($account->sisinstitute_nid) && module_exists('sisstudent')) {
_sisstudent_load($account);
}
if (!isset($account->sisinstitute_nid) && module_exists('sisstaff')) {
_sisstaff_load($account);
}
switch($op) {
case 'create': return user_access('create institute', $account);
case 'update': return user_access('edit institute', $account);
case 'delete': return user_access('delete institute', $account);
case 'view' : {
if (user_access('view all institutes', $account))
return TRUE;
elseif (user_access('view belonged institute', $account) && $account->sisinstitute_nid == $node->nid)
return TRUE;
else return FALSE;
}
}
}
/**
*hook_node_info()
*/
function sisinstitute_node_info() {
return array(
'sisinstitute' => array(
'name' => t('Institute'),
'module' => 'sisinstitute',
'description' => t("Institute for SIS"),
'title_label' => t("Name"),
'body_label' => t("Note"),
)
);
}
/**
*hook_form()
*/
function sisinstitute_form(&$node) {
$type = node_get_types('type', $node);
//$form['#attributes']['class'] = 'sismcomponent_node_form';
$form['title'] = array(
'#type' => 'textfield',
'#title' => check_plain($type->title_label),
'#required' => TRUE,
'#default_value' => $node->title,
// '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'title') : -18,
);
$form['isactive'] = array(
'#type' => 'checkbox',
'#title' => t('Active'),
'#default_value' => $node->isactive,
);
return $form;
}
Hmm Got it:-)(after 8 hours)
function sisinstitute_access($op, $node. $account=NULL) {
has a period instead of a comma after $node

Resources