Fetching and rendering custom-library generated blocks in twig I am using the following code in my theme to fetch 3 blocks (each containing 4 fields) generated via the custom block library interface i:e all 3  block are of the HomePage-Block type:

function legislation_research_theme_preprocess_page(&$variables, $hook) {
    for($i = 1; $i <= 3; $i++) {
        $block_entity = Drupal\block_content\Entity\BlockContent::load($i);// BLOCK_ID
        $block_view[$i] = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity);
    }

    if ($block_view) {
        $variables['page']['my_block'] = $block_view;
    }
}

In my page--front.html.twig, my blocks output via:

    {{ page.my_block }}

However, the output is of the individual fields from each of the blocks rather than 3 divs containing 4 fields of content from each block. That's making it impossible to to style:

Can anyone advice how I might be able to output each block but contained in individual parent divs?

I render my custom library blocks like this:

{{drupal_entity('block', 'block_id')}}

So you have to search your block at your library and use this block's machine name where i say block_id.
Hope it helps.


Why date field is picking the user's timezone? I have a date field with default value set to now. I have selected the site's timezone in the date field settings.

So for every user the date field value should be according to the site's timezone. But on node forms I can see the date field value is different for every user according to the timezone set on that user profile form.

Why the field value is not according to the site's timezone. it should be same for all the users.

If I disable this settings Users may set their own time zone in the regional settings then every thing works fine.

Is there any configuration I'm missing?

In Drupal, dates stored in the DB do not have any timezone fixed to them; it presumes all date fields are consistent in timezone and relies on the system's timezone setting to offset everything to its correct date for displaying.

There are two different offset settings: the field's timezone settings (which adjust from user's timezone input to the site's timezone) & the user's timezone setting which adjust display from the site's timezone to the user's timezone.

Needless to say, the various offset settings can make for a confusing situation to adjust to your needs.

If you want to keep the field adjusted to the site's settings and have the users still adjust for their own time zone, you should customize the display of your field so the time zone is presented in an unambiguous format.


About View format its css setting. I am not good at CSS. Here I want to divid every grid evenly. The is my page. My view I use grid instead of table or unformatted list, which are only text on each row not suit my want.

https://www.jeffhost.idv.tw/services

The other question is on this. I found the picture too small, while making the window smaller. How to adjust a proper setting on View?

https://www.jeffhost.idv.tw/online-buying

Thanks.

Okay, the answers to your questions are both rather simple.

Your columns are uneven because you did not apply a width to the columns. To solve this I simply applied a percentage width to the td element as follows:

.view-view-services .view-content td{
   width: 33.33%;
}

When you make your browser's viewport smaller, your images become smaller. This is due to the auto properties applied to the img tag's height and width. To solve the issue I overrode the max-width property as follows:

.view-uc-products .views-field-uc-product-img img{
   max-width: none;
{

Let me know if you have any questions!


Using a Views Output as Options in a Webform in Drupal 7? I have a list of articles on my site and currently I have a View that lists all of these articles. I want to be able to build out a webform where a user can select certain articles and then have it emailed to an address. I basically want to turn the Views list of articles into a radio button box where it can be selected for inclusion into the webform.

Are there any modules that can do this? Or how would one go about doing this if there is no module that supports this.

I'm a big fan of webform, but in this use case, I would probably use Entity Form and References instead.

Install both modules, and create your entity form.

Add a node reference field. On the field settings, narrow the results by content type "article".

Note, this would show all articles. If you were hoping to narrow down your results using views filters, you might want to investigate the sandbox project that Volker suggested.

Update: The References module allows you to use a view as a list of referenced nodes. This is very useful for drilling your results down to the exact nodes you want to show.


How do use hook_views_pre_render() to modify view fields Want to use hook_views_pre_render() to modify a field in view based upon data in another field. Starting with this code:

function sbn_views_pre_render(ViewExecutable $view) {
  drupal_set_message($view->id());
    foreach ($view->result as $key => $value) {
    // How do I select fields I need?
    }
}

What I don't know how to do is select the fields I want to work with from the $view object.

Some of the things I've tried so far:

kint($value->_entity->get('id')->value);

drupal_set_message($value->_object->get('id')->value);

drupal_set_message($value->get('id')->get(0));

drupal_set_message($value->get('parent_id')->getValue()['0']['value']);

Can someone tell me, or point me to documentation which will explain?

Thanks!

Found the answer:

// https://drupal.stackexchange.com/questions/272495/how-to-get-views-field-names-values-for-hook-views-pre-render
foreach ($view->result as $key => $value) {
  //- Get parent_id value
  $parent_id_value =  $value->_entity->parent_id->getValue()[0]['value'];
  //- Get parent_type value
  $parent_type_value =  $value->_entity->parent_type->getValue()[0]['value'];
  drupal_set_message($parent_id_value .' | '.$parent_type_value);
}


Multiple Group Managers in Organic Group The "Owner / Group Manager" of a group appears to be the person that created the container (let's say a node). That, of course, is controlled by the UID of that node.

Is it possible to have multiple "Group Managers". If that is possible, it would seem to mandate something else controlling the status of "Group Manager".

OK, so intuition told me that this was a can do... Really, membership and controlling the permissions of members is largely what OG is about.

Anyway, the brief solution that I was looking for is this:

Edit the node containing the group in question from group manager account
Click Group Tab
Click Add people
Add user name
Go back to /admin/people (this is where the magic happens)
Check the box beside the username in update options.
open dropdown box
Select Administrator member click Update

Voilà!

There is much more that can be done (for example adding custom roles). Explore on!


What are the differences between Drush 9 and 10 We are using Drupal 8.8 with Drush 9.

What are the main risks and benefits of upgrading to Drush 10?

The official release description is rather vague.

You can check the difference here https://github.com/drush-ops/drush/compare/9.7.1...10.0.0

As you can see, they are mostly fixes and improvements.

There are also some compatibility changes:

  Source: https://docs.drush.org/en/master/install/

As long as you're using PHP 7.1+ there is no risk. The benefit is that it will still work once Drupal 9 comes out later this year.


What is the difference between using hook_views_pre_render() or preprocess functions? What is the difference in using hook_views_pre_render(&$view) instead of using
[THEME_NAME]_preprocess_views_view_table_[VIEW_NAME] . I am just changing the '#markup' of field.
hook_views_pre_render() is being used in custom module and
[THEME_NAME]_preprocess_views_view_table_[VIEW_NAME] is used in template.php file ?

Behind the scenes they're pretty different (one is a hook provided by Views, the other part of the theme system). Practically speaking, as a module/theme developer you'll see very little difference. What you can do in one you can do in the other, and hook_views_pre_render() can even be implemented in a theme.

I'd say just pick the one which offers you the most intuitive/simple way to make the changes you need to. If the theme preprocess requires more complex logic/code use the pre_render hook, and vice versa.


Views Fields and Relationship with Aggregation I have three content types :
Content type A (= leg)
Content type B (= transport)
Content type C (= ticket)

B has a node reference to A.
C has a node reference to B.

I have a views list with the following and aggregation setting is on;

    FIELDS
    Content: Nid
    Content: From
    Content: To
    (field_transport) MIN(Content: Price) (for)
    (term from field_transport_type) Taxonomy term: Name (by)

    FILTER CRITERIA
    Content: Published (Yes)
    Content: Type (= Leg)
    Content: From (exposed)
    Content: To (exposed)

    SORT CRITERIA
    Content: Post date (desc)

    RELATIONSHIP
    (field_transport) Content: Leg (field_leg) - reverse
    (field_leg) Content: Transport (field_transport) - reverse
    (field_leg) Content: Transport Type
    (term from field_transport_type) Taxonomy term: Content using Transport Type

The result with 3 records is shown as below :

    RESULT
    How to go from Bangkok to Singapore:
    for $150.00
    by Plane

    How to go from Bangkok to Singapore:
    for $200.00
    by Train

    How to go from Bangkok to Singapore:
    for $80.00
    by Bus

I want the result with the only last line ( for $80.00 by Bus ). The result is correct before I have no relationship with term from field_transport_type.
How can I do that with aggregation setting MIN which I already applied in the field list?
I'm using drupal 7.10.

[Edit]
Here is the screen cast of my view :

Another thing is that the content type B (=transport) has a taxonomy term field (=transport type) which needs to be displayed in the field list. You can see them in the result - by Bus, by Plane, etc.

To be more clear, I attached another screen cast of my results :

The result should be 2 records above. The last three lines is the group of a leg ( Bangkok to Singpore ). This cannot be done by changing the pager settings. Pager is 10 for the page, meaning - latest 10 legs with cheapest tickets.

[Edit]
When I changed field_transport_type in FIELDS into COUNT(DISTINCT Taxonomy term: Name),
I got the result with the first two lines, but I lost the transport type names.

    How to go from New York to London: for $120.00 by 1
    How to go from Bangkok to Singapore: for $80.00 by 3

Perhaps you want to remove the post date sort criteria, and add an ascending sort criteria for content: price. If you only want one result value, change that in the Pager area.


Bug API migration with postgreSQL i have an issue concerning the API migration.
I have an existing drupal 7 website with a MySQL database.
Now i want to migrate this website in a new drupal 8 instalation with a postgreSQL database.
With a drupal 8 postgreSql, i can't execute the drush commande "migrate-status" or other :

while with exactly the same module and config, simply changing the BDD by a mySql one, i have access to these commands :

Does the migration modules are compatible with a postgresSql drupal ?
Regards

It looks like you simply don't have the migrate_tools module enabled in the Postgres environment.


How to pass variables between theme functions I often use functions that contain variables in the following files:

Template.php
Custom Panels Style Plugins
node.tpl.php files
field.tpl.php files
views.tpl.php files

I often needed to pass variables between these functions.

At the moment, I do this by declaring my variable as a global Using PHP's global command. However, I have read that is not best practice. Is there a better way?

I know that Drupal has variable_set() and  variable_get(). However, apparently these have similar problems to using Globals for lots of little variables.

I am newish to Drupal, but will give this a shot (I'm sure someone will tell me if I am wrong).

You can set variables that exist in different contexts by using the template.php file of your theme by adding stuff to the $variables array with preprocessor functions. So you could maybe add your variables to the YOURTHEME_preprocess_html() function, which should make them available everywhere.

function YOURTHEME_preprocess_html(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');
}


I already have a complete HTML/CSS mockup should I use a base theme or start from scratch? Will it be less painful to just build my theme from scratch using the HTML/CSS mockup that I have or should I still go through the process of using a base theme like Zen?

It's a mix of personal preference, familiarity with the theme system and, arguably most importantly, the experience of the end-user admin and how much they'll need to modify layout.

Unless the site layout will need to be extensively modified (by a non-developer, beyond just toggling/placing blocks) I would always choose to start from scratch.


Delegate user administration to a limited set of users We are currently using the excellent domain module (allows segmenting users by domain) in and the user_import module (allows uploading users via CSV) in Drupal 7.
We've got a new requirement where we want certain authorised users to be able to perform CSV uploads and edit user details for other users within their domain, but limited to no other admin function within the site (or other user details).
Without re-implementing each function (edit users, upload CSV, etc) in a new module (my fallback plan), is this possible within the Drupal permission / authorisation framework?
My gut feeling and exploration so far is no, it isn't. But I am no Drupal expert...

I was never able to find a workaround for this. I ended up replicating the UI outside of the admin panel and reused a collection of the import functions (I also abandoned the users making "manual" edits.)


How to add a div tag after a specific field? I have a view with four fields: title, body, poster, podcast.

I want to add a div tag after poster field. How can I do this?

You can simply rewrite result of poster field (it's in poster field settings), but you need to display fields, not content. Just add there poster token and div

Upd: ong, what am I about. If you display fields in your view, you can add custom Global text field. And write there custom html, remember to use php filter(works 100%, mb one another works too).


Decimal number and Charts Module I installed Charts with Google Charts in Drupal 7. Everything is ok, but when I have to use decimal numbers, with number 0.5 or 0.8, it appears to me .0 or .8 both on the vertical axis of my column chart and on the graph itself. Why?

last night I'v found the problem and solve.

change the row in the file "charts_google.inc" row n. 223

from
       $format = $prefix . '#' . $decimal_count . $suffix;

to

  $format = $prefix . '#0' . $decimal_count . $suffix;


Is there any alternate module of drupal core search form? Is there any module which can be used as an alternative to drupal core search form block.

Drupal core search is not all that optimal, it is really only meant for small sites as the implemented architecture does not scale all that well.

Most sites with a larger number of content commonly tend to integrate Solr


Issue with grouping in a view using Views PHP I posted this a week ago at the drupal.org issue queue for Views PHP, but have not received a single response, so I'm hoping someone here can help me.

I have a view that displays a conference schedule. Each session is associated with a track (taxonomy), and gets a track icon to display. There's also one or more speakers per session (entity references to the speaker nodes). There's one type of session that needs to be associated with all the track types, but we don't want it to have a visual indicator. In order to get the icon to display conditionally, I used a Global PHP field. It prints the icon (if the conditions are correct) and then the session number and title, all on a single line. This works. The view is grouped first by date/time, so all sessions on Wednesday at 10 AM show up under a single heading. This also works. Here's the output code of the Global PHP field:

<?php
if(isset($data->field_field_hide_track[0]['raw']['value'])) {
    if($data->field_field_hide_track[0]['raw']['value'] == '0') {

    $image_vars = array(
        'path' => file_create_url($data->field_field_track_icon[0]["rendered"]["#item"]["uri"]),
        'alt' => $data->field_field_track_icon[0]["rendered"]["#item"]["alt"],
        'attributes' => array(
          'class' => array('session_list_track_logo')
        )
      );

    $track_logo = theme('image', $image_vars);
    print "
" . $track_logo . " " . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "
";
    }
    else {
      print "
" . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "
";
    }
}
?>

Before adding the Global PHP, it was secondarily grouped by a dummy field that had its output rewritten to concatenate session number and session title. (both individual fields were hidden from display.) This worked, but we couldn't display the icon conditionally.

That's where the Global PHP field comes in. If I group by date/time and then by the php field, it's inconsistent between session records. Sometimes it prints the php field twice, regardless of how many speakers there are. Sometimes it prints it once for each speaker. Sometimes it prints once for the first speaker, and a second time for the next chunk of speakers.

grouped by date/time and session number (both excluded from display); displaying php field

grouped by date/time and php field (both excluded from display

I've also tried grouping by all possible common fields (date/time, session number, session title, icon, and php field) which gives me such a mess I couldn't even get a decent screenshot of it because a single record doesn't fit on my screen!

This is the desired result:

I'm attaching screenshots of all of these, as well as a mockup shot of the desired result. Can anyone help me out? (Note that the groupBySessionNumber.png screenshot was taken after the Global PHP field was added, and the icon/number/title line is a result of that field.)

Consider using a Computed Field on the Session content type to combine

the icon  (conditionally)
the session number
the session title

Then you can use that field for the secondary sort, and leave the Global PHP out of the View. Be sure to store the computed field in the database so that Views can access it.


Need Nodes to Appear Only Once I've created a view to display items with a certain content type. I'd like to display the terms in an associated taxonomy along with them. Many of these nodes have more than one term selected.

The output currently displays nodes one time for each taxonomy term assigned. How can I adjust this so that it displays each node once with every term associated with it?

Thank you!

You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.

Go and edit your view
In Advanced » OTHER section by enabling Use aggregation: Yes
In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.


Programmatically display user names according to the user profile type This is a Drupal 7 site. I have a profile2 module installed with several profile types for different users. The user name should be displayed according to the profile type:

For personal users - the user name should be build from the first and last name fields.
For business users, the user name should be taken from the business name field.

How do I display user names programmatically?

I've put the following code on a module:

<?
// Find the type of the current user
function mymodule_get_usertype(&$user) {
  $usertype = 'other';
  if (is_array($user->roles) &&
      in_array('authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('non authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('business', array_values($user->roles))) {
    $usertype = 'business';
  }
  return $usertype;
}

// Implements hook_username_alter,
// to display the user name according to the profile type
function mymodule_username_alter(&$name, $account) {

  $profile_type = mymodule_get_usertype($account);
  if (!empty($profile_type)) :
    $profiledata = profile2_by_uid_load($account->uid, $profile_type);
  endif;

  if ($profiledata) :

    switch ($profile_type) {
      case 'individual':
        $firstname = field_get_items('profile2', $profiledata, 'field_first_name');
        $firstname = $firstname[0]['safe_value'];
        $lastname = field_get_items('profile2', $profiledata, 'field_last_name');
        $lastname = $lastname[0]['safe_value'];
        $name = "$firstname $lastname" ;
        break;

      case 'business':
        $bizname = field_get_items('profile2', $profiledata, 'field_biz_name');
        $bizname = $bizname[0]['safe_value'];
        $name = $bizname;
        break;

      default:
        // For admin users, no change
    }
  endif;
}
?>

The result is that the new name is displayed whenever a user name is displayed (e.g. on the menus, on the user page, or on the user listing pages)


Block title not show for exposed filter My exposed filter's form is placed in a region, within a block. I have activated the Config Block > Display Title option (I also overrode the title) but I see no title (a h2 should be added on top of the form, like it is displayed in other custom blocks below the filter, I suppose)

Why is this happening? Could I add the title within a form_alter hook?

It is a known issue and there appears to be a patch for it: https://www.drupal.org/node/2720101


Difficulties with the #ajax form item attribute My form item is the following one:

$form['foo'] = array(
  '#title' => t('Foo'),
  '#type' => 'radios',
  '#options' => $options,
  '#description' => t('Lorem ipsum.'),
  '#required' => true,
  '#ajax' => array(
    'callback' => 'foo_get_js',
    'wrapper' => 'foo-wrapper',
    'event' => 'click',
    'method' => 'replace',
  ),
);

My AJAX function is the following one:

function foo_get_js($form, $form_state) {
  return mktime().'<xmp>'.print_r($form_state['values'], true).'</xmp>';
}

My wrapper will get updated the first time the ajax call is made, but after that it will stay the same: the time and $form_state don't get updated. If I use the 'append' method instead of the 'replace' method then everything works as intended.

Is it the supposed behavior?

Since 'foo-wrapper' is replaced at the first call, it doesn't exist in the second call, and therefore, the callback doesn't know where to put the return value.

A simple solution would be to include a wrapper in the return value, with the same id as 'foo-wrapper'.

function foo_get_js($form, $form_state) {
  return '
' . mktime() . '<xmp>' . print_r($form_state['values'], true) . '</xmp>
';
}

Please note that this is untested.


How to access taxonomy term field? I added two fields to my vocabulary terms field management. How do I get these values? There is no fields like color or Image in my Taxonomy Term vocabulary dump.

How does Drupal 8 store these additional fields?

$terms = $this->taxonomyStorage->loadTree($vocabularyName);

//CAN ACCESS
$terms[0]->name

//CAN'T ACCESS
$terms[0]->color

Its similar to any other entity on Drupal 8

$name = $terms[0]->name;

//simple text field
$color = $terms[0]->field_color->value;

//multivalue field - get array of values
$color = $terms[0]->get('field_color')->getValue();

//entity reference field
$entity = $terms[0]->field_color->entity;

//image field
$image = $terms[0]->get('field_image')->entity;
$image_uri = $image->getFileUri();

//get color entity id
$entity_id = $entity->id();

I think at least your color field is actually an entity reference


Rotate Specified # of Views Results on a Time Based Schedule I have 1000 results in a View Block. It contains a title and a teaser body. I want to be able to show 10 different results every week. How can this be done using Views? Or is there additional modules I would need?

Not many answers so I'll add my two cents.. A week long cache for the view sounds like it could do the trick.


how to get a field name by field label in Drupal 7 I have added a custom field with title 'play time'. How can I get the field name(internal value) using label value in my custom module. Is there any function to get the value?

If you want to find specific content types based on field you can use:

field_info_instances($entity_type, $bundle_name);

If you want to find any field you can use:

field_info_field_map();

In both cases you will get an array of fields and you can get field name by filtering label value.


Prevent output of control code characters in Views Data Export I've recently experienced a problem where by users have entered control code characters into Long text fields. Specifically the ASCII codes \001, \007, \008, \021 (codes for Start Of Heading, Bell, Backspace, Device control 1) which are causing havoc in my XML exports since they are not allowed by the XML standard and prevent the XML file from being parsed.

Therefore I would like to cleanse the output as it goes through Views Data Export to prevent bad characters from outputting. As commented below, this sounds like a bug in VDE, however I'm wondering whether I can tackle this issue easily with my own views hooks rather than wait for a new version/patch?

Views Data Export enables you to write your own .tpl files for fields. So, in a template for a problematic fields, you might use

preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $input);

to strip all potentially problematic characters. Of course cut list of chars for your specific need and if they are in any way meaningful to your users, consider replacing them with some mark instead of eradicating them entirely. It's a bit clumsy solution, but as far as I remember it works, ant it's fast to get up and running.

You can also use preprocess hook instead of tpl:

/**
 * Implements hook_preprocess_views_view_field().
 */
function mymodule_preprocess_views_view_field(&$vars) {
  if ($vars['view']->name == 'myview' && $vars['view']->plugin_name = 'views_data_export_xml') {
    $vars['output'] = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $vars['output']);
  }
}


How can I run Drush 8 and Drush 9 together on same machine to test some module on it? As in my earlier environment I was running Drush 6 and Drush 8 together.

I need help with the Drush 8 and Drush 9 installation. Is there any possible way to achieve it?

I tried to do porting command following Porting Commands to Drush 9, without success.

Any help would be appreciated.

Install Drush 8 by downloading the phar file as recommended in the documentation. Rename the phar file to drush8, not drush.

Install Drush 9 as recommened in the documentation. I strongly recommend to install Drush Launcher globally using a phar file as documented and only install Drush site local. This is very easy if you are already using Composer to maintain your Drupal site. If you aren't using Composer to maintain your site, you can just as well install Drush 9 globally using Composer and forget about Drush Launcher.


How to add a class to vertical tabs created using Form API? Form API element vertical_tabs does not have #attributes property.

I have two kinds of tabs. The first one is language dependent. The second one has language independent values, just shows a preview in the selected template. I want them to be visibly different on first glance.

How can I mark them, possibly without adding dummy containers that makes the form tree more complicated than form logic requires?

You are right vartical tabs don't have #attributes element.
But you can:

1) place vertical tabs in #container element with class. There you can use #attributes

2) you can add #prefix, #suffix into tabs:

$tabs['#prefix'] = '
';

$tabs['#suffix'] = '
';


How to control path alias in custom node form #validate function? To change form values in code, I understand that the right way is to add a validate function with hook_form_alter, to append the function's name to the #validate array then use form_set_value.

When I inspect the form array at this point though, I cannot see a way to reliably determine the parents of the path value.

e.g. I have

$form_state['groups']['additional_settings'][4]['alias']

And I can only assume that the 4 index is not always going to be 4; that it might be a different number if more modules are installed etc.

So how can I set the alias? (I also need to un-set pathauto's checkbox so it does not auto-generate a new path.) Am I doing it in the right place?

Thanks.

You will find the values submitted by the user in $form_state['values]. So you can just fetch the ones submitted alter them and them send them back to the form. And the path settings are located at $form['path']. $form_state['groups'] is just a way of grouping form elements together.

/**
 * Implements hook_node_form_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Add our validate function to all node forms.
  $form['#validate'][] = 'MYMODULE_alter_node_path';
}

/**
 * Custom form validate function.
 */
function MYMODULE_alter_node_path($form, &$form_state) {
  // Fetch the path values submitted.
  $value = $form_state['values']['path'];
  // Do your changes to the path and unset pathauto checkbox.
  $value['alias'] = 'new-alias';
  $value['pathauto'] = FALSE;
  // Set the values in the form.
  form_set_value($form['path'], $value, $form_state);
}


Best location to keep the javascript files in drupal 7 I am using javascript for some of the html pages.
Where should I store the javascript files in my drupal folder.

If it's a theme, and if you are defining scripts in .info file, keep the .js files in scripts folder of your theme folder (e.g sites/all/themes/mytheme/scripts). You don not have to define the whole path. Just enter the relative path to the .info file (scripts/myscript.js) and it will get included in the entire site.

if you are using drupal_add_js, in a custom module, the common practice is to keep the file in module's folder. Set it as drupal_get_path.

Although it's not recommended, if you are hardcoding the script in html.tpl.php or page.tpl.php folder, I'd place the js file in theme folder and use a drupal_get_path to get the actual path.


How can I export content-type and content from one site to another? I got handed over a drupal 7 site with two branches, one is now in production and other is dev. I am working on dev and had to create new content types and made changes existing content types.

In the meantime other users made some changes to content-type and content. Administration want to merge content types and retain the latest content.
What is the workflow to do this kind of stuff.
In the past I only had to clone whole site so I used rsync to sync file and export/import db.

This looks like way more complicated than I anticipated as both sites have same content types but with some degree of variation in field names and types.

From my current Drupal knowledge it seems like a very complex task.

Where should I start and which approach/technique should I use?

I went through other answers and found that the Node export module can export the node but how can I export the content and map the fields from one content type to another ?

Node Export

Looks like you are already familiar with the Node export module, allows users to export nodes and then import it into another Drupal installation.

Bundle copy

The Bundle copy module has support for export/import of:

Node types.
Taxonomy.
User.
Field API fields.
Field groups.


Programatically create node + panel configuration? Is there a way to programmatically create a panel node with a certain layout?

For some people, Panel Nodes is good enough. Depends on your circumstances.

The below will create a panel node with 2 column bricks layout and will use the In Place Editor (IPE):

$node = new stdClass();
$node->title = t('Home');
$node->type = 'panel';
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->status = 1;
$node->promote = 0;
$node->comment = 0;

$node->panels_node = array(
    'layout' => 'twocol_bricks',
    'css_id' => NULL,
    'pipeline' => 'ipe', // change this to "standard" if you don't want to use the In Place Editor (ipe)
);

// node_submit() populates the node with author UID and creation date
$node = node_submit($node);
node_save($node);


How to use cache set and get to store time cron ran? We have a new requirement where we need to run a job on a daily basis. We have setup cron to run every 1 hour. The goal is to have cron ron every 1 hour, but we want a specific job to run only if 1 day (24hours) has past since last run.

We used to use the Variables table to store the time the job was last run, but we need to change this to use the cache table. Below is the code (mymodule.module) we were reviewing, but it is not creating a cache table and not storing the appropriate date. So we need assistance in figuring out if we are using the correct logic so the job runs once everyday.

Note: $cache->data below is actually the last time the job ran.

mymodule_cron() {
     $data = '';
     if($cache = cache_get('last-run')) {
         $data = $cache->data;
         if($data <= strtotime('-1 day')) {
               //call helper function to perform some logic
               _some_func();
               $data = time();

               //set update date in cache
               cache_set('last-run', $data, 'cache'));
         }
    }
 }

I don't think there is something wrong on cache_get() and cache_set(). It seems a logic problem. In your code the cache is never set if a cache is not found.

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  $data = '';

  if ($cache = cache_get('last-run')) {
    $data = $cache->data;
    if($data <= strtotime('-1 day')) {
      //call helper function to perform some logic
      _some_func();
      //set update date in cache
      cache_set('last-run', time(), 'cache'));
    }
  }
  else {
    // set cache if there is no cache.
    cache_set('last-run', time(), 'cache'));
  }
}


Is it possible to get client ip in setting.php I'm trying to get the client IP in settings.php for security reasons, using the following code.
I have to support X-Forwarded-For header because accessing web server over loadbalancer.

$clientIp = \Drupal::request()->getClientIp();

It causes the following error.

  The website encountered an unexpected error. Please try again later.
  Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/my-site/docroot/core/lib/Drupal.php).
      Drupal::getContainer() (Line: 218)
      Drupal::request() (Line: 759)
      require('/var/www/my-site/docroot/sites/default/settings.php') (Line: 116)
      Drupal\Core\Site\Settings::initialize('/var/www/my-site/docroot', 'sites/default', Object) (Line: 1015)
      Drupal\Core\DrupalKernel->initializeSettings(Object) (Line: 642)
      Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Any suggestions to fix this?

In settings.php the drupal kernel is not loaded yet, so the service container is not initialized. Use the php superglobal $_SERVERinstead:

$client_ip = $_SERVER['REMOTE_ADDR'];


host static files (images) to 3rd party host such as Amazon Cloud. Any modules can facilitate this? I want host all images files to the cloud, such as amazon s3.

For example, when creating the node, uploaded automatically upload the files to the cloud, and all images path automatically point to the image stored in the cloud.

Any modules facilitate the CDN transition?

Thanks.

I would go with the CDN module, also checkout the AmazonS3 module.


relative path in blocks - multilingual - does not work I'm using Drupal 7 with i18n modules. I have 6 languages on my site.
The relative paths are working fine except for:
the relative paths in blocks for the languages other than the default language.

On my front page I have several blocks.
If I add the relative path in a block on my English (default language) front page (www.example.com) it works.
If I add a relative path in a block to my French front page (www.example.com/fr)

Link in block on the French page

Then my expectation was to get to this page

www.example.com/fr/page-in-french

but instead I get to the page:

www.example.com/page-in-french

which obviously does not exist.

I know that I can manually add in the relative path the language code

  Link in block on the French page

but since the URL that I'm accessing is www.example.com/fr , then a relative path should not contain the "fr/" since it is already in the URL.

How can I set the relative path to just "page-in-french"?

Thank you

There are 2 components in the multilingual Drupal WRT which language to show: Content and Interface. /page-in-french refers to Content, /fr/ refers to the Interface language.

Without some additional "guidance" Drupal will link to exactly the link you tell it to. In D7 translations of nodes are new nodes (with different IDs) so it makes sense there is nothing to show for /page-in-french since there are no nodes in English with that name.

Use multilink to redirect to content in language matching the interface language

If you want to make the Drupal be aware of language context in such a way to redirect to a relevant content translation to match the interface language use Multi-Language Link and Redirect (MultiLink).

It works by enabling it on the text Input filter you're using.

It comes with a special syntax to include links to nodes [NID:text] but you don't have to use it! The redirect will work even for HTML links with classes and IDs. Which means you don't have to edit the links you already have.

If you want to control which text to display in the link
you can do this in your English block:

Custom English text

and this in your Spanish block:

Custom Spanish text

The href attribute stays the same, only the link text changes.

If you want to display node title as the link text (the title of the relevant language translation) you can rely on Multilink syntax:

[34: $]

where the 34 is the NID of the English node $ represent relevant node title. This will display node 34 on the English side with node 34 title, and on the Spanish side it will display whichever node is the Spanish translation of node 34, and the link text will be the title of the translated node.

Check your Languages Detection and selection settings

Make sure you have URL set as the first enabled option. This will make sure the redirect respect the Interface language you're using.

If you give advantage to the User option, and a user has Spanish set in their profile, they would never be allowed to see English pages, as long as they're logged in they'd always be redirected to Spanish.


ImageCache action: How do I set the width as 500px and the height will constrain propotion to width? I use ImageCache Action to add watermark and resize image.

How do I set the width as 500px and the height will constrain propotion to width?

Found solution
Use "Scale" in Action, Width:500, Heigth:0,
Select "Allow Upscaling"
Then update action.


how to create a user programmatically using comment_presave hook? I am using this code.

function MY_MODULE_comment_presave($comment) {
  $name = 'test';
  $email = 'test@test.com';
  $password = user_password(8);
  $fields = array(
    'name' => $name,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => '',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'anonymous user',
    ),
  );
  $account = user_save('', $fields);
}

I get the following error.

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users}

How do I solve this error?

There are some errors in the code you are using, but the main error, which is causing the error message you quoted is that the code is creating users always with the same username, which is not allowed in Drupal: Every user needs to have a unique username.

If you are showing exactly all the code you are using for that hook, it's not clear why you keep creating an account before a comment is saved. You aren't checking which user is creating the comment, which means the user account is created even if the comment is created from the admin user.

To avoid that error message, you need to first verify the account you are going to create doesn't already exist, or you create a different username every time a comment is created. (It doesn't make sense, though.)

In the first case, you use user_load_by_name() passing the username; if the function returns FALSE, it means a user with that username doesn't exist, and it can be created.
In the second case, you just add a random number to the username, to make it unique; even in this case, I would verify there isn't already an account with that username.

As for the other errors:

The roles array should be the following one:

'roles' => array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user',
),

The first argument of user_save() is an object, not an empty string, for example the value returned from new stdClass()


Why Drupal won't remember "use search" permission settings for roles? I want to make search available to everyone who uses the site, including anonymous users.
Now, if i go to /admin/people/permissions and and try to enable "use search" for anonymous and authenticated users, the systems seems to act okay, but when I look at it again, nothing's changed. The settings seemingly won't remember my settings.
Any ideas? I hope that there's something totally simple I forgot

EDIT: in fact, it does not keep any changes in the permission system.

EDIT 2: I made it work by editing permissions through /admin/people/permissions/roles. Does anyone has any ideas why it was possible in one way but not the other?

PHP has a default setting of 1000 for max_input_vars, and once you have a significant number of modules and/or roles defined, you end up with an excess number of permissions boxes on the page.

In your php.ini file add max_input_vars = 1500 and keep incrementally increasing it until it saves.


Editable table column data In drupal 8, I am writing a custom module and in one of the function in controller -I am fetching data from an external API, then displaying it in table format using -
 foreach($rec as $data) {
    ksm($data);
    $rows[] = [// mydata
]};

return [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,

  ];

This is working correctly.
But I want table cells to be editable and when user edits the data, a listener gets invoked (or provide an update button for the user).
Now this listener would  do some stuff  with updated data(make external API call).
My doubt is how can we do this with tables? Is there any way to make some columns of table editable and register a listener in Drupal.
Would I need to create a node for each row of this table data?
If a node is required, then how to do ?
I am new to Drupal 8, just started a month ago, kindly help.
Thanks in advance.

What you can do is first create nodes using the API data and create a table view. so that the views fields can be referenced to nodes and they can be updated.
By this way you wont be needing any additional event handlers.
To Create Nodes you can use the following snippet:
use \Drupal\node\Entity\Node;

$node = Node::create([

       'type' => 'new_content_type',

       'title' => 'Creating a new node',

       'body' => 'Body of the node',

       'field_mail'=>'email@gmail.com',

       'field_link'=>'http://www.example.com',

       'field_date'=>[ '2017-07-22', ],

]);
$node->enforceIsNew();
$node->save();


What does the message "hook_flag_access: ignore" mean, and how do I turn it off? I currently have the flag module enabled, and I have placed a simple flag on a node content type. The flag works fine, but I'm getting a Drupal message / notification in green that says "hook_flag_access: ignore" when the node is viewed.

It appears to be called by sites/all/modules/flag/tests/flagaccesstest/flagaccesstest.module

What does this message mean, and how can I fix / disable?

I'm using flag 7.x-3.1 on Drupal 7

Thanks,
Steven

Sounds like you need to disable the flagaccesstest module.

The problem is, in flagaccesstest.info the module declares

hidden = TRUE

So, it doesn't show up in Drupal module admin.

You could probably still disable it with Drush

drush dis flagaccesstest

or even (last resort) SQL:

UPDATE system SET status = 0 WHERE name = 'flagaccesstest';

Alternatively, in flagaccesstest you could comment out

;hidden = TRUE

and then disable the module from Drupal module admin UI.


Reference a filename in form validation for an image I am new to Drupal and am making a module to alter a content type. I have a content type that allows a user to submit an email and an image and I want to change the filename of the image to the email before it submits to the database. I figured I can do this in the form validation but I am having trouble finding the right code to access the filename value using $form_state. I am using the form alter hook and adding to the validation.

You can to this in the submit handler to rename the file.

function SUBMIT_HANDLER($form, &$form_state) {

  $node = $form_state['node'];

  global $user;

  // Loop over the uploaded files. Be sure to re-name field_files to the name of
  // your file field.
  foreach($node->field_files[LANGUAGE_NONE] as $item) {

    // Load the file object
    $file = file_load($item['fid']);

    // To set the destination first remove the filename from the stream wrapper
    // URI.
    $destination = str_replace($file->filename, '', $file->uri);

    // Modify this line to the name of your group field.
    $group = $node->field_group[LANGUAGE_NONE][0]['value'];

    // And then append the group, uid and put the filename back on the end.
    $destination .= $group.$user->uid.$file->filename;

    // And finally rename the file.
    file_move($file, $destination);
  }

}


How do I remove "active" css class from breadcrumbs? I am trying to include Structured Data in my breadcrumbs. The google validator throws an error on my final breadcrumb. When I remove class="active" from the code in the code validator window the code passes without error.

I used the theme_breadcrumb hook to add the Structured Data Markup to the breadcrumbs, but there is no mention of the css active class.

function MYTHEME_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    $breadcrumb = substr_replace($breadcrumb, 'http://mywebsiteexample.com/', 9, 1);
    $rich_snippet = 'rel="v:url" property="v:title" ';
    $breadcrumb = substr_replace($breadcrumb, $rich_snippet, 3, 0);
    if (!empty($breadcrumb)) {
        $breadcrumb[] = ''.drupal_get_title().'';
        //Added this line  to avoid displaying node title twice
        unset($breadcrumb[count($breadcrumb) - 1]);
        $output = '' . t('You are here') . '';
        $output .= '
' . implode(' » ', $breadcrumb) . '
';
        return $output;
      }
    }

Is there another hook I can use to remove the active class exclusively for breadcrumbs? Ideally I would like to do it without inserting Javascript into any templates.

Why not use jQuery .removeclass() on document load so that it removes 'active' from breadcrumb for each page.

More information here.

jQuery remove class


Is it possible not to have $_GET values in views' exposed filters? I can't seem to find a setting to do this nor am I familiar with any hook to implement this. Is it even possible?

I don't want to use ajax though.

You can enable Ajax and extra stuff will not be added to the URL.
If the problem is too long URLs, do a google search and see how short the URL is. However you can clean up the URL (that means you will use $_GET values) by setting a shorter URL parameter identifier.

Click on the exposed filter and expand the exposed filter settings. You will see a text field to enter the parameter string for this filter. Give a meaningful but tiny string.

For example, default URL would be  like:
path/to/view?field_my_weird_field=drupal

You can change it to:
path/to/view?text=drupal


Dealing with errors 403, 404 in Google Webmaster Tools I know it may not be strictly drupal releated question, but I'm curious what would be the best approach to solve it with Drupal.

403 errors to: taxonomy/term/%/feed

I have around 900 errors with 403 most of them look like this taxonomy/term/26/all/feed so they seem to be caused by taxonomy/term/%/feed and my question is how could I best fix this issue ?

So that Google would not penalize me with 404's after ? should I somehow change the view.. or ? not sure how to approach this maybe you have experienced similiar issue also when I try to accesss "name_of_term/feed" it doesnt seem to work

404 errors exposed fields with ?field_name=value

I have have around 200 errors of 404 type most of them look like this: NAME_OF_TERM?field_brand_tid=All&field_color_tid=192&field_size_tid=253

From what I understand it is showing options in exposed filters for items that doesn't have any nodes assigned to them.

For Taxonomy terms you can use Disable Term Node Listings module (https://www.drupal.org/project/disable_term_node_listings)

There is also a great write up on drupal.org about similar issues: https://www.drupal.org/node/345620

In short use robots.txt to disallow paths like ones you specified above. This will prevent google from indexing those pages in first place.


drupal 7.10: View of Most viewed posts i am trying to create a most viewed posts page using views. I know how to create a page with most commented post but I can't seem to find the view count option. Any suggestions. Do i need to add a relationship?

Try using the Statistics modules. It come with Drupal core.

Documents from d.o:
http://drupal.org/documentation/modules/statistics

UPDATE BELOW: (SCREENSHOT)


Creating node via REST POST gives "leaked cache metadata" error I'm trying to create new nodes by POSTing to /entity/node?_format=json.
This is the body I'm sending:

{
    "_links": {
        "type": {
            "href": "http:\/\/my.drupal.be\/rest\/type\/node\/group_of_documents"
        }
    },
    "title": [{
        "value": "Direct test - type 682"
    }],
    "body": [{
        "value": ""
    }],
    "field_owner": [{
        "value": "Symfony"
    }],
    "field_type": [{
        "target_id": "682"
    }]
}

And, in a way, this works. Because the document gets made, and everything is filled in.

But I keep getting an error:

A fatal error occurred:
The controller result claims to be providing relevant cache metadata,
but leaked metadata was detected.
Please ensure you are not rendering content too early.
Returned object class: Drupal\rest\ResourceResponse.

If I create a node without field_type, it doesn't throw an error.

field_type is the only field that has the Reference type -> Reference views -> Reference method set to Views: Filter by an entity reference view. Does that have anything to do with it?

That's a core bug, see https://www.drupal.org/node/2626298 and https://www.drupal.org/node/2663638 (either of those two would avoid this).

The views reference thing is a good hint. Sounds something runs there that then triggers this exception. You could open an issue for that too if you can find the exact reason.


Attaching workflow to node using rule Is there anyway I can set workflow dynamically using rule. Basically I need to setup workflow for given article only when someone flagged that article.

So can I setup some kind of rule that when an article is flagged, initialize workflow for that node and assign it to one of the workflow state?

-- Many thanks for your time.

Why not just set up a workflow that includes a default "no_workflow" state?  Use rules to automatically set all nodes to the "no_workflow" state upon creation.  Then, when a node is flagged, use rules to set it to the appropriate state.  That way, all nodes are subject to the workflow, but by default they don't move through the states until they are flagged.


Recreating a media_gallery using a view? I have a site that includes a photo gallery, using the Media Gallery module. I am now trying to create a mobile site, and the media gallery page, and all of the galleries look horrible on mobile (I'm using the Mobile Jquery theme.) I am trying to create my own view displaying all of the galleries, and a view displaying each image (depending on the photo gallery) I have seen tutorials on how to create a photo gallery from scratch using content, but the media gallery doesn't seem to create individual nodes for each image. How do I make a view for the media galleries, and out of curiosity, how does the media_gallery module its self work?

I haven't used Media Gallery, but have used a few others - they all do similar things though often in quite different ways.

First off, it's not really necessary to create a new node for each image - Image Field can contain multiple images, depending on its configuration.

I recently created a Gallery content type with two image fields - one for the gallery "cover" with a single image and one with unlimited images allowed, for the gallery contents. I then used Views to create a View with several Page displays (one to display a list of galleries, another to display each gallery's contents), along with the Colorbox module for image display in a lightbox, and the Plup module (and plupload jquery plugin) to do drag and drop all-at-once uploads into the gallery. Works like a champ and very easy for site maintainers to deal with - all they have to do is upload a "cover" image, drag the whole mess o' images into the plupload area, give it a title, and save it.

Doing it this way lets you leverage image styles in several places - the cover image, the gallery page images, and the colorbox display images - plus Colorbox makes it possible to set up the gallery slideshow as automatic or manual advance. Pretty cool, and no custom code to write. You can fiddle with the View's output options as needed and, should you need more styling action, you have the option of writing theme templates to get the output looking the way you need it.

You can see it at work at http://betheldrupal.m-so.com/galleries - not in production yet but working well so far...

Let me know if you want details - I can export the views and stuff if need be.


CiviCRM report by address Is there a way to pull a CiviCRM report that compiles all donations from matching addresses?

Whether or not the people at the matching addresses are formally part of a household -- kind of like the mailing option that merges matching addresses for a mailing export to prevent double mailings.

If I understand you correctly the  Aggregate Household Contribution Report is what you are looking for.  If that is not sufficient, it may provide a good basis for a custom report.


Panels Node Add form and passing url parameters I'm using panels to override a nodes display page. I also want to use it to overide the edit and add page. The cck type I'm trying to add has a node reference field, this needs to be passed in through the url.

So far, I've add the panel varaint, added a context (node add form), and added the form to the "content" of the panel, All I need to figure out is how to pass the referencing node ID to the form. Does any one know how to do this?

This is an old question but there is an easier way with the Node Reference URL Widget module, which should work with Panels as well.


Duplicated nodes of thew view I created a view, that is simple page containing nodes of a specific content type.

It had worked before I started to translate nodes.
I added a new translation for my node and now I have duplicated entries of the same node displayed on the page.

I have solved this problem for one view with just enabling aggregation.

But with this one it doesn't work.

It outputs the same node twice. And the language is the same, but at first they have different languages.

Really, I don't understand what is going on with the translation modules, or what causes such a weird behavior. I have asked a lot of questions about translation in Drupal, and each time I try to do anything related to the translation, I get a new error.

Maybe I am going crazy, but something terrible is happening with the Drupal translation modules.

Please suggest how to deal with this ?

I can suggest you an alternative approach.
In your views filter area, create a new filter, based on the current user's language.

How to do it:

Views: add filter criteria -> Content: Translation language
Check the checkbox labeled "Interface text language selected for page"

Another thing, you can go to Views overview page, and then Views settings tab -> Show SQL query option.

How to do it:

Go to admin/structure/views/settings
Check this option

In this way this will always show the query that gets executed.
I suggest you copy it it here, so that the other people will have better time understanding what you want to achieve.

Notes:
The Drupal 7 site builders are used to "Currents user language" checkbox, however that checkbox has been renamed.
More information:
http://hojtsy.hu/comment/21596#comment-21596

Best regards,
Oleg


hook_menu implementation producing error page I am trying to create a new module implementing hook_menu, to render a page on my company's web site, which I have taken over from the external firm who designed it. There are other modules that use the hook_menu mechanism successfully on the site.

However, when I create my module and try to access my new page, I get a message indicating "Error. The website encountered an unexpected error. Please try again later.", with no real indication of what the error is.

Here is my code:

<?php

function customer_stories_menu(){
    $items['test'] = array(
        'title' => 'Products Display',
        'title callback' => 'customer_stories_title',
        'page callback' => 'customer_stories_page',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function customer_stories_page() {
    return "Test 123";
}

function customer_stories_title() {
    return "Title";
}

I have made sure that I cleared the cache after putting the code in place. Could something in the site be preventing new hook_menu pages from working?

I should also mention that I first tried creating a new view page to get to the data I wanted to display, but I also got a non-descript error page when I tried to access the defined URL for the page. The two issues may be related. Thanks for any help you can provide.

I've got this noted down as my starting point for a  module .

function helloworld_menu() {

$menu['helloworld/hello'] = array(
    'title' => 'Hello World',
    'page callback' => 'helloworld_hello',
'access callback' => TRUE,
);
   return $menu;
  }

function helloworld_hello() {
   return 'Hello World';
 };

do you still get an error if you take it back to this point.


Installing Drush on WSL How do you install Drush on WSL (Windows Subsystem for Linux) when the following command from Drush docs, doesn't work?

php -r "readfile('http://files.drush.org/drush.phar');" > drush

sudo wget http://files.drush.org/drush.phar
sudo mv drush.phar /usr/local/bin/drush
sudo chmod +x /usr/local/bin/drush
# test drush by executing:
drush status

Note_1:  For possible future releases --- If there will be non-Ubuntu version of WSL you might need to download the wget Linux utility to use it for downloading drush.phar.

Note_2: To those who have yet to install WSL - See this thread.


Overriding custom page variable I created a template file (page-classifieds.tpl.php) for a classified page.  I would like to override variables of this particular page preferably using a preprocess function.
How can I do that?
hook_preprocess_page() overrides variables for all the pages. I don't want that to happen.

Try this:

/**
 * Variable preprocessor for the page template.
 */
function THEMENAME_preprocess_page(&$variables) {
  if (arg(0) == 'classified') {
    // Do things here.
    $variables['my_new_variable'] = 'Something';
  }
}

Note that the template page-classified.tpl.php will also match all sub paths of that page too, like:
yoursite.com/classified/something
yoursite.com/classified/something/something


How can I show the latest added content to a specific link? I have content type Videos, lets say I have 5 videos, they have these url links:

/videos/video-name-1
/videos/video-name-2
/videos/video-name-3
/videos/video-name-4
/videos/video-name-5

What I want is when I go to /videos I want this page to show the last video added (/videos/video-name-5) and I want to make this dynamic e.g. if I add a new video, when I visit /videos it will show me the page of that new video I added.

How can I achive this? As much as possible I don't want to use redirect.

You can create a views page that shows the most recent video.

Structure > Views > Add new view

Title: "Videos"
Show content of type "Video" sorted by "Newest first"
Check "Create a page" option
Page title: "Video"
Path: "videos"
Display format: "Unformatted list" of "Full posts"
Items to display: "1"
Save & edit
Save again

Now go to the url: http://my-drupal-site.com/videos and it will display the most recent video via the view you created above


Migration taking increasingly long periods of time I have a migration and I've noticed that the code, through each batch operation, seems to process less and less items.

For example, the first few cycles, it'll say, "processed 600", and 600 or around there will be processed. However about 5-10 cycles in, and it will still say "processed 600", and it actually processes perhaps 100 or 200. This eventually stops the migration from happening, as it essentially grinds to a halt.

It was completing on my local machine and not the stage environment, which I initially thought to be due to some sort of environmental condition. Now I think that the cycles on my local were just large enough to allow everything to process before it grinded to a halt.

I'm not sure what is causing this, and if it's in this migration, or the migration that this migration is extending. I'll include the former, and if anyone needs the latter, let me know.

Note, there may be occasional instances where the words Company or Type are capitalized when they should not be - I just did a quick find/replace for sensitive data.

class CompanyTypeUserDataMigration extends CompanyCertBaseMigration {

public function __construct($arguments) {
    parent::__construct($arguments);

    $this->machineName = "CompanyTypeUserData";
    $this->systemOfRecord = Migration::DESTINATION;
    $this->group = MigrateGroup::getInstance("Company");
    $query = Database::getConnection('default', 'Type')
        ->select('Type')
        ->fields('Type', array('Name', 'Username', 'Address', 'City', 'State', 'Zipcode', 'Country', 'Phone', 'Notes', 'Email'));
    $query->addExpression('`Company Name`', 'Company');
    $query->addExpression('`Supervisor Email`', "supervisor_email");
    $query->addExpression('`Declined Recert Renewal`', "declined_recert");
    $query->isNotNull('Username');
    $this->source = new MigrateSourceSQL($query, array('status' => 'Status calculated based on various fields'));
    $this->destination = new MigrateDestinationUser();
    $this->map = new MigrateSQLMap($this->machineName, array(
            'Username' => array('type' => 'varchar',
                'length' => 50,
                'unsigned' => FALSE,
                'not null' => FALSE,
            ),
            'Email' => array('type' => 'varchar',
                'length' => 50,
                'not null' => FALSE,
            )
        ), MigrateDestinationUser::getKeySchema()
    );

    $this->addFieldMapping('name', 'Username');
    $this->addFieldMapping('field_company', 'Company');
    $this->addFieldMapping('field_supervisor_email', 'supervisor_email');
    $this->addFieldMapping('field_notes', 'Notes');
    $this->addFieldMapping('field_status', 'status');
    $this->addFieldMapping('field_full_name', 'Name');
    $this->addFieldMapping('uid', 'user_id');
}

public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
        return FALSE;
    }
    if (empty($row->Username)) {
        return FALSE;
    }

    $uid = $this->find_user_id($row);
    if($uid === FALSE){
        return false;
    } else {
        $row->user_id = $uid;
        $user = user_load($uid);
        if(isset($user->name)){
            $row->Username = $user->name; //so we don't try to overwrite username permutations
        }
    }
}

}

What's the total number of nodes you're importing? I've hit this issue before using the D2D Migration module. I've found that D2D starts to slow down on consecutive batches when I'm importing in more than ~5K nodes. In scenarios where I've needed to import 10K-100K nodes, batches eventually slow down to where nothing is ever imported.

Using XHProf & XDebug, I traced down the issue to database objects consuming tons of memory & CPU to the point of stopping PHP execution. I've never been able solve the issue for importing over 10K nodes using D2D. Searches all over the internet have produced nothing. In many instances I've had to rely on custom PHP import code as since I could not use D2D.


Can I get Entity Cache Tags from a Route? If I have a node object I can use $node->getCacheTags() to get the cache tags for the node object, and I can do the same for other entities. Is there a way for me to do something similar with a Route object?

$cache_tags = $route->getCacheTags();

or maybe there's a way for me to do something like this, where $entity is populated with the $user, or $node, or $view, etc. object that is responsible for the current route:

$entity = $route->getEntity();
$cache_tags = $entity->getCacheTags();

Adding my eventual solution based on @No Sssweat's comment.

I created a method in a service like:

public function getEntityFromRoute(RouteMatchInterface $route_match) {
  foreach ($route_match->getParameters() as $param) {
    if ($param instanceof EntityInterface) {
      return $param;
    }
  }

  return FALSE;
}

Then I have code like the following where I'm not entirely sure what entity type may be providing the route:

$route_entity = $MY_SERVICE->getEntityFromRoute(\Drupal::routeMatch());
$cache_tags = [];
if ($route_entity !== FALSE) {
  $cache_tags = $route_entity->getCacheTags();
}

Then I create my render array using the cache tags.


extract list of user id's from views to tag a content automatic I want to extract a list of users id's from views to automatic tag the user generated content.

The function is important because a company should be able to make a list of users receiving their ads. These ads are a defined content type they are able to make and it would be great if these user id's could be tagged automatically. This is the only way (as I see it) I am able to control which users are exposed to these ads, because in most instances its only part of a group that should be exposed to it.

Can anyone help me with making this functionality, either in code or through modules I do not know about.

Perhaps you could use Views Bulk Operations to list the advert nodes and assign the relevant field information though 'Modify entity values' action

It will allow you to filter and select the adverts to update then batch update them.


Displaying data from a web service I'm using Drupal 7, and I need to retrieve data from a web service. This data cannot be stored in the Drupal database due to regulations.
What would be the best practice for retrieving this data: using Java, Drupal Entities, or storing in tokens?

We are currently making calls based on an ID stored in the database and displaying the data from the web service associated with that ID.

The problem with this is that it's all being done outside of Drupal, and we are unable to use Drupal to manage any of this content. So we have many modules with custom code to do everything from creating forms, pre-filling forms, tying into a users account on Drupal, etc.

We are at a point where we can totally refactor how this works.

Do you have any suggestion on how we can improve this?

It sounds like your question cannot be answered unless it is redefined.  Drupal entities, views, and all of the other niceties that you would like to do involve storing information in the database.

You might look more closely at your regulations, and see what specifically they allow you to do.  For example, sqlite stores its entire database in a file. If you used an sqlite database where the database file was stored in a volitile storage device (e.g. a RAM based filesystem), would you still meet regulations?

Even if this is possible, you might have performance problems if the amount of data you need to store is large, because sqlite was designed only for small databases, and is mostly used for testing.  The same idea might work for mysql or postgres, though, as ultimately even these databases store their data in files.

If your data retention regulations are strict enough, you may find that the technique you are currently employing is the best you can do.


Nothing returned from taxonomy_term_load function The --very normal-- taxonomy_term_load() doesn't seem to be able to load entities within a custom menu callback. Yet I can access a profile entity, load fields, and get the field tids, but I get nothing from the taxonomy load function!

function mymodule_menu() {
  $items = array();
  $items['user/account-convert'] = array(
    'title' => 'My Page',
    'page callback' => 'mymodule_page',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mymodule_page() {
  global $user;
  $profile = profile2_load_by_user($user, 'my_profile_type');
  // Sanity check tid return. Success.
  echo $profile->field_profile_myfield[LANGUAGE_NONE][0]['tid'];
  // Term name returns nothing. The object just won't load.
  echo taxonomy_term_load($profile->field_profile_myfield[LANGUAGE_NONE][0]['tid'])->name;
}

This makes absolutely no sense.

I have even sanity checked outputting hard coded tid's like echo taxonomy_term_load(1708) after 100% confirming it's a valid tid value.

Additionally I followed the function tree up and tried calling taxonomy_term_load_multiple
 directly, and entity_load directly. All give me nothing.

Furthermore I can confirm the function is valid and available at that point with function_exists, and the lack of undefined function errors.

Probably, this is a Taxonomy Access issue.

See taxonomy_access_query_term_access_alter().

(For the rest of the Internet, I only know this is the issue because Josh and I are working on the same codebase and I ran into the exact same issue in a completely different context.)


Redirect from within controller always goes to home page I have a custom module named rsc.

My Default 404 (not found) page is set to /page-not-found in Basic site settings.

My rsc.routing.yml file contains

  rsc.pageNotFound:
    path: '/page-not-found'
    defaults:
      _controller: 'Drupal\rsc\Controller\rscController::pageNotFound'
      _title: ''
    requirements:
      _permission: 'access content'

My rscController.php file contains:

  class rscController extends ControllerBase
  {
    public function pageNotFound()
    {
      $path = '/test-page'; // Just for testing

      if (($url = \Drupal::service('path.validator')->getUrlIfValid($path))) {
        $route = $url->getRouteName();
        $param = $url->getRouteParameters();
        error_log("route=$route param=" . print_r($param, true));
        return $this->redirect($route, $param);
      }
      else {
        return
        [
          '#markup' => 'No such page'
        ];
      }
    }
  }

/test-page is the alias for /node/125.

If I type mywebsite.com/junk in the address bar (to force the not found page to be invoked) and press Enter, I am always redirected to the home page, even though the error log contains the result

route=entity.node.canonical param=Array
  (
    [node] => 125
  )

What am I doing wrong? Why doesn't $this->redirect() take me to the node?

When you call a controller as error page via the basic site settings this is not the controller of the main request, this controller is executed in a subrequest to get a themed output of the otherwise simple text message you see for non 4xx exceptions like a 500 error.

Better place the redirect in the main request, before the rendering of the exception is delegated to a subrequest by CustomPageExceptionHtmlSubscriber. You can use the default priority 0, because the core exception handler has -50.

@MarshallMorrise has posted the working code at https://drupal.stackexchange.com/a/290659/47547


How do I keep fields from being in the same row? I've attached a pic to show what I'm talking about.  I'm using 'fluid-grid' in Views.  Drupal 7.  Thanks so much![1]

Find the class of the element/field above (using your browser's developing tool) and try this CSS:

.field_my_field:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

Change the "field_my_field" with your class name. Clear Drupal cache.
It should push the next element below.


Filter a field based on the content type in a view(Drupal 7) I need to remove a field for a view(Block) for a particular content type.

I have two different content types.One is Article and another is External News.

The following are the fields I added in the view.

Field:

      Content: Title
      Content: Post date
      Content: External URl
      Content: Last comment author
      Content: External URl

CONTEXTUAL FILTERS:
   Content: Has taxonomy term ID

FILTER CRITERIA
    Content: Published (Yes)  AND
    Content: Type (in Article, ...)
     AND
     Content: Has taxonomy terms (with depth) (= Technology)  AND | Settings
     Field: Tags

Here I need the field Last Comment author to display only when the content type is Article and not for External news.

Can Anyone help me how to filter the field based on the content type for a view block

You can use a preprocess hook to build in some logic to now show the last comment when the content type if of the type is External news. You need to add the content type and exclude it from display. That will make the value available in the preprocess hook.

You could use hook_preprocess_views_fields for this.


How to have the autocomplete option with ajax in a text field? I am struggeling with creation of tetxfield with autocomplete option for my Drupal 8. My Drupal website is multilingual, and on one view page we present some content in Default language, by typing in the textfield some other language, I need to change the language of the content. For this I created a filter (Translation language = Content language selected for a page), and I want to expose it in a custom block.

My custom block looks like following:

<?php
/**
 * @file
 * Contains \Drupal\filters\Plugin\Block\FilterLanguages.php
 */
namespace Drupal\filters\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * @Block(
 *   id = "block_filters_languages",
 *   admin_label = @Translation("Filter for languages"),
 *   category = @Translation("Filters"),
 * )
 */
class FilterLanguages extends BlockBase {

  /**
   * {@inheritdoc}
   */

public function build(){

$form['language'] = array(
  '#type' => 'textfield',
  '#placeholder' => t('Choose language autocomplete'),
  '#autocomplete_route_name' => 'filters.autocomplete',

);

return $form;
  }
}

To provide autocompletion option, I have created routing file:

filters.autocomplete:
  path: '/filters/autocomplete'
  defaults:
    _controller:'\Drupal\filters\Controller\AutocompleteController::handleAutocomplete'
 requirements:
    _access: 'TRUE'

And Controller:

namespace Drupal\filters\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Controller\ControllerBase;

class AutocompleteController extends ControllerBase{
  /**
   * Returns response for the autocompletion.
   */
  public function handleAutocomplete(Request $request) {

    $languages = \Drupal::languageManager()->getLanguages();
    return new JsonResponse($languages);
  }
}

I have oriented on the followin tutorial
But the autocompletion still doesnt work. Could you please help me to solve the problem?

You need to filter the user input and return the matches.

  public function handleAutocomplete(Request $request) {
    // Getting the user input.
    $string = $request->query->get('q');
    // Getting the languages.
    $languages = \Drupal::languageManager()->getLanguages();
    // Getting the matches.
    $matches = preg_grep("/$string/i", $languages);
    // Returning the matches.
    return new JsonResponse($matches);
  }


How to get language code of a field in a node I have a requirement where in hook_node_insert I need to get the language code of a field

What I have tried is

$langcode = $node->{$field_name}->langcode

But this returns null. Any suggestions?

And is it possible that different fields in a node have different langcode?

You can use getLangcode
Try with:

$node->{$field_name}->getLangcode()


How to display a contact form as a node block? I have a content type let’s say "hotels" and there are a bunch of nodes for different hotels. I would like to display a content form either as a block or in the node itself, where users can send an e-mail to the accordant hotel owner.

How can I do this? I have tried using display suite and entity reference but could not get this to work.

Thanks for your help :)

For non coding solution, you can go with

Create the form using Webform and utilizing Webform Blocks and Token

  Webform is the module for making forms and surveys in Drupal. After a submission customizable e-mails can be sent to administrators and/or submitters. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.

Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Worth mentioning, just might not do for this question's specific use case.

Do it programmatically by creating a custom block and fetching the form, you can find an example here Problems to integrate a form into a block


Get SQL From View to put in db_query() I am using views and have a query to return some data. I want to take the SQL from the view and use it in my code.

The SQL the view is creating is:

SELECT node.title AS node_title
FROM
{node} node
LEFT JOIN {field_data_field_order_reference} field_data_field_order_reference ON node.nid = field_data_field_order_reference.entity_id AND (field_data_field_order_reference.entity_type = 'node' AND field_data_field_order_reference.deleted = '0')
INNER JOIN {node} node_field_data_field_order_reference ON field_data_field_order_reference.field_order_reference_nid = node_field_data_field_order_reference.nid
INNER JOIN {field_data_field_service_status} field_data_field_service_status ON node.nid = field_data_field_service_status.entity_id AND (field_data_field_service_status.entity_type = 'node' AND field_data_field_service_status.deleted = '0')
WHERE (( (node_field_data_field_order_reference.nid = '110' ) )AND(( (node.status = '1') AND (field_data_field_service_status.field_service_status_value = '1') )))
LIMIT 1 OFFSET 0

When I try and run this code in mysql I get back some errors. Such as:

It seems not to like the {}.

Is there an easy way to transform this View SQl into SQL that I can run using db_query()?

Assuming the table and field names are valid, you can run that SQL straight through db_query() and it will work fine.

It won't work if you just put the raw query into an SQL client, as Drupal uses brackets around table names to substitute in any necessary prefix. MySQL doesn't do that, so if you want to run the same query against the server proper, you need to remove the brackets from around the table names.


View of users having same taxonomy terms? I'm running a D7 system where every user has a skills field which is a taxonomy field.

How do I create a view to pull users where they have/share same skills (taxonomy id's) with the login user.

So for example If I've added 'photoshop' to my skills and when I login the view should provide me other user who have tagged their profiles with taxonomy term 'Photoshop'.

Note: view of users having same taxonomy term as well as login user have.

Thanks

The right way to solve this is by writing a default argument handler.  A patch to do this was started here: https://www.drupal.org/node/721390

A "shortcut" to doing this would be to use the PHP Code default argument handler and plug it in directly.  This is not generally recommended; it would be much better to put the code in a custom default argument handler so you should Google around for how to set one of those up as that's a bit beyond the scope of this question.  But here are the steps for using the PHP Code approach and you can use the same logic for a default argument handler:

Create a view listing users
Add a contextual filter to filter on the user skills field
In the contextual filter option, for "When the filter is not in the
URL" choose "Provide a default value" and select "PHP Code" from the
list.
Assuming your field is named "field_skills", enter the following:

PHP code:

global $user;
$account = user_load($user->uid);
$terms = array();
if (!empty($account->field_skills['und'])) {
  foreach ($account->field_skills['und'] as $value) {
    $terms[] = $value['tid'];
  }
}
return implode('+', $terms);

Down towards the bottom of that form there's a "more" link.  Be sure
to open that section of the form and select "Allow multiple values".

At this point, you should have the list that you want with one caveat: the currently logged-in user will show up in this list.  You probably don't want this.  To prevent that from happening add another contextual filter that excludes the current user from the list:

Add a contextual filter on the User:Uid value
Choose "Provide default value" for "When the filter is not in the
URL" and, out of that list, choose "User ID from logged in user".
Under the "more" link at the bottom, choose the "Exclude" option.


A function to get the term parent function term_parent($tid) {
  $row = db_result(db_query("select * from {term_data} where tid = ?",array($tid)));
  if ($row['pid'] > 0) {
    $term = term_parent($row['pid']);
    $row['classid'] = $term['tid'] . '^' . $row['classid'];
    $row['classname'] = $term['name'] . '^' . $row['name'];
  }

  return $row;
}

I don't know why it is using tid = ?. When should I use ?.
What's the meaning of $row['pid'] and of the following line?

$row['classid'] = $term['tid'].'^'.$row['classid'];

In a Drupal query, ? should never be used. Drupal uses placeholders, which are listed in db_query(), and that allow to

type casting to a integer the value passed for the %d placeholder
escape the string passed as value for the %s placeholder
convert the value to a floating point value for the %f placeholder
convert and escape the value passed for the %b placeholder

This means that, for example, db_query("SELECT * FROM {table} WHERE value = %f", "12") would convert the string "12" in the floating point value 12.0, and db_query("SELECT * FROM {table} WHERE string = '%s'", "It's an example") will change the string passed as argument to "It\'s an example".

The query is wrong, in a way, as taxonomy_schema() doesn't define pid (nor classid) as fields of the {term_data} table. The following part of the function will never be executed:

if ($row['pid'] > 0) {
  $term = term_parent($row['pid']);
  $row['classid'] = $term['tid'] . '^' . $row['classid'];
  $row['classname'] = $term['name'] . '^' . $row['name'];
}

The {term_hierarchy} table define a parent field, which is the ID of the parent taxonomy term, but the reported code is not making a join between the tables, and it could not find the ID of the parent taxonomy term, which then is not stored in the pid field.


Cannot update modules with drush – needs higher bootstrap level As stated in this answer Drush needs to find the settings.php file in order to work. My problem is that the settings.php file is indeed in the right folder (and I have navigated to the Drupal root folder before issuing the Drush commands), but it still does not work to update modules with drush. I just get the message that Command pm-update needs a higher bootstrap level to run. It even states itself that the Drupal settings file is located in sites/default/settings.php.

This is the error message:

C:\wamp\www>drush ups
Command pm-updatestatus needs a higher bootstrap level to run - you      [error] will need to invoke drush from a more functional Drupal environment
to run this command.
The drush command 'ups' could not be executed.                           [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

I have also followed the instructions in this post, with no luck.

What else can I try?

Finally I found an answer that I could adapt to my WAMP environment here. I simply added C:\wamp\bin\mysql\mysql5.7.14\bin to the PATH, and then Drush worked also for updates.


Block Regions in node.html.twig How can i use block regions in my node.html.twig in drupal 8 ?

i tried this :

block_get_blocks_by_region

but function not found

Fixed by adding this function to my theme

function YOURTHEME_preprocess_node(&$variables) {

$block = \Drupal\block\Entity\Block::load('views_block__sidebar_meetings_group_page');
$variables['block_output'] = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);

}

thanks @ivan jaros and @berdir


How can i load a table on changing a select option using AHAH callback I have drop down in a form as follows and i want to load a table of data using the drop down value , here is i have tried ,

function list_user_form(){
     $form['howmany'] = array(
    '#title' => t('List all the users in a group'),
    '#type' => 'select',
    '#options' => select_usergroup_dropdown_options(),
    '#default_value' => $default,
    '#ahah' => array(
      'path' => 'mailusers/listuserstable',
      'effect' => 'fade',
    ),

  );
   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );
   return $form;
}

function listuserstable(){
//make html for the table and rendering it
}

But unfortunately it gives me 403 error , please help

Try to add some wrapper to your table:

function list_user_form(){
   $form['howmany'] = array(
      '#title' => t('List all the users in a group'),
      '#type' => 'select',
      '#options' => select_usergroup_dropdown_options(),
      '#default_value' => $default,
      '#ahah' => array(
         'path' => 'mailusers/listuserstable',
         'effect' => 'fade',
         'wrapper' => 'mytable'
      )
   );

   $form['mytable'] = array(
      '#title' => t("Generated table"),
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',
      '#description' => t('This is where we get automatically generated table')
   );

   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Click Me')
   );
   return $form;
}

function listuserstable(){
   // make html for the table and rendering it
}


How do I create and render a custom region? How do I create and render a custom region in Drupal 7, when the Display Suite module is used?
I am not able to show/display a block into a custom region and  confused with the files structure. Please suggest any solution.

I got the solution and so sharing with all, if it could help someone:

Creating a custom region in our theme if we are using display suite module is slightly different.

1.First define region in your theme's .info file (same as we do without display suite)

regions[name_of_region] = 'Name of Region'

2.Then print the following line in your template file wherever you want to display

print render(block_get_blocks_by_region('name_of_region'));


Putting new configuration files in module hook_update_N upgrade? If I release a new version of a module, and want to include new configuration in the new version (particularly new fields, and updates to views to rely on those fields) by either making Drupal update the config.whatever.yml files, or writing something in hook_update_N() that will install them, how could I do it?  I would want to make sure it only installs the new fields if they don't already exist, since I would want to include the fields' yaml files.

Or, should I require features and use that for adding new fields?

It's confusing to me, because I want to include a config.yml that has the most recent config information, right?  Yet, I want to update anyone already using the module by installing the new fields that they don't have.

EDIT 2:

Okay, no, never mind. Don't use the below code.  I thought it worked, but really the fields were just installed via the yml files when I installed the module.  I don't know why I didn't realize that would happen.  My update function never really ran.  When I retried it the correct way, it failed, because FieldConfigStorage can't be loaded in this way.  I still don't know how to install fields in a way that will create the tables.

EDIT:

The code resulting from Berdir's example:

// Don't forget to include a use-statement if you haven't already:
use Symfony\Component\Yaml\Yaml;

function some_module_update_8101() {
  $message = "";
  if ( !FieldConfig::load('example_field') ){
    $config_path = drupal_get_path('module', 'some_module') . '/config/install/field.field.node.some_node_type.field_example_field.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.field.node.some_node_type.field_example_field')->setData($data)->save(TRUE);
    $message .= "FieldConfig installed for module some_module.\n";
  }
  else {
    $message .= "It didn't work!\n";
  }
  if( !FieldConfigStorage::load('example_field') ){
    $config_path = drupal_get_path('module', 'some_module') . '/config/install/field.storage.node.field_example_field.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.storage.node.field_example_field')->setData($data)->save(TRUE);
    $message .= "FieldConfigStorage installed for module some_module.\n";
  }
  else{
    $message .= "That didn't work either!\n";
  }
  return $message;
}

You can parse and load the yaml file yourself, something like redirect_update_8003:

use Symfony\Component\Yaml\Yaml;

/**
 * Creates the new default redirect view.
 */
function redirect_update_8103() {
  $message = NULL;

  // Only create if the redirect view doesn't exist and views is enabled.
  if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('redirect')) {
    $config_path = drupal_get_path('module', 'redirect') . '/config/install/views.view.redirect.yml';
    $data = Yaml::parseFile($config_path);
    \Drupal::configFactory()->getEditable('views.view.redirect')->setData($data)->save(TRUE);
    $message = 'The new redirect view has been created.';
  }
  else {
    $message = 'Not creating a redirect view since it already exists.';
  }
  return $message;
}


Implementing redirection on node viewing without affecting solr search indexing My logic demands that for a specific content type provided a node (Ex) node/123 has one if its CCK field named web link with a URL value like http://someothersite.com in it, viewing the given node mysite/node/123 should redirect to the respective URL http://someothersite.com given in that field.

I've implemented this with a custom module's hook_nodeapi view case to check the value of the field and perform the redirect. However doing so has inadvertently affected my apachesolr search indexing which invokes the hook on view condition (through node_build_content) to generate the node for being indexed.

This has forced me to currently skip such specific nodes from not being indexed, however I wish to know if there's a better way of programatically implementing the aforementioned redirect without hook_nodeapi to keep the sanity of search indexing intact.

How about doing this in hook_init() instead, eg, something along the lines of...

function YOURMODULE_hook_init() {

   $mgo=menu_get_object();

   if (!empty($mgo->type) && $mgo->type=='THE_TYPE_YOU_ARE_LOOKING_FOR') {

      if (!arg(2)) { // eg so we ignore node/###/edit etc
        if (!empty($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value'])) {
          drupal_goto($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value']);
        }
      }
   }

}

Caveat:  I've never used apachesolr, so you may need to wrap this with further logic to make sure you are running when a user actually goes to the page, eg, arg(0)=='node' and is_numeric(arg(1)) kinda stuff.

ADDITION:

You might be able to just check args inside nodeapi() as well, eg:

if (arg(0)=='node' && is_numeric(arg(1)) && !arg(2)) {
  // do your magic
}


How to clear the a block cache programmically I have a custom block that display some information from a custom configuration form.  I want the block to be cached, however, I want the block cache to be cleared every time I save the form.
I would like to do this in the submitForm function.  How do I go about and do this?

When displaying information from a config object add it also as cache dependency to the render array.
For example in a preprocess hook:
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');
  $variables['some_field'] = [
    '#markup' => $config_value,
  ];
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);

See How to clear cache for config entity after making changes?
You don't need to change form submit because saving a config object automatically invalidates cache entries having this cache dependency (cache tag).

Another example based on the block code from your answer and using a different method to add the cache tag:
  /**
   * Config settings.
   *
   * @var string
   */
  const SETTINGS = 'uw_cbl_special_alert.settings';
  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = \Drupal::config(static::SETTINGS);
    return [
      '#markup' => $config->get('message'),
      '#cache' => [
        'tags' => $config->getCacheTags(),
      ],
    ];
  }

Access caching
As asked in the comments, you can add cache dependencies to access results as well:
AccessResult::allowed()->addCacheableDependency($config)
AccessResult::forbidden()->addCacheableDependency($config)


Content moderation - workflows / weird behavior I have set a content moderation workflows for my content type : Draft and Published states.
Pretty basic, i create a content in Draft which is not published, i can change the moderation_state to Published to published it.
But when i do the following workflows : Draft -> Published -> Draft again, the content is still published. Is it a normal behavior ?
My core version is 8.8.3.

What I did was create a new state called Needs Review to mimic draft state at /admin/config/workflow/workflows.

The one thing to note is to check default revision. Then set the permissions and you should be able to go from publish to unpublish.

After the change here is what your configuration should look like.


Embed view and set filter from CCK field I created a view with 3 filters. I embedded the view in my tpl.php file for the content type. My question is, how can I set some filter with the value from a CCK field?

This is the code I use:

$view = views_get_view('view_name');
$view->set_display('default');
$view->filters[2]['value'] = $node->field_name[0]['value'];
if (!empty($view)) {
    print $view->execute_display($display_id , $view_args);
}

You should use arguments instead of filters on your view. That way you can use views_embed_view.

Just add an argument to the view with the same field you would use as a filter. That adds a where condition to the views query in a similar way as a filter would do.

Then pass on the CCK field value as the third argument on your template file like this:

print views_embed_view('view_name', 'default', $node->field_name[0]['value']);