How do you format the exposed filter options? I am guessing this is a easy question, but I am stumped for a couple of hours.
I am using Views with some exposed filters as shown below.

Search keyword
Drawing Type
Type of Mould
Customer Name

They are all in one line where "Customer Name" and the "apply" button are wrapped onto the next line.
How do I make "Search keywords" in one line, then "Drawing Type" + "Type of Mould" + "Customer Name" on another line, and "Apply" button alone on the last line?

Views 3 for Drupal 7 kindly gives each exposed widget DIV a class with a unique name. Then it's a matter of adding clear and float attributes.

If you're using Views 2 you will have to override the views-exposed-form.tpl.php file in the views/theme folder. You can just copy and save this code in a file called views-exposed-form.tpl.php in your theme file path. It should override the original template file.

<?php
// $Id: views-exposed-form.tpl.php,v 1.4.4.1 2009/11/18 20:37:58 merlinofchaos Exp $
/**
 * @file views-exposed-form.tpl.php
 *
 * This template handles the layout of the views exposed filter form.
 *
 * Variables available:
 * - $widgets: An array of exposed form widgets. Each widget contains:
 * - $widget->label: The visible label to print. May be optional.
 * - $widget->operator: The operator for the widget. May be optional.
 * - $widget->widget: The widget itself.
 * - $button: The submit button for the form.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($q)): ?>
  <?php
    // This ensures that, if clean URLs are off, the 'q' is added first so that
    // it shows up first in the URL.
    print $q;
  ?>
<?php endif; ?>

    <?php foreach($widgets as $id => $widget): ?>
      <div class="views-exposed-widget views-widget-<?php print $id ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>

      <?php print $button ?>


Create multiple custom node add pages I'm using Display Suite to create custom multiple layouts for content. Is it possible to do something similar to the node/add/mycontent page? I want to be do show/hide and organize fields on the edit and add pages.

You can check out Field group module. It allows you organize the fields with different transitions.


How to re-upload an image but not removing it I have an image field which has 1 value limited. I need to change the uploading photos frequently, and I hope the old images will not be removed. Is it possible to achieve this?

It's not really clear what you're trying to achieve, but basically there are two ways to go:

Don't use an image field, but use an "entity relation" to a media entity instead. (Media is a core module >= Drupal 8.4, or a contrib module <= Drupal 8.3)
User revisions: Create a new revision of your node every time you update the image field. You then can view older versions of the image in the version history of your page.


How add a function in a condition method in db api I am strugginling to find out how to execute the below query using drupal's db api
$startdate = '1491001200';
$enddate = '1498690799';
"SELECT * FROM field_data_field_symposium_event_time
    WHERE UNIX_TIMESTAMP(field_symposium_event_time_value) BETWEEN
    $startdate AND $enddate;"

I have tried adding 'addExpression' but does not work. I did it like this
$query = db_select('node','n');
$query->join('field_data_field_symposium_event_time', 'et', 'et.entity_id = n.nid');
$query->condition('et.field_data_field_symposium_event_time_value',array($day_start, $day_end), 'BETWEEN'));
$query->addExpression('UNIX_TIMESTAMP(et.field_symposium_event_time_value)');
$query->fields('et',array('field_symposium_event_time_value'));
$result = $query->execute()->fetchAll();

The $result is empty. Is there a way to achieve this  as I dont want to write the full query .

I believe the addExpression is for SELECT clause expressions

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/function/Select%3A%3AaddExpression/8.2.x

For a WHERE clause expression it should be

$query->where('UNIX_TIMESTAMP(et.field_symposium_event_time_value) BETWEEN :start AND :end', array(':start' => $day_start, ':end' => $day_end));

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21QueryConditionTrait.php/function/QueryConditionTrait%3A%3Awhere/8.2.x

And then of course remove your $query->condition(...); line.


How can I create a web form automatically when an organic group is created? I would like to automatically create a webform when a new organic group node is created.

The webform should have predefined fields and trigger an email to the group administrator or a user in the group with a predetermined role.  Alternatively it could email an address filled out in a cck field on the group content type.

I tried using og_webform but couldn't figure out how to get it to create webforms for each group.

There is probably multiple was to this.  The way I see it is a custom module.

You want to use hook_nodeapi(&$node, $op) in Drupal 6,  hook_node_insert($node) in Drupal 7.

You code would look like something like this

CUSTOM_MODULE_NAME_nodeapi(&node, $op) {
  switch ($op) {
    case 'insert':
       if ($node->type == 'group') {
         global $user;

         // Create new object.
         $node = new stdClass();

         // Set desired data and metadata as members in object.
         $node->type = 'predefine_webform_with_predefine_fields';
         $node->uid = $user->uid;
         $node->title = 'node title';
         $node->body = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...';
         //... prefill other cck fields

         // Save the node
         node_save($node);

       }
       break;
     }
   }
}

(Code should look the same for Drupal 7, minus the switch case)


Unhelpful error message When I try to upload an image to a content type that has an image field, I get this very non-specific error:

The file could not be uploaded.

I have checked that the file is within the allowed size constraints, the proper format, and has no spaces or strange characters in the name. Saving the content works fine except for that one field.

I have other fields accepting uploads and images on this and other content types and they work fine.

I have no idea how to troubleshoot this issue. Where do I begin?

That error comes from file_managed_file_save_upload() (around line 638 of the core file.module file).

Just before that error is a call to watchdog() with a much more descriptive error message:

  The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

So it looks like it might be a permissions issue (does your web server own the sites/default/files folder?)

In case you haven't come across it before you can see you "Recent log messages" at http://mysite.com/admin/reports/dblog, it's often the best place to look when the front-end messages are unclear.


How to select author/creator field of CRM-Core Contact and Activity in views? I'm building a view for CRM-Core Contact, but I can't find the author/creator field from the Add Fields list.

I have checked the database table, there IS a column uid:

  The users.uid that owns this contact; initially, this is the user that created it.

Any idea about this?

And there are no permissions like Edit own Contacts, only permissions like Edit any Contact. Is it designed on purpose?

From what I know, the permissions 'edit any contact' is designed on purpose...module maintaiers claim this allows for custom permissions to be set per your requirement.

As for author / creator field, you have to add a relationship first to your view
Try these -

CRM Core Activity: Author
Entity Reference: Participants

That should probably expose the field you are looking for.


Feeds file path to content type I’m using feed module to import csv file. and the content type includes file field. I added the external file path in the csv file (file column). but It's not working.
Mapping includes:

Target:
Attachments: (field_file): File ID
Attachments: (field_file): Desciption

Feeds item: (feeds_item): item URL
Feeds item: (feeds_item): item GUID

Title(title)

csv:
ID
file
title

How I can deal with Attachments and Feeds item in source section. What I should put in the source section for Attachments and Feeds item.

Thanks in advance

Currently only files coming from a HTTP(s) source are supported in the D8 version of Feeds. So the sources for the files need to look like this:

http://www.example.com/myfile.jpg
http://www.example.com/myfile.pdf
https://www.example.com/myfile.jpg
https://www.example.com/myfile.pdf

Adding support for local file paths is planned:
https://www.drupal.org/project/feeds/issues/2968671
See also other file target related issues:
https://www.drupal.org/project/issues/search?issue_tags=Feeds%20file%20target


Why is the fivestar rating displaying/suggesting 4 out of 5 stars when no votes have been made? When adding a node which has a fivestar field and there are no votes yet, it shows 4 out of 5 stars as "on". Is this intended/ normal?

In my preprocess_page hook:

<?php
if (isset($node->field_rating)) {
                $field = field_view_field('node', $node, 'field_rating', array('label' => 'hidden'));
                $rating = render($field);
                $vars['title_rating'] = $rating;
            }

which gets rendered like this (with no votes made yet):

            Cancel rating

            Give it 1/5

            Give it 2/5

            Give it 3/5

            Give it 4/5

            Give it 5/5

Same problem here. I've made a workaround putting a class and set "display: none" in it.


Filtered html ignores extra line breaks I'm using the Filtered HTML input format without a WYSIWYG editor.

When editing text, if I put some text onto a new line by hitting return, when I save its fine.

However if I add another line (so there is a space between the 2 lines of text) by hitting return twice, when I save this extra line disappears. How can I stop this from happening? Thanks

So I can do this:

1
2

But I can't do this:

1

2

Consider using the Markdown Filter. It not only solves your problem, but gives a more intuitive input option.

If your users are used to using Markdown on StackOverflow, then they will love it ;)
In fact, StackOverflow was one of the first sites to integrate the Markdown format.


hook_form_alter multiple Content Type How I use hook_form_alter with multiple Content Type..

function custom_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'register_node_form' || 'session_node_form'){

  if(empty($form['field_event_ref']['und'][0]['nid']['#default_value']))
     {
    $form['field_event_ref']['und'][0]['nid']['#default_value'] = arg(3);
     }
    $form['field_event_ref']['und'][0]['nid']['#disabled'] = True;
     }
  }

I want Here to Get Both Of (Register) and (Session) Content type to be alter..

The code is incorrect, it should be:

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'register_node_form' || $form_id == 'session_node_form') {
    // code here that alters forms for both content types
  }
}

The if statement is missing the second $form_id.

Also, I wouldn't name the module custom. If you are doing that as a demonstration purpose, a typical convention is to use mymodule_ in posts.

A more readable way:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $content_type_forms = array('register_node_form', 'session_node_form');

  if (in_array($form_id, $content_type_forms)) {
    // code here that alters forms for certain content types
  }
}


A module that allows user to create content anonymously, then if they register, assigns the content to them I recall a module I came across that was in dev a while back that basically allowed users to create nodes as an anonymous user. Then if they registered on the site, it assigned authorship of these nodes to that user account. Similar to how Drupal Answers works. It helps to lower the threshold for someone to get involved in a site. I just cannot recall the name.

Does anyone know?

You should use Create and Register module.

  This module creates a "lazy registration" which means that the user creates the content first and after this logs in or registers to the site.


How to change the link text in Drupal 8 Views? I have a simple problem that I can't seem to resolve despite everything I have tried. Googling for a answer has not turned up anything either. Here is my problem:

I have an entity A that references entity B. What I would like to do is be able to link to entity B's content (by that I mean click a link and be taken to the page the displays entity B's content). In Views you would use the "link to content" switch to accomplish this.

However here is the catch, I would like to use entity A's title as the link's text. I figured this would be an easy thing to do in Views, but no matter what I tried I can't do this.

I have tried rewriting the result in Views, but I can't find a reference to say that you want to link to entity B's url. Using the below substitution:

{{ entityA_title }}

you would get a link that looks like:

EntityB Title">EntityA Title

Where EntityB Title would link to Entity B's content and EntityA Title would link to a page that does not exist. It looks like you can't separate Entity B's title from its url - where I just want its url.

Is there a way to accomplish what I want to achieve? I figure this should be possible and straight forward to do, but apparently not.

Thanks.

Here's how I do this (just tested it, working):

Make sure you have a relationship to Entity B added to the view.
Potential gotcha: Make sure your Title field for Entity A is NOT a link already; you won't be able to use it as a title in a link rewrite if it is already a link.  (If you want to rewrite a title that is already a link, you can add a second title, make the second one not a link, and then use that in your rewrite.)
Add a Path field that uses the Entity B relationship.  Rewrite it like {{ entityA_title }}


To view the database field data in the admin page custom module How to show the data from the database in the admin page of custom module. The listed data should be edited/deleted/view.

Please say what Hook is to be used in the.inc file

There are plenty of ways to get your fields in a page.
You can try

Views OR Data

If you prefer some coding you could try theme_table or theme_item_list

I would do it by theme_table if i prefer coding.

  Returns HTML for a table.

Read HowTo: Create Simple Tables

<?php
  $header = array('Node ID', 'Title', 'Type', 'Terms', 'Created', 'Published', 'Sticky', 'Promoted');
  $rows = array();
  $no_yes = array('No', 'Yes');

  $results = db_query("SELECT * FROM {node} ORDER BY promote DESC, sticky DESC, created DESC");

  while ($node = db_fetch_object($results)) {
    $termlist = taxonomy_node_get_terms($node->nid);
    $terms = array();
    foreach ($termlist as $key => $value) { $terms[] = $value->name; }
    $rows[] = array($node->nid,
                    l($node->title, 'node/'. $node->nid .'/edit'),
                    $node->type,
                    implode(' | ', $terms),
                    format_date($node->created),
                    $no_yes[$node->status],
                    $no_yes[$node->sticky],
                    $no_yes[$node->promote],
                );
   }
  return theme('table', $header, $rows);
?>

To get Edit/Delete work you should write your own code if its not nodes.


How to add the placeholder in view exposed filter I am just created a block-view with exposed filter in view,, now i want to give the placeholder to auto-complete widget type same as label name , how can i do this ?

You can simply add below code to form alter hook

$form['title']['#attributes']['placeholder'] = t('Keyword search');


403 forbidden error when loading images in test server Am working with drupal7.When images are loading below error is showing in my test site console:

GET sites/default/files/styles/slideshow_full/public/plans/30989/main-image/contemporary_house_plan_westbrook_30-065_front.jpg?itok=TkUdCJQ5 403 (Forbidden)

When I paste the above URL in browser it is showing that "You are not authorised to access this page" error.

I checked all the permissions and all has 777.
But the same functionality  is working with my local site.Can anyone give me a suggestion to solve this issue?

This is a typical result of an incorrect url path.

That folder may/may not exist on the test server, but because it's outside of your user's folders, you 'don't have permission to access' it.

For example: Typical user's folders for cPanel are /home/USER/ with the site root at /home/USER/public_html. But, typical for a local machine is /var/www/....

So when you call sites/default/... from a local machine, it is possible that it's actually looking at /var/www/sites/default/.... When doing that on the test server, the path would be outside your user's folder and therefor no access permission.

It could be as simple as a missing ../ on your relative paths.
So you could try 1. adding ../ to the start of your paths and see if that takes it to the correct location.
or 2. Try explicitly setting the base url in your settings file $base_url = 'http://foobar.com'; to force a starting point for relative paths.


file upload using Webservice I am using Drupal 7 and trying to upload a file

function upload_service_menu() {
  $items = array();

  $items['api/v1/upload'] = array(
    'title' => 'File Upload Service',
    'description' => 'Upload files to public directory on this server',
    'page callback' => 'upload_service_job',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Function to get the path, download and store the file on our server.
 */
function upload_service_job() {

    $file = $_FILES;

    $validators = array();
    $file = file_save_upload($file, $validators, 'public://');
    if($file){
        echo "Sucess";
    }else {
        echo "fail";
    }
}

and my local form is

<form action="http://example.com/api/v1/upload/" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

But i am not able to upload file. Seems file_save_upload($file, $validators, 'public://'); function is not working .I checked permissions also..
Can anybody tell me what to do.

Thanks

$_FILES is

  An associative array of items uploaded to the current script via the HTTP POST method.

file_save_upload() takes as its first parameter

  A string specifying the filepath or URI of the uploaded file to save.

Your code essentially does this

$file = file_save_upload($_FILES, $validators, 'public://');

So you're currently passing an array to a function that's expecting a string.

You're probably looking for something along the lines of

$file = file_save_upload($_FILES['file']['name'], $validators, 'public://');


Drupal 7: user is following view I need to create a view of people a user is following. the default settings for user relationships only shows people following a user. i know i need to use views but i have no clue how to set it up. Any suggestions will be greatly appreciated.

I've just had a problem that took me forever on a View to do with User Relationships, on question #25294.

The screenshot of the View I was debugging and the information I put in my question should hopefully give you everything you need.

(Bear in mind that my View was getting the people following $currentuser, whereas you want the people $currentuser is following, so you'll want to reverse all the instances of requester and requestee.)

I hope this helps!


How do I use rules scheduler to disable and enable a commerce product entity based on certain date fields? I have a commerce product type (entity not display node) with two date fields (enable_date and disable_date). What are the steps to create a rule/component and use rules scheduler to schedule these to disable and enable these products, based on the value of these two fields?

The use case is that I have an event node (product display) that needs to always be viewable but the attached registration (product entity) needs to be disabled on a specific day/time. i.e. Registration is now closed, but users can still see the event info, like location, map etc. Using rules scheduler I am sure I can do this. I have tried with mixed results but I am still learning the rules module. Any help would be appreciated.

First create a Rules component for setting the status of a product.

Go to Configuration -> Workflow -> Rules -> Components -> Add new component.
Create an Action set.
Give the component a suitable name, such as Set product status.
Create a parameter of type Commerce Product, label Product, machine name product; and another of type Truth value, label Status, machine name status.
Add action: Set a data value
For Data, use the Data selector to select the product parameter's status (product:status).
For Value, use the Data selector to to select the status parameter (status).
Save

You now have a component that can be scheduled. Next you need to trigger the creation of the scheduled action. I'm going to describe the process for enabling the product; you should be able to create another rule for disabling easily enough following the same method.

Go to Configuration -> Workflow -> Rules -> Add new rule
Choose the triggers After saving a new commerce product and After updating an existing commerce product.
Add the condition Entity has field.
For Entity, use the Data selector to choose commerce-product as the entity.
For Field, use the dropdown to select your start date field.
Add condition Data value is empty.
For Data to check, use the Data selector to choose the start date field.
Check the Negate checkbox (we only want to proceed if the field is not empty)
Add another condition Data comparison and select the start date field is greater than site:current-date
Add an action Schedule component evaluation.
For Component, choose the component you created earlier.
For Scheduled evaluation date, use the Data selector to get the start date.
For Identifier, choose something like Enable product [commerce-product:product-id]
For Status check the box.
For Product use the Data selector to choose commerce-product.

Then in order to remove a scheduled action if the date's removed from the field:

Follow steps 1-7 (but not 8!) immediately above to create a new rule.
Add an action Delete scheduled tasks.
For Component, choose the component you created earlier.
For Identifer, use the same string you used before.

And another rule to delete the scheduled action when the product's deleted would be good too.

I quickly gave that a go and it seems to work for me. Let me know if you have any problems.


Is there any technical reason why we now should put third-party modules in the [docroot]/modules folder? Is there any technical reason why we now should put third-party modules in the [docroot]/modules folder? It seems like an odd inconsistency that common third-party modules go there, while multisite-specific modules go in the traditional /sites/[site]/modules folder. It appears that creating a sites/all/modules folder still works.

Technical? Not really, it isn't faster or anything like that.

It's basically about Developer/User Experience. It's 2 clicks less to go there and find a module.

Also, there multiple issues to either drop multisite entirely (although most people disagree with that) or not exposing it by default and just have a settings/settings.php by default.

Move settings.php to /settings directory, fold sites.php into settings.php
Discuss whether to deprecate multisite for removal in 9.x


How can I add arbitrary placeholder text to form fields? I'm converting an existing site (built by someone else) from Drupal 7 to Drupal 8.

The old site uses the Field Placeholder module to add placeholders to form fields. However, there isn't yet a Drupal 8 version of this module.

I came across the Form Placeholder module, which does have a Drupal 8 version – but it won't work for my case. (Most significantly, it only allows you to use the field label as the placeholder – you can't enter an arbitrary placeholder that's different from the label.)

Is there another option I can consider?

(I'm aware that I could hack something together with jQuery. For various reasons, I'd prefer not to do that.)

It seems that this functionality is now in the Drupal core – placeholders can be added from the widget settings on the content type's form display page.


Placing user login and user menu at the bottom right when this is not supported by the theme I'm new at Drupal and am building a site with the Bootstrap theme, and i would like to place the user login and user menu in the lower right corner. Unfortunately there is no region for that, there is just the footer region which covers the whole width of the screen

What is the best way for me to add the user login and user menu to this area?

This would have been a problem if i just wanted to place the user login and user menu below, because when setting contents of the blocks they are placed vertically on top of each other. But in my case this wouldn't look good, i would need the stacking to be done horizontally instead of vertically

I can think of two different approaches:

Modifying the bootstrap theme so that there is a region in the lower right
Modifying the code of the footer to include the content of the "user login" and "user menu" blocks (maybe using this as a guide)
Maybe using the panels module?
Somehow getting the stacking to be done horizontally rather than vertically

Which of these would you recommend? Are there other approaches that are better?

It's important that the site is easy to maintain long-term and that we can continue to use the auto-update for the bootstrap theme

Grateful for any suggestions!

Never directly use the Bootstrap theme, create a subtheme from one of the starterkits inside your theme folder (they have readme files inside the starterkits with more info and relevant links depending on which method you prefer to use), and do all your work in the subtheme. This way you can auto-update the bootstrap theme, without loosing all your customisations.

Next step would be to create your own region (for example Footer right) in the info file of your subtheme:

;;;;;;;;;;;;;;;;;;;;;
;; Regions
;;;;;;;;;;;;;;;;;;;;;

regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'

regions[footer_right]   = 'Footer right'

regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

Next create the region in your page.tmpl.php file. You should override the one used in the Bootstrap theme, with a duplicate you make in your subtheme: YOUR_SUBTHEME/templates/system/page.tpl.php. (Copy the file you have in YOUR_SUBTHEME/bootstrap/system/page.tpl.php)

Go to the footer section in this page.tpl.php file, it should look somewhat like this:

<?php if (!empty($page['footer'])): ?>
  <footer class="footer <?php print $container_class; ?>">

    <?php print render($page['footer']); ?>

<?php endif; ?>

And add your new region where you would like it to go (for instance like this), and use the Bootstrap markup to align your content to the right:

<?php if (!empty($page['footer'])): ?>
  <footer class="footer <?php print $container_class; ?>">

   <?php if (!empty($page['footer_right'])): ?>

      <?php print render($page['footer_right']); ?>

   <?php endif; ?>

    <?php print render($page['footer']); ?>

<?php endif; ?>

Make sure to clear your sites cache when you're doing changes to template files like these. If all is fine, your new region should appear in "structure > blocks", and you should be able to add your login blocks to it.


Given that db_select is much slower than db_query, why would I want to use it? For the background on this, please see http://drupal.org/node/1067802.

Given all that, what situations exists where I might want to use db_select(), or should I be relying solely on db_query?

There are 5 reasons to use SelectQuery

You are building dynamic queries with a varying number of conditions, joins, fields and so on. See field_read_fields() for an example.
You want to use so called Extenders. Example extenders are PagerDefault (replaces pager_query()) and TableSort (replaces tablesort_sql()). These allow to add additionally functionality to SelectQuery. See also How do you make sortable tables with a pager with data from a custom table?. An example: node_page_default().
You want to allow other modules to alter your queries. Then you can add so called tags and SelectQuery will automatically call a corresponding alter hook for that tag. I'm am heavily relying on this with my Privatemsg module (We already did that in D6 with a custom query builder).
If you want/need to use the node_access system to only show nodes the user is allowed to see. Just add the 'node_access' tag to your $query. This replaces db_rewrite_sql().
SelectQuery has a few features that help to make your code work the same across all supported databases. For example there is SelectQuery::orderRandom(). And if you have a LIKE condition, ->condition('field', $value, 'LIKE') will make sure that it is always a case insensitive comparison. In D6, you had to use LOWER() for that which was much slower. But AFAIK, there aren't more than this two right now.

If none of these reasons apply for a specific case, use db_query().


How to export a menu and blocks? I created a Superfish menu in a test installation of Drupal (8.5.4) and want to import it into another install (8.5.5).  How can I do this?

Is the navigation data stored in menu_link, menu_link_content, and menu_tree?  I tried importing these tables into my new install, but when I try to "Place Block" in Block Layout - I don't see the old menu showing up as a Superfish block.

I also tried using the Menu Export module. But was unable to find the "Menu Export Configuration" page that they show in the image.

The new install is migrated from Drupal 7. So it lacks a config table.  Where is the config installed?  I think I need to copy the menu which is stored in a blob in the config table, but I don't know where to put it.

Note: The main question is "How can I export the menu"? To which the answer appears to be "Not possible." I'm still confused though as the menu information has to be stored somewhere. The other sub-questions are trying to get at pieces of the puzzle.

Both menu link items and custom block content are treated as content within Drupal core. That's to say, they aren't covered by the configuration management system.

In instances where it make sense to have menu link items or custom block content stored in the configuration system, there are modules out there to assist with this:

Fixed block content: Provides a way of having permanent custom content blocks without broken instances if the block does not exist.
Config menu link: A drop-in replacement for core's Custom Menu Links module.

There many other options to store menu/block data into the config system so it's worth your time to explore other options to find the one that best matches your scenario (especially since Superfish seems to be a part of it).


How to limit a user to one vote when using Rate module? In Drupal 7, I have installed the Rate module for voting. But here, the user can change his vote anytime he wants.

If I want to restrict an user to vote for a particular node only once, what I have to do?

I don't remember this feature in Rate. I don't know the module well enough to know if you can set that user can vote only once per node, but you can just alter the render. You should probably go for a custom module and implements HOOK_preprocess_HOOK.

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_preprocess_rate_widget(&$vars) {
global $user;
// if user have voted
// then alter the render
// else nervermind
}

Hope that help.


show a form in a popup when a button is pressed I am creating  a registration form it has multiple stages. I am able to redirect to another page with the help of a link.
How can i get the form as a popup with a button.

 $form['adding_disease']=array(
   '#markup'=> ''.t('disease_list').'',
 );

Here this snippet is written in a form with many other fields.
this link is in the middle of the form.

Another solution is to use Ctools Automodal module. This approach is less complicated to @Web-Beest answer.

Here is the example on how to use it.

function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE,
  );
}

The most important line in the above code is 'modal' => TRUE,.


How do I add fields to the email field contact form? Using Drupal 7, I have a content type that uses the email field module(CCK) so that the page author can enter an email address for readers to mail them. With display suite module together with views contact form module, the saved page displays the site wide contact form. The emailed responses are delivered to the email address that was entered by the content author. That works great.

I wanted to add extra fields and managed to do this with the code below which I  added to the template.php file but the code only works with the site wide contact form on example.com/contact

My question: How can I add those fields to the email field module's contact form as well?

This is the code I'm using to include the fields in the contact form display:

function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
if( $form_id == 'contact_site_form' ){
    $form['message']['#weight'] = 6;
    $form['copy']['#weight']    = 7;
    $form['phone'] = array(
        '#type' => 'textfield',
        '#title' => t('Phone'),
        '#required' => TRUE,
        '#weight' => 4
    );
    $form['province'] = array(
        '#type' => 'textfield',
        '#title' => t('Province'),
        '#required' => TRUE,
        '#weight' => 5
    );
}
}

This is the code I'm using to include the field responses in the email that gets delivered:

function MYTHEME_mail_alter(&$message) {
if ($message['id'] == 'contact_page_mail' ||
$message['id'] == 'contact_page_autoreply') {
$message['body'][2] = t('My Phone Number') . ': "' . $message['params'][phone'] . '"';
$message['body'][3] = t('My Province') . ': "' . $message['params']    ['province'] . '"';
}
}

You'll need to replace email_mail_page_form_submit with your own submit handler, because the Email module doesn't add extra form items to params automatically.

Firstly, copy the code from the function email_mail_page_form_submit in email.module and add phone and province to the params:

function MYMODULE_email_mail_page_form_submit($form, &$form_state) {
    // ...

    $params['object'] = $object;
    $params['subject'] = $form_state['values']['subject'];
    $params['name'] = $form_state['values']['name'];
    $params['message'] = $form_state['values']['message'];
    // Add your extra params
    $params['phone'] = $form_state['values']['phone'];
    $params['province'] = $form_state['values']['province'];

    // ...
}

Secondly, replace the submit handler on the form:

function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
    // contact form alterations
    // ...

    // email page form alterations
    if ($form_id == 'email_mail_page_form') {
        // add your phone and province fields
        // ...

        // override the email module's submit handler
        $form['submit']['#submit'] = array('MYTHEME_email_mail_page_form_submit');
    }
}

Then you can add them to the message as needed in HOOK_mail_alter.


How to restrict node view to users by registration date? In short I'm trying to find a solution to:

Restrict view access to certain custom node types by the date the
user registered
The user would be able to see restricted content created in
the month they registered and any future month while their user
account is active, but nothing before the date the account was created
There is existing content restrictions and
functionality for the same users on the same content. Only certain
roles can see selected node types and this is selected when the user
is created (manually). This is managed by
https://www.drupal.org/project/nodeaccess

This website has restricted content that only members (registered users) can see.

These fall into several categories and the content is divided into these categories too.  Depending on the type of member and what you been given access too, you will only be able to see that content. This is managed by Node Access and works well and as intended.

A new requirement has now popped up after the fact where this content access should be further restricted. It should honour the previously mentioned restrictions managed by nodeaccess but now apply additional parameters.  All these are relevant to the month in which the user's account is created:

Restricted content posted before must not be available
Restricted content posted after must be available (and future
content too, but still honouring the nodeaccess restrictions)

I'm fairly capable with Drupal dev, but cannot write code or rules which I think this requirement is leaning towards.

Anyone got any suggestion that will work or can perhaps point me in the right direction to get a start?

You need use this hook https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7

So in your module you need code smth like this

function YUORMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($op == 'view') {
    global $user; // get current user
    // check user register date
    if ($user->created < $node->created) {
      return NODE_ACCESS_DENY;
    }
  }

// Returning nothing from this function would have the same effect.
  return NODE_ACCESS_IGNORE;
}


Any suggestions for Taxonomy scaling and performance with 1073 terms? I manage a website where the owner categorizes everything via taxonomy. However, he's extremely detailed when it comes to categorizing things. He has 1073 taxonomy terms, about 1000 of which are in one single vocabulary. The node edit screen takes 10-15 seconds to load!

I've told him he needs to consolidate but he's not going to.

Does anybody have any advice for performance tuning? Changing to the ajax autocomplete control isn't an option because he needs to be able to see the hierarchy.

1000 terms is not so bad, really. I am inclined to believe the number of terms in your vocabulary is not what has the most impact on response time, as MySQL can handle much larger datasets out of the box.  One factor to consider is the hierarchy of your taxonomy, or the number of levels it has. A vocabulary with 3-level-deep hierarchy will be much slower than a vocabulary that is implemented as flat hierarchy.

Good-luck


Calculate Star rating based on webform submissions Is there a module to calculate Average Vote based on webform submissions?

Explanations:

I have a Webform which looks like this. So when a user submits the form i need a average value to be calculated which i can show as star rating some where on another page.

Does it need a custom module ?

Any clues ?
thanks

Yes. You should create a fivestar field in your webform and than create a custom module which calculate the rating and save it to a fivestar field.


Presenting a menu within page content with associated descriptions and images Currently, I have a drupal project where I have two levels of menus. (So for example, the top menu has "home" "about us" "faq" etc.) each top level menu has a secondary menu.

I'm trying to create a node for each top level menu item that is an 'overview' of that category. One of the things that I'd like to do on each overview page is provide an expanded version of that secondary menu in the content area, where instead of just having links, we would also have a description and an image associated with each menu item. (So on the "About Us" page, there would be a link to the "About Us-> History" page, and this link would have an icon and a description). Ideally, I'd like to lay these out as a set of horizontally spaced squares below the content area.

Currently, I'm managing this by creating a custom block for each link/image/description combination, and using Context to toggle the appropriate blocks on and off, but this seems really inefficient and error prone. Can someone recommend a 'correct' way to do this?

I'm not positive I entirely understand what you envision, but one possibility might be to use the Menu Trails Module to handle the submenu.

For the section of blocks you are currently toggling on and off contextually, I might consider instead authoring a block in Views that is queried off a default argument passed through the url.  This argument would be the same value from the Main Menu which is configuring the Menu Trails and could be configured to display the node teaser (or a cck/field value called Overview) for the active Main Menu Item.

Or what you may be describing is something more like a list of submenu items as teasers,:

[Some Photo] | [Some Photo] | [Some Photo]
[Menu Title] | [Menu Title] | [Menu Title]
 [Overview]  |  [Overview]  |  [Overview]

In that case, I'd still use Menus to organize the content hierarchy, but don't check expand in the menu options.  Instead, use the method described above to construct a block in Views that displays all the submenu items. You won't need Menu Trails for this type of display.


How can I use Rules to publish nodes depending on changing the value in a Field? I would like to set up rule to detect if I change one specific field in the content type.  For example if I choose the field "dyzury", then the rule will publish this node to the front page with the new value in the field.

How can I achieve this?

Set the rule to fire on the event Before saving content so you will have both values of the field available.

Set the conditions as follows:

Node is of type and select your content type.
AND Entity is new. Your data selector should be Node and negate the condition (NOT new)
AND Entity has field, Again your data selector should be Node and select your field_dyzury from the drop-down list to make the field available to the rule.
AND Data comparision and using data selectors for both values choose [node-unchanged:field-dyzury] and [node:field-dyzury]. Select the Equals operator and negate the condition (NOT equal)

It is important to detect that the node is not new, or there will be no existing data value for the comparison.

Then set the Action to Promote content to front page. Again, data selector should be Node.

This rule will detect any change in field_dyzury, and will promote the content to the front page when a change is detected.

Edit:

The conditions should look like:

+ Content is of Type
+ AND
    + NOT Entity is new
+ AND
    + Entity has field
+ AND
    + NOT Data comparison

The AND's force the rule to require ALL of the conditions to evaluate to true before the actions are performed.


How to print the Views title in page.tpl.php? I could print the view with this code in page.tpl.php.

print $view->display['view_display_name']->display_options['title'];

How can I print the Views title ?

You can aptly use this function views_embed_view(). This will help you to print out the view, passing arguments.


Keep less files of Bootstrap in productions site after compiling? i'm new to Bootstrap, Drupal and Subthemeing so maybe this question is a bit noob. ;-)
I did a Subtheme for Bootstrap 3-Base-Theme with the local bootstrap-files etc. Makes completely sense for developing. But when i'm finished with editing and compiled my styles.css it doesn't make sense to upload also the less-files to my webserver as they are no longer needed, are they? (I just keep them local for developement)

I'm not so sure about the js files, those are still referenced at the info-file.
But i keep thinking that one could drop the less-folder - do you agree?

Technically you will not need the less files on your production unless you need to Drupal to modify your theme. For instance, if you are integrating the color module that with your theme to allow administrators user to change the colors of the theme using the color module. You need the less files and you need to use less module. Otherwise you don't need them less files on your production site.


Modifying integer field to decimal gives error when editing field information I have implemented php code to update a field from integer to decimal. However when trying to modify the field name from UI, it gives error:

Attempt to update field Maximum Temperature failed: field_sql_storage cannot change the schema for an existing field with data.

The system behaves well when editing existing field data or creating a new one.

Please find the code executed via hook_update_N() below:

/**
* Modify the integer field of nursing notes temperature field
* to decimal field with precision and scale
*/
function ji_custom_update_7001() {

  // Manual database changes.
  db_query("UPDATE {field_config} SET type = 'number_decimal'
      WHERE field_name = 'field_nursing_note_max_temp'");

  $new_field = array(
    'type' => 'numeric',
    'precision' => 10,
    'scale' => 2,
    'not null' => FALSE,
  );

  db_change_field('field_data_field_nursing_note_max_temp', 'field_nursing_note_max_temp_value'
    , 'field_nursing_note_max_temp_value', $new_field);

  db_change_field('field_revision_field_nursing_note_max_temp', 'field_nursing_note_max_temp_value'
    , 'field_nursing_note_max_temp_value', $new_field);

  // Clear caches.
  field_cache_clear(TRUE);
}

If the only tables that you have updated are field_config, field_data_field_nursing_note_max_temp and field_revision_field_nursing_note_max_temp then you missed one: field_config_instance.

Without being able to explain in detail how your manual mingling with the database produces the error, I'll try to outline what I understand.

The error you're seeing is produced in field_sql_storage_field_update_forbid. This is a hook implementation that is called by the Field CRUD API in order to give modules the chance to object the updating of a field:

// See if any module forbids the update by throwing an exception.
foreach (module_implements('field_update_forbid') as $module) {
  $function = $module . '_field_update_forbid';
  $function($field, $prior_field, $has_data);
}

The hook function receives three argumentes, the first is the current field definition coming from the field settings form, the second is the prior field defintion which is read from the field_config_instance table:

$prior_field = field_read_field($field['field_name']);

I assume that those two arrays differ and produce the error that you are encountering.

So I'd say, welcome to field hell! It's in general not advisable to mingle directly with the fields underlying table structure and column definitions. If you need to change a field, it might be a lot better to create a temporary field and migrate the data using API functions in batch scripts for example. That sounds like more work in the first place, but it will spare you these kinds of inconsistencies.


Using SQL to output link to a node Does anyone know - using SQL only - how to output the link to a drupal node?

If I was using PHP I think it would be something like this:

print l($node->title, 'node/' . $node->nid);

But I'm not using PHP, I need to use SQL only because the report module I'm using requires it.

It's in url_alias table, you'll need concatenate it with your domain name.

SELECT `alias`  FROM `url_alias` WHERE source = "node/XXX";

Note: if you have more than one alias it will return multiple results.


How do you remove product from shopping cart? I have three product variations: Postpaid, Prepaid, and Accessories. I can't seem to figure out why when I add a product with the Accessories product variation, I'm unable to remove it from the Shopping Cart. However with the Postpaid and Prepaid product variation I am able to. Also, previously someone took care of the store, and I can't get support anymore.

I double checked the workflow Rules, and can't seem to find the options. I know it's not a view issue, because it shows the remove link with the Postpaid product variation.

My only work around is to add a new product through the Postpaid and Prepaid product variation, but I don't really want to do this because it's messy.

Please see screenshot below.

If that button is missing for some reason on just a specific product type, then it's more than likely the result of custom form altering in a module file on your site. I'm not aware of any Views configuration that could remove that button just for products of a certain type. Just in case, you can check your shopping cart form View's configuration for the line item delete button to see if any advanced settings are somehow hiding it conditionally.

My hunch is on custom code, though.


How to share only a particular link in a node using social media,instead of complete node? Using user referral module i was able to generate referral link.
After this i enabled social media module in order to share the particular link to other people whom i would be referring.

While testing this,i came to know that instead of link,entire node is being shared.

Can anyone tell me  an idea as how to share only the link,apart from getting the entire node being shared

If you're open to using an alternative module (instead of the Social Media module), you can get this to work for at least Facebook and Twitter by using the Rules module instead, combined with these modules:

Facebook rules (for Facebook, of course ...).
Twitter (for Twitter, of course ...).

For (way) more details on that, refer to my answer to "How to post the node link in social networking if node is published?", which also explains what the options are (that I'm aware of) for Google+.


How can I change the display settings of the referenced field, programatically? A paragraph entity references a media image field, and it needs to change its display options in code.

How can I achieve this?

One option is to alter the build array using entity_view.  You could then add conditional code there, to change image display settings.

/**
 * Implements hook_entity_view().
 *
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityType()->id() == 'paragraph' && $entity->bundle() == 'my_paragraph_type') {
    if (!empty($build['field_image'][0])) {
      // $build['field_image'] =
       // make changes to your image field here
    }
}


Custom content type on registration form. No node title field I set my custom content type to show on user registration form. I see cck fields, but I don't see node title field (required field) :(

Could somebody give any advice?

Do you need title or you want it because form gives you error? Maybe Automatic Nodetitles (http://drupal.org/project/auto_nodetitle) can help you? You can use that to have node automatic title like "Profile of [Name] [Surname]" and title will not be required field.


To suppress this error, add the option --strict=0 Drush My custom Drush commands use options(--ver,--env,etc). Whenever the option is used, I get message:

Unknown option: --ver.  See `drush help build-asset` for available options. To suppress this error, add the option --strict=0.

By adding --strict=0, it will suppress the message, however. how to make the custom Drush commands run with --strict=0 automatically or what needs to be done to avoid this all together. Thank you for helping

There's enough situations where I need to do that that I have just defined an alias in my startup file.

alias drush='drush --strict=0'

This is in my .zshrc file (or put in your .bashrc file if using bash).


Restriction on specific content types for admin content page filter I need help with removing a content type from admin/content page's content type filter in D8.

Let's say I have content type1, content type2 and content type3.

I want to have an exposed filter in admin/content page for content type1 and content type3.

Thanks in advance.

Just go to the /admin/structure/views/view/content and edit the
Content: Content type (exposed) filter in the "Filter Criteria Tab" of your view.

Then just select  your type1 and type 2.


How do I programmatically update a UUID? Reason: Receiving uid does not exist error. Upon investigating, this error appears only when we edit or save the preexisting columns paragraph. If we create new columns paragraph, the error doesn't appear as the uuid is different for the newly created columns paragraph.

This is the reason to update the uuid for a paragraph that is referenced on that page. In my custom module I have loaded all nodes using entity query below and loaded the referenced paragraph.

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'page')
  ->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  foreach ($nodes as $n) {
   //Relevant apragraph for the content type
   $para = $n->get('field_page_content')->getValue();
   $para_2 = $n->get('field_banner_image')->getValue();

   foreach($para as $e){
     $p = \Drupal\paragraphs\Entity\Paragraph::load($e['target_id']);

    if($p->bundle() == "columns"){
      kint($p,'Paragraph Entity');
      kint($p->uuid(),'Paragraph UUID');

       $uuid = 'd12da227-890b-4eb7-86b1-93937e7d6d91';

       //save paragraph
       //$p->save();

    }
  }
}

How can I get this updated without recreating the columns paragraph as there are quite a few.

Haven't tested this but I believe this is the route to go if you must add the uuid in this manner.

$uuid = 'd12da227-890b-4eb7-86b1-93937e7d6d91';
$p->set('uuid',$uuid);
$p->save();

Let me know if that doesn't work.


Upgrade zen theme (7.x-3 to 7.x-5.5)? Presuming I have zen-7.x-3.x + a sub-theme, how do I go about uprading to zen-7.x-5.x? Perhaps using drush?

I am in awe of the people who wrote these pages:

https://www.drupal.org/node/219527
https://www.drupal.org/node/1588244

You can run
drush up zen, it will update the zen theme, but not the subtheme
Please do a backup before running this command


How can I create a bulk node creation interface? I have a request for an interface where nodes with a small amount of required fields (for example, a title, date, and a node reference) would be able to be created in bulk on one screen.

I am imagining some kind of editable table view/grid with each row representing an individual node.

What would be the best approach to implementing something like this?

The Multi Node Add module might provide what you need.


Check if teaser or full content I want to add an HTML block inside the node.html.twig file, but only in full content view.

I used the following code but it is not working.

{% if view_mode %}

{% endif %}

I would like to move this code to a Drupal 8 block to avoid editing the template file.

How can I achieve it?

check like this

{% if view_mode == "teaser" %}

{% elseif view_mode == "full" %}
  //something else
{% endif %}


How does one add a Total(s) row to Views results? After doing some research, it seems like the best way to get a Total(s) row added to a Views table is via the Views Aggregator Plus module. (Is there an easier/better way?)
As can be seen below, I'm trying to list a bunch of nodes grouped by the first column (the taxonomy term "Type"), with the second column containing the number of each.

I'd like to add an additional row to the bottom:

Total | 6

...but no matter what I try, the additional row doesn't show up in spite of what the module documentation, various videos, and blog posts are telling me.
In the view Format, I'm using "Table with aggregation options", and the settings are as can be seen here:

Under Column Aggregation, I should be able to check "Apply column function" and select Sum (I think), but this has no effect on the live preview.  I tried this on both fields (and even both together), and it made no difference.
I'd like to make the Total row part of the table, rather than a hacky solution where I calculate it in the view header or footer.  How can this be done?  What am I missing?

I'd like to make the Total row part of the table, rather than a hacky
solution where I calculate it in the view header or footer. How can
this be done?

I've never used that module, but alternatively, you could do the template file solution.
Since you want this to work in the View's preview, which uses core's admin theme and since you should never hack core, this cannot be solved via theme. Therefore, must be solved via custom module.
Example:

View ID: content
View Display ID: page_1

/mymodule/mymodule.module
/*
 * Implements template_preprocess_views_view_table()
 */
function mymodule_preprocess_views_view_table(&$variables) {
  $view = $variables['view'];
  if ($view->id() == 'content' && $view->current_display == 'page_1') {
    $variables['total_rows'] = $view->total_rows; // pass custom var to template
  }
}

/*
 * Implements hook_theme()
 */
function mymodule_theme() {
  return array(
    'views_view_table__content__page_1' => [
      'template' => 'views-view-table--content--page-1',
      'base hook' => 'view',
    ],
  );
}

/mymodule/templates/views-view-table--content--page-1.html.twig
Copy the code of views-view-table.html.twig and paste into this file and just change the last 3 lines to:
  {% endfor %}

    {{ 'Total'|t ~ ' | ' ~ total_rows }}


Add description to files uploaded by the Media file selector widget I am using D7 with media module. I have a field for (multiple) files.

Instead of the built in "file" widget for the file field, I am using the "Media file selector" widget.

In drupal core's "file" widget, I am able to select the "Enable Description field" option to label the files. I am unable to find such an option with the "media file selector"

There is a whole section to add files with many fields. But I am looking for a field with some sort of description or title option. I will use it as the link text, instead of the file name.

Is there an option somewhere that I've been missing?

Thanks.

With the file_entity module you can add fields to files.  So in your case add a "Description" field to your image file type.

When selecting how the field will be rendered, make sure to choose "Rendered file" and it display the file with the extra fields.


How can I programmatically add a field to a field group? I have tried this code but it is not working.

$form['field_test'] = [
  '#title' => t('test'),
  '#type' => 'radios',
  '#options' => [t('A'), t('B'), t('C')],
 ];
$form['#group_children']['field_test'] = 'group_1';

I also tried with

$form['#fieldgroups']['group_1']->children[] = 'field_test';

But nothing is working. It works in Drupal 7. Is it changed in Drupal 8?

I have written this code in hook_form_alter and I'm altering a node form.

You have to put both.

$form['#group_children']['field_test'] = 'group_1';
$form['#fieldgroups']['group_1']->children[] = 'field_test';


Can you make a field unique in a content type? I have an Employee content type with an ID field.

Can I make the field unique, so that Drupal would prevent me from entering the same ID more than once by mistake?

You can add a validation constraint to your field.
There is two ways to do that:

Setting a validation constraint to a field you haven't defined by implementing hook_entity_bundle_field_info_alter:

function YOURMODULE_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'ENTITY_TYPE' && $bundle === 'BUNDLE_NAME') {
    if (isset($fields['FIELD_NAME'])) {
      $fields['FIELD_NAME']->addConstraint('UniqueField');
    }
  }
}

Setting a validation constraint to a field you have defined in baseFieldDefinitions

public static function baseFieldDefinitions(EntityTypeInterface $entityType) {
 $fields['FIELD_NAME'] = BaseFieldDefinition::create('string')
   ->setLabel(t('MY UNIQUE FIELD'))
   ->addConstraint('UniqueField');

 return $fields;
}

If you want to create your own validation constraint you can check here.


Add a class to the first li.pager-item for a view pager? How can I add a class to the first li.pager-item and a different class to the last li.pager-item for for a Views pager?

I know that I need to make a theme override of theme_pager
https://api.drupal.org/api/drupal/includes!pager.inc/function/theme_pager/7

However I cant figure out what PHP to change.

If you implement theme_pager you'll be expected to create the entire pager render array from scratch using several theme function - theme_pager_first, theme_pager_previous, theme_pager_next and theme_pager_last. That seems like entirely too much work for adding one class.

Since theme_pager calls theme_item_list at the very end to build the final render array, you can use hook_preprocess_HOOK to modify the pager render array before drupal renders it into HTML.

function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
    // make sure there are items
    if (count($vars['items'])) {
      $vars['items'][0]['class'][] = 'test';
    }
  }
}

Clear the cache after adding this hook.

UPDATE: find the first li.pager-item:

function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {
    // loop the items and find the first .pager-item
    foreach ($vars['items'] as $index => $item) {
      if (in_array('pager-item', $item['class'])) {
        $vars['items'][$index]['class'][] = 'test';
        break;
      }
    }
  }
}

UPDATE2: find first and last li.pager-item:

function THEME_preprocess_item_list(&$vars) {
  // make sure we're dealing with a pager item list
  if (isset($vars['attributes']['class']) && in_array('pager', $vars['attributes']['class'])) {

    // loop the items and find the first and last .pager-item
    $first = FALSE;
    $last = NULL;
    foreach ($vars['items'] as $index => $item) {
      if (in_array('pager-item', $item['class'])) {

        // first
        if (!$first) {
          $vars['items'][$index]['class'][] = 'test';
          $first = TRUE;
        }

        // last
        $last = $index;
      }
    }

    if (!empty($last)) {
      $vars['items'][$last]['class'][] = 'test2';
    }
  }
}


Need to create a report in Drupal 7 that counts Articles by Author for date range I am trying to create a simple display that lists all my authors who provided content to my site during a date range (i.e. Jan 1 thru Dec 31) with a count of the number of articles published, as follows:

Joe Smith, 120
Bob Jones, 87
Tom Kelly, 3

While the output is fairly simple, creating it is not (at least for me). I would think this would be a fairly common reporting requirement, so I'm hoping someone has already created it somewhere. If so, I'd love to use it on my site.

Create a view by selecting users and add filter by date.


Ubercart Module for handling subscriptions? Trying to figure out the best UC module to use for this...

Essentially, I'm trying to create a site where users may purchase subscriptions.  There are about 15 different subscriptions a user may purchase.  The first subscription (regardless of which one it is) will sell at $20.  Every additional subscription purchase after that will cost $10.

Not sure which module to use (or if one even exists) to accomplish this.  There appears to be so many contributed modules, and the descriptions "kinda sorta" seem like what I need, but a lot of them sound very similar...

If someone knows a good way to accomplish this, that'd be great...

Look at UC Recurring module. It should do what you need. The instruction on how to set it up is here.


Block visibility based on the content type I have created a block for showing author details for every individual author; the article's authors can be identified by the 'Author' field.
Now I want to match the author block with the particular author's content.

For example, I have an author called 'vividvilla', and I have created a block for 'vividvilla'. How do I show this block for articles where 'vividvilla' is the author?

I know it can be done with PHP code in blocks, but I am not sure about the code.

I would use the menu_get_object() function to determine whether or not the block visibility check is being executed on a full node page, then check the field value on the node from there.

EDIT

The other edits were getting a bit long so I've deleted them. I've just set up a site quickly to test this and the following steps have worked for me (this is Drupal 7):

Created a content type called Author Profile (machine name author_profile)
Added a node reference field from the Article content type to the Author Profile
Created an Author Profile node with a title of "vividvilla"
Created an Article node linked to the Author Profile node above
Enabled the core PHP Filter module
Created a block called Author Details with some dummy content in the body, choosing "Pages on which this PHP code returns TRUE (experts only)" for the block visibility settings.
Entered the PHP code below

<?php

$node = menu_get_object();

// Check we're on a 'full' node page.
if ($node && isset($node->nid)) {
  // Check the node is of the right type
  if ($node->type != 'article') {
    return FALSE;
  }

  // Load the author node based on the node reference field value.
  $author_node = node_load($node->field_blog_authors[$node->language][0]['nid']);

  // Check the title of that node
  if ($author_node->title == 'vividvilla') {
    return TRUE;
  }
}

// Default is to not show the block
return FALSE;

?>

The block only shows on an article page that is linked to an Author Profile with the title of "vividvilla" which I'm pretty sure is what you're trying to.

On the off-chance you're using Drupal 6 just change the $author_node = line to:

$author_node = node_load($node->field_blog_authors[0]['nid']);


How Not To Update Existing Taxonomy Terms At Migration I am using migrate and migrate_d2d to migrate taxonomy terms from a d7 site to another d7 site.How can I specify in my migration that nothing be done if the term already exist in the target?
So far, in "prepare" function, I am querying the target to find out if the term already exist, but I am not sure if this is the right way to go about it or where to go from here.

function prepare($entity, stdClass $row) {
  $term_name = $entity->name;
  $query_checking_if_term_exist = db_select('taxonomy_term_data', 'ttd')
    ->condition('ttd.name', $term_name)
    /* TODO: fetch vid from taxonomy_vocabulary table instead of hardcoding it */
    ->condition('ttd.vid', '2')
    ->fields('ttd', array('name'));
  $term_exists = $query_checking_if_term_exist->execute()->fetchAll();
  if(isset($term_exists)) {
    //TODO
  }
}

If found the solution, if the term exists return false from prepareRow($row) and the term won't be updated or migrated again. like this:

public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }
  $term_name = $row->name;
  $query_checking_if_term_exist = db_select('taxonomy_term_data', 'ttd')
    ->condition('ttd.name', $term_name)
    ->condition('ttd.vid', '2')
    ->fields('ttd', array('name'))
    ->execute()->fetchAll();
  if(!empty($query_checking_if_term_exist)) {
    return FALSE;
  }

}


Trigger highlight in maparea when mouseover on link I've created a content type where I can load an image into a text editor and use Image Map Editor to create area to be highlighted when mouse moves over mapped region. At the same time, below the image, a list of persons in that image is displayed. This names are coming from a taxonomy terms list. How can I highlight the area when I move my mouse on the name below the image? I guess I need a javascript which looks for the id namelist, grabs the text for each link, finds in the map with the map id "mapname123" the area hith the same name and changes its state to hovered. I hope I've used the correct words to describe the situation. Thanks in advance.

  <canvas style="width: 800px; height: 450px;"></canvas>

<map id="mapname123" name="mapname123">
  <area shape="circle" coords="213,301,36" alt="John Doe" title="John Doe" href="#1">
  <area shape="circle" coords="334,312,32" alt="Fred Flintstone" title="Fred Flintstone" href="#2">
  <area shape="circle" coords="437,317,33" alt="Wilma Flintstone" title="Wilma Flintstone" href="#3">
</map>

Name List:

  John Doe,
  Fred Flintstone,
  Wilma Flintstone,

An IT guy delivered the solution. Here the code

jQuery(document).ready(function() {
    jQuery('a[typeof].kisiler').each(function() {
        var txt = jQuery(this).text();
        var maps = jQuery('area[title="'+txt+'"]').attr('coords').split(',');

        maps[0]-= maps[2];
        maps[1]-= maps[2];
        maps[2] = maps[2]*2;

        jQuery(this).hover(function() {
            jQuery('.maphilighted').before('

');
        }, function() {
            jQuery('.tagbox'+maps[0]+maps[1]).fadeOut();
            setTimeout("jQuery('.tagbox"+maps[0]+maps[1]+"').remove();", 100);
        });

        console.log(txt, maps);
    });
})


How to use multiple content types in a "Calendar" View sorting by the field type of "Date"? I am using a module called "Calendar" that puts a calendar on the sidebar, and allows you to add events using a cck, which will be displayed on the calendar so that you can click the date, and it will bring you to the event (along with any other event that day.) the problem is, that i don't want to have to create all new content using the cck that was part of the Calendar module. when installing the module, it added a field type called "Date", which is what the calendar events are sorted by. this allowed me to add other cck events that had that field, into the calendar. The problem is, that it puts in onto the wrong date. instead of putting it onto the date that it is set at, it is put onto the date that it was created. is there a way to fix this?

You need to change the calendar view's Contextual Filter (Under "Advanced") to use the new date field, instead of the post date.


How to alter account activation mail Depending on roles In account settings ,Account Activation mail settings is general i think so.

I want the account activation mail to be altered. I want to check roles, according to that display the mail messages .

how will i do that?

You can create a new rule like this

EVENT saying  After saving a new user account

Conditions saying  User has role(s)  check your role there.

Actions saying send mail you can send the mail what you want in that.


Render field collection multiple times on node.tpl.php I have created a custom view mode for field collections with this code:

/**
 * Implements hook_entity_info_alter().
 */
function view_modes_entity_info_alter(&$entity_info) {
  $entity_info['field_collection_item']['view modes']['myviewmode'] = array(
    'label' => t('My view mode'),
    'custom settings' => TRUE,
  );
}

And I'm trying to render the field in the node.tpl.php using the view mode with this code:

$display = array(
  'label' => 'hidden',
  'type' => 'myviewmode',
);
$output = field_view_field('node', $node, 'field_page_collection', $display);
print render($output);

But the field is rendering with the default view mode, not with the custom one I created. Is there a way to render it using the new view mode??

Thanks a lot!

You should read manual for field_view_field function.

Do not use inside node (or any other entity) templates; use render($content[FIELD_NAME]) instead.
Do not use to display all fields in an entity; use field_attach_prepare_view() and field_attach_view() instead.
The field_view_value() function can be used to output a single formatted field value, without label or wrapping field markup.


How to iterate multi dimensional array and pipe each sub array to another plugin as input in Migration yml I am migrating CSV data into Nodes and Paragraphs in Drupal 8.
I have field in CSV file which has JSON data, I have written a process plugin to convert JSON data to multi-dimensional array.
I would like to know a way to pass the each sub array to my another custom process plugin. Is there any such process plugin available to pipe sub array from parental array in core migrate or through migrate_plus module.
I am looking for something similar so that it passes only sub array into the final custom process plugin.
  pseudo_field_country_time_zones:
    - # plugin which converts JSON data to multi dimensional array.
      plugin: country_timezones_data_formatter
      source: timezones
    - # not sure if this is correct plugin to process array.
      plugin: sub_process
    -
      plugin: country_timezones_paragraphs

You might ask why cant you process the data in the country_timezones_paragraphs process plugin itself. That plugin is being used by other process, so dont want to change it. Other solution for me is to write another process plugin but it will be just code duplication with foreach loop added to country_timezones_paragraphs.
I believe there is already a plugin available either from migrate or migrate_plus module for this scenario , but not able to identify what it is.

$input_data = '[{"zoneName":"Africa Ceuta","gmtOffset":3600,"gmtOffsetName":"UTC+01:00","abbreviation":"CET","tzName":"Central European Time"},{"zoneName":"Atlantic Canary","gmtOffset":0,"gmtOffsetName":"UTC\u00b100","abbreviation":"WET","tzName":"Western European Time"},{"zoneName":"Europe Madrid","gmtOffset":3600,"gmtOffsetName":"UTC+01:00","abbreviation":"CET","tzName":"Central European Time"}]';

Decoded JSON array.

$decoded_array = var_dump(json_decode($input_data, TRUE));

Array
(
    [0] => Array
        (
            [zoneName] => Africa Ceuta
            [gmtOffset] => 3600
            [gmtOffsetName] => UTC+01:00
            [abbreviation] => CET
            [tzName] => Central European Time
        )

    [1] => Array
        (
            [zoneName] => Atlantic Canary
            [gmtOffset] => 0
            [gmtOffsetName] => UTC±00
            [abbreviation] => WET
            [tzName] => Western European Time
        )

    [2] => Array
        (
            [zoneName] => Europe Madrid
            [gmtOffset] => 3600
            [gmtOffsetName] => UTC+01:00
            [abbreviation] => CET
            [tzName] => Central European Time
        )

)

There's no such process plugin in core or migrate_plus. If you can't find what you need in those lists, you'll probably have to write a custom solution. You may want to check out SubProcess process plugin which may be able to work with your decoded array with minimal changes.


Menu entries not being translated I have sitemap, and I would like to display the menu in the primary language of the site.  However, as this screenshot shows, some items are still being displayed in English:

How can I fix this?

I miss to determine the language of the menu ... I am stupid it fix by adding the language of each menu i wanna to display on specific language like this


How do I optimize a Views "execute_count_query"? So, I was able to optimize a particularly nasty query in one of my views using mymodule_views_query_alter(), bringing it from 13 seconds down to about 200 milliseconds.  However, I see in my Devel query log there is an associated "execute_count_query" that Views automatically runs that does NOT contain my optimizations.  It is as if any count query ignores my hook overrides.  Thus, the count query continues to run up a 13 second call!  I've pasted it below in all its disgusting glory.

So, how in blazes do I get at this query?

SELECT COUNT(*) AS expression FROM (
SELECT 1 AS expression FROM drupal_node node INNER JOIN (
SELECT td.*, tn.nid AS nid FROM drupal_taxonomy_term_data td
INNER JOIN drupal_taxonomy_vocabulary tv ON td.vid = tv.vid
INNER JOIN drupal_taxonomy_index tn ON tn.tid = td.tid
WHERE (tv.machine_name IN (:db_condition_placeholder_7)) ) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid
LEFT JOIN drupal_taxonomy_vocabulary taxonomy_term_data_node__taxonomy_vocabulary ON taxonomy_term_data_node.vid = taxonomy_term_data_node__taxonomy_vocabulary.vid
LEFT JOIN drupal_field_data_field_published_at field_data_field_published_at ON node.nid = field_data_field_published_at.entity_id AND (field_data_field_published_at.entity_type = :views_join_condition_0 AND field_data_field_published_at.deleted = :views_join_condition_1)
WHERE (( (node.status = :db_condition_placeholder_0) AND (node.nid IN (SELECT tn.nid AS nid FROM drupal_taxonomy_index tn
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th ON th.tid = tn.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th1 ON th.parent = th1.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th2 ON th1.parent = th2.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th3 ON th2.parent = th3.tid
LEFT OUTER JOIN drupal_taxonomy_term_hierarchy th4 ON th3.parent = th4.tid
WHERE ( (tn.tid = :db_condition_placeholder_1) OR (th1.tid = :db_condition_placeholder_2) OR (th2.tid = :db_condition_placeholder_3) OR (th3.tid = :db_condition_placeholder_4) OR (th4.tid = :db_condition_placeholder_5) ))) )AND(( (node.type IN (:db_condition_placeholder_6)) )))) subquery

As long as you know the query you want use in its place, you can override the count query for a view fairly easily. There are probably other places to do it but I found hook_views_pre_execute() to work pretty well:

function MYMODULE_views_pre_execute($view) {
  if ($view->name == 'view_name' && $view->current_display == 'page') {
    $new_count_query = db_select('some_table', 't')
      ->fields('t', array('id'))
      ->condition('some_field', 'some_condition');

    $view->build_info['count_query'] = $new_count_query;
  }
}

Views will convert the above query into a COUNT(*) at some point further down the line.


How do I properly remove "Powered By Drupal"? How do I remove the "Powered By Drupal" string that is displayed on the site footer?

Does it involve PHP coding?

Use this technique

go to yoursite/admin/structure/block

you will see the "Powered by Drupal" as a block

Choose - None - it will go away and you can create your own block with your own footer information


Having a view spitting out a form - the UI way Suppose I have a lot of entities that match users to some nodes and the entities have a field called "rating" which is/could be a Drupal list of four possible values ranging from interesting to uninteresting.

I want to have a view that spits out all entities related to the currently logged in user and let him choose his rating for each of them. When he comes back later, he should see his choices and be able to edit it.
How to do that?

I know, that it's somehow possible by writing a module. Ideally, I don't want to do that but rather solve it completely with UI.

(I'm not fixed to the entity approach I described above. If you think it's a bad idea, I'll be happy to hear alternate suggestions.)

You can try using the editablefields module.

I personally find it better to write a custom views handler implementing the Views Form API, but you can try to see how far this takes you.


How can I implement AJAX form submission? My task is to submit a contact form via AJAX and then to show a "Thank you for submission!" message, loaded in place where the form was. So I need to ajaxify existing contact form.
I found some examples of how to validate form fields using AJAX in D8, but I can't find any example of how to implement an ajax form submission and load some content via AJAX then.
How can I implement my task? How should I alter the contact form to add the required functionality?

When working with ajax in forms you have to keep in mind the following things:

know if you are rebuilding the whole form or only part of it and wrap the form accordingly with div element that has ID attribute that you will use in the #ajax definition on the triggering element as 'wrapper'. Use #prefix and #suffix attributes for this($form['#prefix'] = '
'; $form['#suffix'] = '
';). Also keep in mind that if you have custom template for your form to NOT render the prefix and suffix in this case({{ form|without('#prefix', '#suffix') }}) otherwise they will get rendered twice - by your template and also by the form theme wrapper. You cannot prevent this by setting #theme_wrappers to empty array since the form template contains the actual form html element.
in your ajax submit handler, return the whole form or portion of it that you've wrapped and want to rebuild(return $form or return $form['myelement']). You can additionally use ajax commands instead of just returning the form structure but that is more advanced stuff.
store every value in form state's storage until you submit the form. Do this in the submit handler($form_state->set('somevalue', $form_state->getValue('somevalue'))) and always call $form_state->setRebuild() if you are not doing the final form submission. I prefer having custom submit handlers but having more logic in the primary submit handler is totally ok as well.
always use #name attribute on the button that is doing the submission and if you have only single form submit handler use $for_state->getTriggeringElement()['#name'] to detect which element has submitted the form.
if you are using 'trigger_as' in the #ajax definition, in case you want to submit the form with select element for example, always use the same #ajax definition like you do on the button. In my experience it is required - although not stated in the documentation.
using #limit_validation_errors can get very tricky sometimes and to figure out why the form is not working can take quite some time, so use it carefully(this is good for isolating form errors only on the element(s) that you are actually rebuilding so that your code does not influence other parts of the form).
always use buttons to submit the form and if you want to have something fancy, like select being the triggering element, use the 'trigger_as' option of the #ajax configuration and hide the real button with 'js-hide' class for good UI.
in the form definition, get the default values from the form state's storage if they exist or assign them into the storage if they don't. Otherwise the form won't work properly.
don't use $this or anything else that you don't have access to externally, otherwise it will break the ajax. always use static ajax handlers.
when finally submitting the form, depending on the fact that you (don't)have  a custom form submission handler for the ajax, disable the form rebuilding by calling $form_state->setRebuild(FALSE).
you can use the :: shorthand calls in the ajax submit element($element['#ajax']['callback'] = '::ajaxFormRebuild'; and $element['#submit'] = [['::ajaxFormSubmitHandler'];).
the ajax callback is purely to return the rebuilt form or ajax commands. Never return altered form(ie. do not alter the form array in this callback).


Migrate_d2d: Excluding node import based on a date comparison For a migrate_d2d project, D7 -> D7, I wish to exclude the importing of nodes whose date field is less than the current date. My only class overrides are for mapping custom fields. The migrate function is working as I expect. However, we don't need to import nodes whose dates have passed today's date.

The custom node field is not part of the core field data set, so the following:

public function prepareRow($row)
{
    $postDate = $node->field_job_start[und][0][value2];
    if ($postDate < time()) {
        return FALSE;
}

Will not work, as 'field_job_start' isn't accessible until prepare() by which time, apparently, a return FALSE doesn't cancel the row import.

What is the best way to exclude these rows?

You have to do this in prepareRow. Whatever value is mapped to field_job_start, check its value there and return FALSE.


Redirect anonym user after click on link i have preprocess function

function THEME_preprocess_views_view(&$vars) {
    global $user;
    $view = $vars['view'];

    if ($view->name == 'questions_by_category' && $view->current_display == 'page') {
        $vars['header'] = '<div>' . l('Ask your question', 'node/add/question') . '</div>';
        if($user->uid == 0) {
            //this code not working
            if($_GET['q'] == 'node/add/question') {
                $path = drupal_get_path();
                drupal_goto('user/login', $path);
            }
        }
    }

i need to redirect anonym user to login page when he click on the link node/add/question, i also tried with arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'question' but this wont work.

The code inside if($user->uid == 0) { } works fine, i can redirect, but i need to redirect on click only. Also i need to redirect user back on the page after login, and this code :

$path = drupal_get_path();
drupal_goto('user/login', $path);

seems not working too.

ok i found solution, i just changed link for anonym user

if ($view->name == 'questions_by_category' && $view->current_display == 'page') {
        if ($user->uid) {
            $vars['header'] = '
' . l('Ask your question', 'node/add/question') . '
';
        }
        if ($user->uid == 0) {
            $vars['header'] = '
' . l('Ask your question', 'user/login') . '
';
        }
    }


Drupal Auction module - Mails not send I'm using the Auction module now. The Auction works fine, but there are no emails sent to users when they place a bid. When you insert your bid

  Unable to send e-mail. Contact the site administrator if the problem persists.

When I create an account, then i get a email with instructions. Only by the Auction module the mails will not sent. I saw one topic:

Drupal node 1945662

But there was no good answer for me. I used this module auction

Did you look at Debugging your Email on a development server? Have you looked at the Rules module and the Auction Rules to see if their firing (it sounds like they are)? Did you create hook_mail_alter() to see what email drupal thinks it's sending?

Does your "Create Account" email message fully validate as an email sent from a valid domain, etc.

It's email -- there are no easy answers :)


Format date in Rules I'm using a rule to send out emails when a node is created. Under Action and Message body, I insert [node:field_calendar_date]. The token is replaced with (for example) "2012-12-14T08:00:00" in the email message, but I would like it to be replaced with "Friday, December 14, 8:00am" (same date, but a different format).

I tried to follow format_date(), but it doesn't work.

How can I get the format I want?

You can use [node:field_calendar_date:custom:l, Fd, gia], if [node:field_calendar_date] is a date token. In that case, [node:field_calendar_date:custom] returns the date in the custom format listed after the following colon. The format string is the one accepted by date().

If you want to use the format set as short/medium/long format set in the Drupal date settings, then you can use the following tokens:

[node:field_calendar_date:short]
[node:field_calendar_date:medium]
[node:field_calendar_date:long]


How to dynamically pass contextual filter to a block view without changing view settings I have a content type called artists. In various locations I want to feature one of the artists. I have a view block that has a contextual filter for the node id.

I want to display this this block on various locations of the website. I want site admins to be able to change the featured artist ( node id ) but I don't want them to have access to the views interface ) how can I pass the the node id via the blocks interface or is there some other way that I can make a mini admin screen that will let site admins choose the featured artist?

I don't want to use the promoted to homepage feature on the content type or any other field on the content type as the artist themselves have access to edit their content.

Any advice would be greatly appreciated.

You have a task:

  " I want site admins to be able to change the featured artist ( node id ) but I don't want them to have access to the views interface )"

and it seems you already decided to use specific solution:

  pass the the node id via the blocks interface

Don't do that. That's pretty weird and unneeded. Easier options are:

Draggable Views and show only first one
Use "sticky" or some other field to mark promoted artists (random order, limit 1 in case more than one is selected)


variable api vs custom table I have a module Block No Results which displays the no results data when block has no results.
Variable Api
if I will use the variable api then I need the 4 variables for a single block to keep the no results data and displays the results.
Custom Table
If I'll go with custom table then I'll keep the 6 fields in the table.

id - primary key

module - varchar(64)

delta - varchar(32)

status - tinyint(4)

content - longblob

empty_criteria - varchar

UNIQUE KEY md (module,delta)

KEY list (status,module)

Overview
On every block view I need to check that whether the block no results criteria is enabled for this block.If it is then I need to check what is the empty criteria and on the basis of that I need to perform action.

Problem
Variable api : If I'll use the variable api then on each block view I need to load the variables separately i.e. 5 variables load( ~5 database fetch queries)(if block no results is enabled) and 1 variable load(~1 query)(if block no results is disabled for that block).
As the variable api is integrated with the cache api so on the development sites usually get the results from cache.This seems to me not good approach in the case if a site has 100's of blocks.

Custom table
Load the whole row using the module & delta and take the appropriate action if needed.

Currently I have implemented this using the variable api.
Which approach should I use ? Is there any other better approach then these ?
how I can make it more better if you are going to suggest an approach ?

Not an answer per say; more of a critique of some of your assumptions with variables.

  If I'll use the variable api then on each block view I need to load
  the variables separately i.e. 5 variables load( ~5 database fetch
  queries)(if block no results is enabled) and 1 variable load(~1
  query)(if block no results is disabled for that block)

In actuality all variables get loaded on EVERY pageload with a single query, including cache_page hits (think anonymous users) unless your doing something special ($conf['page_cache_without_database'] = TRUE;, varnish, or boost). variable_initialize() get's called very early; dig though drupal_bootstrap() a little bit to see. So a variable get doesn't cost you a db query, but it's not a good idea to abuse the variables db table because the more data that's in there (KB), the slower Drupal gets.

Actual answer:
My personal preference is to use cache_get_multiple() if your looking at 100s of items to get; unfortunately it looks like _block_render_blocks() makes this hard to do; the function that calls hook_block_view_alter(). So in this case a cache_get would be the easiest way to go. Another option is a cache loader; all in one cid (harder to manage writes) or get all cid's for the enabled blocks block_page_build() or $blocks = drupal_static('block_list'); with drupal_static(). What's ideal depends on many factors, biggest one being how large (KB) is the cached data; if its small a loader & drupal_static() might be the fastest option. If you have a large amount of data then doing individual cache_get() call might be better due to the lower memory usage and not loading unused data. See https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 for more details on caching.

Also be aware of cores built in block caching. Use it if at all possible. See https://www.drupal.org/project/blockcache_alter for ideas and usage.


Devel query log not showing all queries I've enabled the Devel query log, and it's logging most queries as expected. However, I've got this module which connects to another database and executes a few queries against that one. All queries goes through db_select(), db_query(), db_insert(), db_delete() or db_update().

However, queries executed against the other database (connection is configured on the fly, and not through the settings.php file) never appears in the query log.

Any way I can make it work, so that ALL queries appear in query log at the bottom of the page?

Note: Caching does not seem to have anything to do with it. I've cleared all caches, returned to the page, and still no queries appear in the query log.

It's because Devel uses the Database::getLog() static method to get a list of the queries that have run for the page.

That method can only be run for a single connection at a time, and Devel specifically requests logs for the 'default' database connection (see devel_shutdown_real()):

$queries = (devel_query_enabled() ? Database::getLog('devel', 'default') : NULL);

In short you've got 2 options that I can think of:

Edit the devel module file directly, forcing it to loop through all available connections and combine the query logs (obviously hacking contrib modules is not recommended though)
Implement your own logic in a custom module and have a second set of query logs appear at the bottom of your page. The devel_shutdown() function and devel_shutdown_real() should give you all the code you need to get started if you go down this route.


What's the difference between the container and html_tag render elements? What is the difference between render elements of #type html_tag (set to div) and container in Drupal 8?
Is the container render element, a simpler version of html_tag? Easier for processing to preprocess container elements?
I note that:

historically, html_tag was for void elements in the  tag in Drupal 7.x.
if the container element is used a form, it adds the form-wrapper/js-form-wrapper class and an HTML ID if it has #array_parents.

Perhaps my theories are correct (easier to leave be for historical reason / form element reasons)?
PHP:
  use Drupal\Core\StringTranslation\TranslatableMarkup;

  $variables['myhtml_tag'] = [
    '#type' => 'html_tag',
    '#tag' => 'div',
    '#attributes' => [
      'class' => 'my-container-class1',
    ],
    'child' => [
      '#markup' => new TranslatableMarkup('Some Container text1.'),
    ],
  ];

  $variables['mycontainer'] = [
    '#type' => 'container',
    '#attributes' => [
      'class' => 'my-container-class2',
    ],
    'child' => [
      '#markup' => new TranslatableMarkup('Some Container text2.'),
    ],
  ];

HTML:

Some Container text1.

Some Container text2.

I did "Blame" on the 7.x system.module after I didn't found a clue of 'container' in the 6.x branch. In the "Blame" you can see that Dries himself committed the patch that introduced $types['container'] in 2010 and that it leads back to the following issue on drupal.org:

#557272: FAPI: JavaScript States system

The issue which introduced #states to the Form API! Now let's scan the page for "container". Okay, comment #36 explains quite a bit of the reason why it was introduced:

As discussed with kkaefer and tha_sun, we switched the "wrapper" Form
API element type to "container" to not get too confused with other
"wrapper" stuff, like "wrapper_callback", "theme_wrappers", etc. The
"container" type still uses the CSS class of "*-wrapper" though, to
match with the rest of the Drupal coding standards.

And in the commit itself you then can see how container elements already replace some markup elements (markup being the default if #type omitted) which had '#prefix' => '<div>', '#suffix' => '</div> with hardcoded HTML.
To make it short: Container is a classical wrapper. And more of a form element. Whereas html_tag is more of a render element, traditionally used for void elements, often in the HTML <head>. Like placing meta tags or placing JavaScript and CSS libraries in script tags.


Why does the download page recommend the previous version? Why does Drupal download page recommend Drupal 7.x? I can hardly see the footprint about Drupal 8.

Does it mean Drupal 8 is still under development? Does it mean Drupal 7.x can be the last stable version?

Yes, Drupal is under development. See
 http://drupal.org/core/release-cycle

API freeze was in July, now API completion phase.


How to change a fields label name based on another fields value? I have a content type and it has two fields:

Field One (select list)
Field Two (text area)

What I want to do is to change Field Two's label name based on Field One's value in node add/edit page and node dipslay. If Option 1 selected in Field One field, then make the Field Two's label name Option 1 etc.

How can I do this?

Consider using the Conditional Fields module. Excerpt from its project page:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

So if you have like 6 possible values (Option 1, ... Option 6), as in your comment below the question, you could create 6 fields with label "Option 1", ..., "Option 6".
Not sure if it is acceptable to "split" your "Field Two" in like 6 separated fields, but at least it would change the field labels as you are asking for.