Is there way via phpMyAdmin or importing SQL into the database? Yes. Between 2 Drupal installs of the same version that is possible, but that comes with a big caveat. You need to know exactly what you're wanting to import and that you're not missing anything.

For example, say you want to import roles. You could export/import the role.sql from the role table, but that would only get you the role definition. If you want the permissions with those roles, you'd need to copy over the role_permission table. Depending on your needs this might work; the smaller number of table dependencies, the easier this approach can work without a problem.

However, in your case, you've mentioned a few Drupal components that span multiple data tables (e.g. node types, views, fields, etc.), not to mention other configurations (e.g. module settings in the variable table) that a module might depend on to behave the same between 2 installs. To take the example above, the role_permission is filled with permission items that are created by various modules. There might be a problem if you don't have all the same modules installed on your new site.

In these cases, and in general, you're better sticking with the tools that the community has created to handle importing the various components of Drupal. For example, the maintainers of Views have already built in a export/import feature for views. There many posts on Drupal Answers discuss these tools (and how to use them). Here are a few examples:

Features (content types)
Feeds (content/users/taxonomy)
Drupal-to-Drupal migration (users/profiles/taxonomy/content)
User Import (users)


Add a NO RESULTS BEHAVIOR Global: Text area to the inner view (the one in the header) and leave it empty.

Add this code to your theme's template.php file:

function THEME_views_pre_render(&$view){
  if (($view->name == 'outer' && $view->current_display == "default") || ($view->name == 'inner' && $view->current_display == "default")) {
    static $count = 0;
    $count += $view->total_rows;
    if (count($view->parent_views) && $count == 0){
      $view->empty['area']->options['content'] = "custom no result text";
    }
  }
}

Change the view names (outer and inner in my example) and display_names (default in my example) to reflect your views.

Clear the cache.

Perhaps someone else can elaborate on how to add the global text for the no result in code instead of setting it to an empty value in the UI and then altering that value in code.

EDIT

If you intend to add any of these block multiple times on the same page then this answer will no longer be valid. Also, the no result text displays in the no result text for the inner view. You may want to consider altering the title of the block in that case. Unfortunately the outer view runs first, so it cannot be added to there as the result count of the second view is not yet available at that stage. count($view->parent_views) is the bit of logic that checks for the inner view.You can change that to check for the $view->name if you want to.


Drupal_goto => POST $result as node Title

You add this line before your code:

$search_term = arg(2);

Send it in your drupal_goto, but you need to specify which content type to add (here i chose "article"):

<?php drupal_goto('node/add/article', array('query'=>array('title'=>$search_term))); ?>

And hook your node form in a custom module (here I chose content type "Article") :

function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;
  if ($content_type == 'article') {
    if(isset($_GET['title'])){
      $form['title']['#default_value'] = $_GET['title'];
    }
  }
}


Can I delete leftover field_deleted_* tables?

No, this is not a good idea, because there are more things that need to be removed, not only the database tables. Deleting these tables without checking their usage first (see troubleshooting below) results in this error Cron error message. table or view not found: 1146

The deleted fields are purged by cron, but only 50 rows per run. If you want to accelerate the process, run cron more often or increase the batch size in field.settings.yml:

purge_batch_size: 50

Instead of cron you can run field_purge_batch() from the command line, then with a higher batch limit, for example 1000 or how many rows you have and are able to delete without hitting a memory/time limit:

drush ev "field_purge_batch(1000)"

Troubleshooting

If cron or the drush command has no effect, even not deleting some of the rows (if there are any more rows left in the tables), then check whether there are still field storages registered for these tables:

drush ev "var_dump(\Drupal::state()->get('field.storage.deleted'))"

If this is empty, then you can remove the tables in the database as well, because Drupal has no chance to guess the hash keys of the table names without this information.

If this is not empty, then you can use this output of the field storage definition(s) to debug this further (see comment of @MarioSteinitz).


Using webform 4.x values in other fields/descriptions on multi-page webforms

Once you complete an specific field in one page, it can be used ONLY in the next page.
The variables are stored into ->

$form_state['input']['submitted']['your_field_machine_name']

One trick I did, I saved that submitted variable into a hidden input in the next page.


How do I avoid the error "out of memory"?

There's really not much you can do in this case. Drupal 7 requires fair bit of memory and so do Views, Panels, etc.

If upgrading to a hosting plan where you have at least 128MB is not an option I would at least make sure the following modules are kept disabled:

Update Manager
Database Logging
Field UI
Views UI
Panels In-Place Editor
Any other "UI" module

Do your development locally and use version control & Features to update your production box.


Create a menu hook with the path "[themed_node/%node]".

Within the function returning the the output for the menu hook use

return theme_node($node);

And then make an ajax call to "themed_node/nodeid" whenever you need the themed node.

Hope that should work.


Error : Only variables should be passed by reference

The error is because you're trying to directly pass menu_tree_output() function return value to drupal_render() function. Which is not allowed because drupal_render() accepts $element as call by reference. When accepting arguments as call by reference those must be passed as variable (preferred).

So your code should look like below:

        <?php $menu_output = menu_tree_output(menu_tree_all_data('menu-top-menu')); ?>
        <?php print drupal_render($menu_output); ?>


File viewer with search filter by category and sub categories Drupal 7

A vocabulary of taxonomy terms could be set up to reflect the hierarchy of books.
Then you could attach this vocabulary to your node content type. After uploading a file to a node, you can tag the node with the appropriate term.
Views allows you to filter by taxonomy term of any depth.

This would organize your data, but you'll need to use some plugin/other means to display the book in adobe reader in the browser.


In Drupal 7

 $data =  variable_get('test_content_types');

In Drupal 8

 $data = \Drupal::state()->get('test_content_types');

For more information about about "get", "set", "delete" visit - Step 5: How to upgrade D7 variables to D8's state system.


Programmatically creating multivalue field with a button of add another

Here is a nice article on how to do it using Form API http://rapiddg.com/blog/use-ajax-support-multiple-item-values-custom-drupal-7-forms

Hope this helps.


Is the views module a viable options for creating reports with calculated totals?

Another Module you can consider is the views summarize

  Enables an extra display style which displays summaries of a column on
  the last row.

You can also use the views calc mentioned by @Felix together with the views aggregator module


In the Advanced section of the view, click on Query Settings and choose your own LDAP Query from the select list that appears.


You need to use the l() function in place of t() (which is a string translation function):

$url = Mage::getUrl($brand->getUrlPath()).'.html';
$link = l('Link Title', $url);

If the URL is external you'll also want to provide that information in the $options parameter:

$link = l('Link Title', $url, array('external' => TRUE));


This feels like an issue with your files directory permissions. Specifically, the permissions on the directory that contains the image style derivatives for the flexslider. My guess is that they are not being created properly.


will be any problem with my website if I empty all the cache tables from Database?

As per the drupal community doc for clearing the cache you can manually TRUNCATE the tables (empty, not remove) starting with cache_ and there shouldn't be any problem doing so as on visiting any page the cache is rebuilt.

However I would recommend to either use the drush, or clear the cache from the /admin/config/development/performance page.

If you want to clear the cache from code than you may try the following:

// clear cache
drupal_flush_all_caches();

Also its always safe to keep the Backup of database before making any manual operation on database.


How to implement a notifications on my webpages while any data insertion or updation occured on my custom tables

You need to accomplish with three module and rules, private message and custom module.

rules provide event, condition and action through which you need to set, events supports CRUD. Condition provides you to check condition has been fulfill and Event sends you private message to groups or personal mail / text message.

Private message provides you send bulk message / mail through rules. Message itself can be thread.Private message has feature to count unread message to particular user.

Custom module to create event, conditions and actions for rules to custom table.


Drupal 7 Most Popular Tags in a list as a block: How?

You can do this with views:

create a view of terms
add a required relationship to "content using tags"
set use aggregation: yes
add the "term name" field a second time, set one of the to "aggregation type: count"
add "term name" as a sort criteria, set "aggregation type: count"

A sample view is at http://drupalbin.com/19467


If you are using ApacheSolr then I imagine this could be solved with the use of 'Synonyms'.

See the documentation on this.

Example synonyms file you might use:

#Equivalent synonyms may be separated with commas and give
#no explicit mapping.  In this case the mapping behavior will
#be taken from the expand parameter in the schema.  This allows
#the same synonym file to be used in different synonym handling strategies.
#Examples:
ipod, i-pod, i pod
baseball, football


Drupal 8 - What is the format for viewsreference arguments?

I'm see code ViewsReferenceFieldFormatter.php.

The argument field is treated as follows:

if (preg_match('/\//', $argument)) {
  $arguments = explode('/', $argument);
}

Hence argument have next format: tid/nid/custom_id


How to hide text format options when using WYSIWIG module?

Try unsetting the field elements. According to the blog post this kills TinyMCE

<?php
  function [theme_name]_form_comment_form_alter(&$form, &$form_state, $form_id)
  {
    $form['comment_body']['#after_build'][] = 'remove_tips';
  }

  function remove_tips(&$form)
  {
    unset($form['und'][0]['format']['guidelines']);
    unset($form['und'][0]['format']['help']);
    return $form;
  }
?>

source: technonaturalist


How to export custom user fields configuration?

Modules can add in the config/optional directory any configuration file for fields or  entities. For example, the Forum module uses the config/optional directory to define a new content type and its fields, but it could have as well defined fields for a content type defined from another module. Keep in mind that in this case, the module need to define an explicit dependency from the other in the configuration file for the field.

For an example of using the config/install directory for defining new bundles and its fields, see the config/install directory used from the Standard profile.


What's the difference between private message & message?

By using the Message module, you can create your own custom "Events logging" (to register things that happened in a site).

A great sample of this you can find in Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

The Message module is an amazing module, though there is not a lot of documentation about it. It is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules. And to give you an idea of the kind of things you can use it for, have a look at the answers to:

How to create a basic message - notifications system displaying a real time message counter badge?
How to show message view containing own and following activity?
How to integrate messaging into a custom module?
Is there a simple way to notify users about new posts on the site?


Page Title outputting leading/trailing whitespace within H1

In the page.tpl.php file, the page title bit looks like this:

                <?php print $title; ?>

Simply removing the trailing/leading whitespace (tabs and new lines) from the code, did the trick:

<?php print $title; ?>

(Thanks to @sareed and @slawrence10 for the comments that jogged my memory as to how to deal with this!)


How to pass parameters to same form after form submission?

You can use the following code, to achieve what you want.

function submission_list_form_submit($form, &$form_state) {
  $filter = array();

  if (isset($form_state['values']['filter_user'])) {
    $form_state['filter']['username'] = $form_state['values']['filter_user'];
  }

  $form_state['rebuild'] = TRUE;
}

The form building function should then check if $form_state['filter'] is set.

function submission_list_form($form, &$form_state) {
  if (isset($form_state['filter'])) {
    // …
  }

  // …

  return $form;
}

If the code doesn't work, use another array index instead of $form_state['filter']; it is probable that in such case the array index conflicts with the one used by Drupal or a third-party module. I would rather prefix the array index with the short module name, to be sure to avoid conflicts with other modules or future Drupal versions.

References

drupal_build_form()


Term reference field lists the terms for all the languages

Try selecting Localize. Terms are common for all languages, but their name and description may be localized as the Translation mode, after that remove the terms that you added separately for Spanish language and edit each term that are there in English and translate it to Spanish.


There are 2 ways to do this, but you should do this the Drupal way.

You can use JavaScript to iterate through each
 adding a class to the
 if it finds finished in the last column.
You can do it the Drupal way in views. I assume you are using the table view to output your data since that's what you are showing us.

Under your edit view mode, you'll see "Format" and then "Format:Table | Settings".

Click on Settings. Under settings you should see an option that says "Row Class".

You want to set your row class equal to the value of the status field. To do this. Look under Fields to find the field that is displaying your status column and click to edit it. Once there, select "Rewrite results" and then click the "Override the output of this field with custom text" checkbox.

This will open a textbox with an option below it stating "Replacement Patterns." when you click this, you should see some options inside of {{ }}. There will likely be one that looks something like {{ status }} == Status.

The {{ status }} part is your replacement pattern. Copy it and paste it into the row class field under table settings.

What this will do is add a class to your
 in your view.

Example of what the view output will then look like:

  3/5/19>
  write article
  finished

After completing this step, you need to add a bit of CSS to your stylesheet in your theme.

Something like:

tr.finished td { color: red; }
tr.ongoing td { color: green; }
tr.failed td { color: yellow; }

So you end up changing the row class to be the replacement pattern of your status field and adding 3 lines of CSS code to your theme's style sheet.


Is it possible to include countdowns in nodes?

There is jquery_countdown for general purpose countdown display, though the way you would integrate this depends on what you want to countdown. Using this module it is quite easy to display a countdown based on a node field value. Unfortunately there is no display configuration in the UI. But you could use hook_node_view() to add a countdown to a node view like this:

$node->content['countdown'] = theme('jquery_countdown', array(
  'id' => 'jquery_countdown-' . $node->nid,
  'options' => array(
    'until' => date("F d, Y g:i:s a", $some_timestamp),
    'format' => 'dHMS',
    'compact' => TRUE,
  ),
));


Remove label Search terms from Views exposed form

function views_exposed_form($form, &$form_state) {

if ($info = $handler->exposed_info()) {
          $form['#info']["$type-$id"] = $info;
          /**enter your code here  *****/

        }
/**for place holer**/

if (isset($form['title'])) {
        $form['title'][] = array('#placeholder' => t('Gemeente...'));
}

}


How to set related products view contextual filter to get its value from current product category id

I needed a block to display related products for the current viewed product by showing products from the same category.

To do that you can use the same steps used in the 'related article' tutorial.

but first you have to add the ability to extract term id from product page (like the way it is extracted from node page), so you have to modify

core\modules\taxonomy\src\Plugin\views\argument_default\Tid.php

like this

include this namespace:

use Drupal\commerce_product\Entity\ProductInterface;

look for:

    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  }

replace with:

    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  } elseif (($product = $this->routeMatch->getParameter('commerce_product')) && $product instanceof ProductInterface) {
    $taxonomy = [];
    foreach ($product->getFieldDefinitions() as $field) {
      if ($field->getType() == 'entity_reference' && $field->getSetting('target_type') == 'taxonomy_term') {
        $taxonomy_terms = $product->{$field->getName()}->referencedEntities();
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        foreach ($taxonomy_terms as $taxonomy_term) {
          $taxonomy[$taxonomy_term->id()] = $taxonomy_term->bundle();
        }
      }
    }
    if (!empty($this->options['limit'])) {
      $tids = [];
      // filter by vocabulary
      foreach ($taxonomy as $tid => $vocab) {
        if (!empty($this->options['vids'][$vocab])) {
          $tids[] = $tid;
        }
      }
      return implode($this->options['anyall'], $tids);
    }
    // Return all tids.
    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  }


you cane do it by Rules module

please check this article it will help if you are new in rules module


Is it important to use base table in query?

No, it's not important, nor necessary.

There's no API method for getting this information, so going directly into the database is fair game. Once you're going directly into the database, you only need to include the tables and fields that your data requires - anything else is a waste of resources.

In this case, you don't need to select or filter anything from the users table, so there's no need to join it in (unless you're worried about referential integrity, and want to make sure the user record actually exists).


Toggling view modes of Views results with Display Suite

Solution that I use sometimes.

Create a content type with one or more multiple-value block reference fields.
This is like a "cheap" version of panels..
Create your views displays as blocks. One for each version.
Create a custom module to define a block that acts as the "switcher" between the two. Put some dummy content for now.
Create two nodes with the block reference.

One that has the switcher and the Views display A.
One that has the switcher and the Views display B.

Set url aliases for both nodes.
Flesh out the "switcher" block. E.g. make it keep the url query parameters. Make it look different depending on whether you are on A or B.
If you want, you can have a separate block for the exposed filters, that you also add via the blockreference.
Use Display suite or some other way to arrange the different blocks on the page.

The benefit of block reference + ds over theme regions is that you don't spam your theme regions with one-page-only blocks.


Add popup within the ckeditor dialog box?

I don't know a custom module that can do this, I'll do like this:

Create a new content-type with an  entity reference, a trigger
string and a dialog text area.
In the referenced node, query for any referencing entities from the new content type. Most likely with a preprocess function and preferably in a newly created custom module.
Load referencing entities if found and attach a JS file that will receive the triggers and dialogue values through the settings array.
If all is well then JS file will have triggers in selectors and
dialogues to display.


Select a taxonomy parent ID based on the current node type for shared field declarations in cck

Apparently, I am answering my own question. This may not be the best solution (the drupal way) but it works and at least for the meantime I can continue the project. Here is how I solved it:

arg(0), arg(1).. will always refer to the current url arguments. so arg(0) will be the first arg after the siteroot, arg(1) is next.. etc..

With my problem, when you are editing a content type here is my current url path for example: http://localhost/mysite/node/add/commercial-for-rent, where arg(0) = node, arg(1)=add etc..

simply posting this to php snippet worked:

if(arg(2)=='commercial-for-rent' || arg(2)=='commercial-for-sale') return 798;
else return 799;

That's at least as far as the url pattern goes. ../node/98/edit is when editing the content which is again this solution will no longer work...

As I said this is not the best solution if there is anyone out there who has better ideas please do tell me so I can edit the snippet and solve this the drupal way.


The hook you're looking for is hook_views_view_field().

This hook allows you to alter the output of the field, and still is early enough to have the entity data for for that field.

In the example below, I'm checking if the node has a link field, field_my_link set, and if it's set, I alter the title output (which is normally linked to the node) to output to the link field's uri, but only if it's an external link.

function mymodule_preprocess_views_view_field(&$vars) {
  if ($vars['view']->id() != 'testview') {
    return;
  }
  $node = $vars['row']->_entity;
  if ($vars['field']->getField() == '.title' && $node->field_my_link->isEmpty() === FALSE) {
    if ($node->field_my_link[0]->isExternal()) {
      $link = $node->field_my_link[0]->view();
      $link['#title'] = $node->label();
      $vars['output'] = $link;
    }
  }
}

If you want to alter the output of one views field based on the output of another, use hook_views_view_fields():

function mymodule_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->id() != 'testview') {
    return;
  }

  // Cast Markup object to string.
  $field_one_content = (string) $vars['fields']['field_1']->content;

  // Check if first field contains a substring, if so, update second field.
  if (strpos($field_one_content, 'my search string') > -1) {
    $vars['fields']['field_2']->content = \Drupal\Core\Render\Markup::create('hello world');
  }

}


I created a new content element: how do I print it out?

Your question hints that you're not quite yet understanding some of the basics of the Drupal CMS. I'd recommend you do a little reading about nodes, content types and paths.

The page.tpl.php template is the master page template for your entire theme. That means every page output regardless of node type or non-node page altogether.

Your node.tpl.php template is the template for specific nodes. You can create node-MYTPE.tpl.php to control a specific node type.

For further details, see Theming Drupal 6 and 7, and Drupal 6 Template Suggestions.


Change default upload file path (sites/default/files) for a content type

The public filesystem is a system-wide setting; it can't be different per content type.

There's a setting under every file field attached to your content types that will allow you to choose the sub-folder within public:// that files for that field are uploaded to.

As an extension you can get a more advanced version of that functionality with the File (Field) Paths module...but beware, there are issues with it and you'll need to test thoroughly before deploying to a live site.

One of those methods will likely be your best bet. There's lots more info at Working with Files in Drupal, including documentation on how to use the private file system (in case you can leverage that).


How to use Computed_field as a product of an existing one?

A NOT commonly known/used solution that might help to prevent your problem from happening, is to use the (fairly new) Math Field module (for D7), instead of the Computed Field module (so change your mind about which module to use). Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Known issues

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

The cTools math expression library causes an error when using function that take more than one parameter. This effects pow(), min(), max() (#1958538: Improve math expression engine).
Math Field does not yet support multivalue options fields (checkboxes, or multiselect) (#2483453: Add aggregate functions for multivalue fields).
Math Field does not yet support Field Collections (#2573643: Support the Field Collection module).

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...


Do you need this in an existing menu?

Personally I would do this with Views. If you have it installed try the below.

Create a new view
Add a Block Display
Set Access to Authenticated Users
Change the Basic Settings > Style to "Table"
Add Fields for Node Title & Organic Group Post count
Add Filters for Organic Group Member "True"

This will now display a table with the titles and a "new" post count. You can make it look more like a traditional menu by changing the view settings further.


Administration Theme switches to front-end theme

Overlay does not work with prefixed URL paths.
http://drupal.org/node/1075096


How to update a menu link created with MenuLinkContent::create()?

If you remember the id after saving the menu link

$id = $home_new->id();

You can load it directly:

$link = MenuLinkContent::load($id);

If you don't know the id, you can load the menu link by a property:

$links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['title' => 'Home']);

if ($link = reset($links)) {
  // found a link with title "Home"
}


How to call the implemented hook_profile2_access() function?

Well, it was a typical user error: The implemented mymodule_profile2_access() function is called only for non-admin users and I checked it with administrator. So simple...


How do I load templates within templates?

You need to (properly) define two theme hooks. One for your table, and the second for your rows. Then, in the preprocess function for your table, you can call the row template for each row in your data array, something like:

function MODULE_theme() {
  return array(
    'mylist' => array('arguments' => array('data' => array())),
    'mylist_row' => array('arguments' => array('id' => NULL, 'name' => NULL)),
  );
}

function MODULE_preprocess_mylist(&$variables) {
  $rows = array();
  foreach ($variables['data'] as $item) {
    $rows[] = theme('mylist_row', $item['id'], $item['name']);
  }
}

If you want to display a nice and themed table, you don't need to implement your own theme hooks using templates, the table theme hook provided by core should be fine. It is a complete and flexible solution for most table output needs.

function MODULE_table() {
  $header = array(t('ID'), t('Name'));
  $rows = array(
    array(1, 'foo'),
    array(2, 'bar'),
    array(3, 'foobar'),
  );
  return theme('table', $header, $rows),
}


Drupal 7: Display latest articles by an author with bio

If you create a views panel pane (available as a views display mode) and place that with panels, then you can accept arguments from the panels context when editing the view. The display will have panels argument options controls that other display modes do not offer.


How do I add a menu router that works even in the maintenance mode?

You can use hook_menu_site_status_alter() to change the site status for a specific path.

Control site status before menu dispatching.
The hook is called after checking whether the site is offline but before the current router item is retrieved and executed by menu_execute_active_handler(). If the site is in offline mode, $menu_site_status is set to MENU_SITE_OFFLINE.

The user module implements that hook (user_menu_site_status_alter()) to make sure the site is always online for the user, user/login, user/password and user/reset/* paths. It should be simple enough to use the logic from that function to implement it for your custom path, e.g.
function MYMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  if ($menu_site_status == MENU_SITE_OFFLINE && $path == 'my-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}


This is quite a bit more complicated than your previous question.

My best advice would be that in order to get each content node to have a gallery with multiple images, each Article node should use an image field with multiple values.

These "child sideshows" will be completely separate from the "parent slideshow" which is the one using Views with the taxonomy filters (e.g., "Previous / Next Forest").

You should still be able to make the "child slideshow" into a scrollable gallery as you show in your thumbnails (e.g., "Previous / Next image in Article") by using a library like SlickSlider.

This Drupal.org issue queue talks about setting up Slick without Views as a "multi-imagefield single-node slick on D8" so it can definitely be done. (The Slick Extras module may help, but I haven't tried it so I'm not sure.)

It will be a bit more work this way, and not all the advice you find online will be completely applicable to your situation. If you get stuck, I recommend following the Javascript code in the Slick demos rather than any Drupal-specific walkthroughs.

Good luck!

EDIT 2019-11-27: Thanks, the comment below helps me to understand what you're trying to do.

The real problem is that your data model is a mess: you want to apply the taxonomy terms to the Article (child slideshows) content type, and also to the individual photos within the Articles. You apparently don't want to display all the photos in each Article, but only the individual photos that match the selected taxonomy term in the parent. That wasn't very clear from your earlier description.

To accomplish that, I think you'll need to implement the term filters (Animals, Forest, People) as an exposed filter on the child slideshow. You can't filter by the taxonomy terms on the child node because you want to jumble terms together at both levels.

This is made more complex by the fact that you want the same buttons to act as exposed filters on two different Views. No wonder you are having trouble.

Maybe you can use a contextual filter on the child slideshow that refers to the value of the exposed filter on the parent.


How to create a node revision view with a "Node" row style?

I believe the answer to my original question is no, it is not possible (please update if Views changes to allow this).

To accomplish what I needed, I ended up creating a custom module instead of using Views. I lifted the query that Views had generated as this was essentially what I needed. After returning the nid's of the nodes in question, I have drupal theme the nodes:

theme('node', $node, $teaser, $page);

Add each themed node to an array, $items, and then theme that array into an unordered list:

$rendered_list = theme('item_list', $items, NULL, 'ul', array());

I then set the block's content to that returned list.

$block['content'] = $rendered_list;


Site dead after Devel Module and Library sethtmldom

You can try using Registry Rebuild

Project page says..

  THIS IS NOT A MODULE. YOU CAN'T ENABLE IT. FOLLOW THE INSTRUCTIONS.

  Make a backup of your database before running this. It won't break
  your database, but we can't improve this unless we have broken
  databases that it doesn't quite do the job for.

  There are times in Drupal 7 when the registry gets hopelessly hosed
  and you need to rebuild the registry (a list of PHP classes and the
  files they go with). Sometimes, though, you can't do this regular
  cache-clear activity because some class is required when the system is
  trying to bootstrap.

  When would you need Registry Rebuild? You might get something like:

  PHP Fatal error:  Class 'EntityAPIControllerExportable' not found in
  ...sites/all/modules/rules/includes/rules.core.inc on line 11


Give permission to dealer_user_role to create users and profile2 fields

global $user;

$uid = $user->uid;

$accessRoleArr = '';

if(in_array('Admin',$user->roles) || in_array('Dealer',$user->roles) || in_array('Customer',$user->roles))

{ return FALSE; }


How to show a message to a list of article publishers using Rules?

The loop isn't checking for the current user, so it is showing a message for all the users in the list, like you describe.

You need to check that the current user is in that list.

To do so you really need the http://drupal.org/project/rules_conditional module.
It allows you to have conditions in actions.

So your rule would be something like this:

Event: After saving new content
Condition: Content is of type: Article
Action: Load a user list with views (using Rules Bonus pack - user list of article publishers)
Action loop: Loop (above user list)
  Conditional:
    If: Data comparison (Parameter: Data to compare: [site:current-user:uid], Data value: [list-item:uid])
      Action: Show a message on the site

However, if you say that the list of users is any user that has created an article, and this message is being displayed after a user creates an article, then you can be sure the user who just created the article is in the list of users who have created an article :)
So just show the message when an article is created. No other checks for users.


Well after a couple of weeks I got it to work. In case anyone else wants to do the same, here is how I did it.

I added a Webform submissions: Data Relationship for each field in each form (16 total for me....4 fields from 4 webforms). Then I added the fields for each one (again 16 total). Then I went into the Table Settings and had each of the 4 types displayed in the same column. Then I just added a Content: Title field to show which Webform the submission came from.

I don't know if that is the best way to do it, but it worked for me.


I want to write the logs for users info, page navigation in drupal 7

User log in/out is always logged. Switch on the statistics core module for page view statistics. If you need more details google analytics is very handy (or Piwik if you don't trust google).


How to provide a custom option for an exposed filter in Views?

if you are not able to achieve what you need with views default options.
You can create your custom views handler. In this case, it would be a filter handler.

https://api.drupal.org/api/views/handlers!views_handler_filter.inc/group/views_filter_handlers/7

https://drupal.org/node/1239866

Extending views functionallity to provide an approach to your problem


How do I inject services in class that implements an interface?

You define the necessary services as arguments of the service you implement.

Since you are showing a class that implements ThemeNegotiatorInterface, see the theme.negotiator.default service and the class implementing it, Drupal\Core\Theme\DefaultNegotiator.

Service definition

  theme.negotiator.default:
    class: Drupal\Core\Theme\DefaultNegotiator
    arguments: ['@config.factory']
    tags:
      - { name: theme_negotiator, priority: -100 }

Class constructor

public function __construct(ConfigFactoryInterface $config_factory) {
  $this->configFactory = $config_factory;
}

There isn't any static create() method as in your code.


"Process 'Apache web server' failed to start. Port 8083 didn't open"

Sounds like there is a port conflict or a hiccup in Acquia Dev Desktop.

Try a reboot. This might fix an Acquia hiccup.
Since you already have XAMPP configured and working the way you want change, I'd suggest changing the Acquia Dev Desktop port.

Here's how:

Open Acquia Dev Deskop
On the menu bar, click "Acquia Dev Desktop", then "Preferences...."
Click on the "Ports" tab (2nd tab)
Change the "Apache port" to another another number. Eg. "8087"
Click "OK"
You will need to restart the Apache server. You could click the "Stop" -> "Start" button. I prefer to close and re-open Acquia Dev Desktop.

No need to learn/install another DEV environment or change an already setup one (XAMPP)


Well if what I getting from you is right then you have to look into Taxonomy Vocabulary and terms.

So you can have a Vocabulary of Sports but under sports there are so many taxonomy terms - types of sports, like footbal,hockey,basketball etc

then for your content type you add a taxonomy field mapped to the sports vocabulary

now users can create content and add the various tags/terms to it.

if not then you may have to look at using books in drupal


How to reference external JS callback in custom module

You could/should add the defer tag to your maps drupal_add_js as recommended by google (https://developers.google.com/maps/documentation/javascript/tutorial)

You'll get abit better page performance and should get rid of your issue you're facing as the google maps code will always be loaded after your scripts

Here's how you can add the defer tag:
How to drupal_add_js an external and defer script


Out of the box Drupal 8 doesn't support file attachments. Take a look at this module and read the steps on the page: https://www.drupal.org/project/swiftmailer`

  The Swift Mailer module extends the basic e-mail sending functionality
  provided by Drupal by delegating all e-mail handling to the Swift
  Mailer library. This enables your site to take advantage of the many
  features which the Swift Mailer library provides, such as :

  Sending e-mails directly through a SMTP server of your choice, a locally installed MTA agent such as sendmail or the mail functionality
  provided by PHP.
  Sending HTML (MIME) e-mails.
  Adding file attachments to e-mails.
  Adding inline images to e-mails.

Also take a look at this: https://www.drupal.org/node/2821590


Drupal 8 Form Redirect On Failed Validation

If you want the redirect to happen immediately, you can do it like this:

use Symfony\Component\HttpFoundation\RedirectResponse;

$response = new RedirectResponse('/path/destination');

$response->send();


Get the response from Pay-pal if the response code is 200 save the node otherwise don't save it.

for example :

if ($responseCode == 200){
  //node_save($node);
}
else {
  print "payment failed";
}

https://www.drupal.org/node/1207878
check this for more info only for condition to check the payment status.


Simply rewrite the results of Content: Edit link and add image with HTML.

<img scr=".....">

For Example:


is there any general or universal way to change Drupal's objects CSS?

No. Of course there are default Drupal styles but there are no guarantees that whichever base theme you are working from hasn't overridden them.

The good news is that most popular base themes will implement classes that are universal to a particular type of output, like a row or a block. For instance, Foundation uses its own 'row' and 'column' but retains the core 'block' class.

Since you asked :), here is something you might do to add padding to columns in a Bootstrap subtheme:

.main-container > .row > section {padding: 1em;}

Note the '>' combinator. This refers to immediate descendents.

Note: If a selector is prefixed with '#' it is an id, and will only apply to one element. A class is prefixed with '.' and can apply to multiple elements. So all rows in bootstrap can be accessed with:

.row {padding: 1em;}


Is there a way to import Drupal variables into a the twig template?

You can't directly use these functions in a Twig file. Instead, you can preprocess the page and store your configuration settings in a variable that is passed to the template file, and display that variable in the template file.

function mytheme_preprocess_page(&$vars) {
  $vars['new_var'] = $config->get('id');
}

You can render your variable with {{ new_var }}.


Should I translate string inside a Unit test?

No, you should not. An assertion message is basically on the same level as a code comment, you're not translating that either.

We used to do that in core, also because it was all Simpletest then and the messages were shown in the UI, so an argument could be made that should be translatable. But we did massive patches to get rid of that, it just adds more complexity without any additional benefit.


How can I switch language links to master links on a translated page?

Go to admin/config/regional/language/detection/url and then you must delete the path prefix for the language, you don't need code to do this.

And save the config.


Doing this in an .htaccess should be OK.

Doing it in the Apache config for the host (main httpd.conf, include for the vhost, etc) is better.  When you upgrade Drupal, the .htaccess will be nuked.  Also, .htaccess is interpreted for every single access; Apache config (including Includes) is compiled when Apache starts.

You can also use drupal_set_header().  You just need to use the right hook for your situation (not terribly familiar with the Services hooks).

drupal_set_header('Access-Control-Allow-Origin: "*" IS_CORS');
drupal_set_header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
drupal_set_header('Access-Control-Allow-Headers: x-requested-with');

You may also want to check out the H5BP Server Configs project.  I use bits and pieces of this as Apache includes for my virtual hosts, and I am pretty sure they have some good CORS rules.


I figured it out!
this works:

$values=$form_state->getValues();
if ($values['estlecontact']['value']==1 && $values['adherentid'][0]['target_id']==NULL) {
  $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
}

Note that $values['adherentid'] is a mutliple value field. I was missing an array level. Adding [0] before accesing target_id solves the problem.


Can we migrate basic Metatag data without customization?

There's a patch at https://www.drupal.org/node/2563649, currently at "Needs work".


How to disable a language while still being able to create content for it

You could try to use the Hidden Language module.

  This module allows site admins to hide languages from end-users. As opposed to disabling language content editors still can translate content to that language. It's useful if you don't have entire website translated.


Why can't I debug twig templates with intellij idea?

The problem was that the twig cache path was not set for the project.

See https://blog.jetbrains.com/phpstorm/2019/05/twig-and-blade-templates-debugging-2/


Multiple Date field with term attached to each instance

I can confirm that Field Collection is the answer with a little themeing of the node edit page -thanks for your help.


How do I customize the search result page?

You can override theme_search_results(), or theme_search_result().

The first is the theme function that is invoked for the search result page, while the second is the theme function that is invoked to render a single result. Both the theme functions use a template file (search-results.tpl.php in the first case, search-result.tpl.php in the second case).

search-result.tpl.php would use $info_split['type'] in Drupal 6, which contains the node type. In the latest Drupal 7 version, $info_split['type'] is not anymore passed, but search-result.tpl.php still gets $result['node'], in the case the search is done for nodes; $result['node']->type is then the content type of the node.

To notice that Drupal 7, and higher, allows the modules to implement hook_search_page(), but it is a hook used by a module that integrates with the Search module, not from a module that wants to change the result page for results returned by another module.
Also, on Drupal 7, each theme function uses a preprocess function, which in this case would be hook_preprocess_search_results() and hook_preprocess_search_result(). They are helpful in the case you just need to edit the value of what passed to the template file.


to slecet image uri you have to do

selest uri from node
join field_data_filed_image on field_data_filed_image.entity_id = node.nid
join file_managed on filed_image_fid = fid

anfd you can use this function to get thumbnail using uri

<img class="image" src="<?php print image_style_url('thumbnail', $block->uri) ?>"/>


Views regex: exclude alphabetical strings as well as those with spaces

The Views module uses MySQL regular expressions, and \s is not recognized in those regular expressions.

You should try with [^a-zA-Z[:blank:]], or [^a-zA-Z[:space:]]. The first excludes any whitespace character, while the second excludes any space, tab, newline, and carriage return.

In the views_handler_filter_string class, the method associated with the regular expression is the following one.

  function op_regex($field) {
    $this->query->add_where($this->options['group'], $field, $this->value, 'RLIKE');
  }

// Add regexp support for MySQL.
if (Database::getConnection()->databaseType() == 'mysql') {
  $operators += array(
    'regular_expression' => array(
      'title' => t('Regular expression'),
      'short' => t('regex'),
      'method' => 'op_regex',
      'values' => 1,
    ),
  );
}


When you want to alter the behavior of an existing form, hook_form_alter() is a useful tool here. Here you want to alter the existing form so that the redirected URL has an extra query parameter. By looking at the submission handler we can see that the search form uses drupal_redirect_form() to go to the /search/node/SEARCH_TERM path.

We can add an extra submission handler to this search form so that it modifies the redirect path with the extra query parameter.

Here's an example MYMODULE that would do as such for the search block form.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Add an extra submission handler the search block form.
  if ($form_id == 'search_block_form') {
    $form['#submit'][] = 'MYMODULE_search_box_form_submit';
  }
}

/**
 * search_block_form submission handler
 */
function MYMODULE_search_box_form_submit($form, &$form_state) {
  $form_state['redirect'] = array($form_state['redirect'], array(
    'query' => array(
      'scq' => $form_state['values']['search_block_form'],
    )
  ));
}


In the firebug(any) console, try jQuery('#edit-title').css('color', 'red'); it should work or something with the css is wrong.

For Drupal you're really supposed to use something like this to do on document load:

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };
})(jQuery);

Check out Managing JavaScript in Drupal 7, and search for "behaviors".

@ krister.. The code is a function where the $ variable is jQuery. So in most languages you create function and declare variables that you want passed into it. Well in JavaScript you can create that in one line.

function some_function(tmpVar){ alert(tmpVar); }
some_function("Woot!");

You can wrap the function side in ()s and it still works
( some_function )("Woot!");

Now you can put an anonymous function block instead of some_function

( function(tmpVar){ alert(tmpVar); } )("Woot!");

and finally the jQuery

(function($){... the $ = jQuery ...})(jQuery);


Preferred way of adding new setting to all fields in a View?

I wrote the module Views Label Tooltips based on my technique to achieve this, and here's a post explaining it: http://thereisamoduleforthat.com/content/recipe-extending-views-handlers-without-subclassing


How to bulk update (delete) Product Variations

Seems now you know the answer :)

https://www.drupal.org/project/commerce_bulk/issues/3023651

BTW, thank you for your contribution to the module!


Can Views output only the first vocabulary term?

Edit the term reference field in your view, and under "Multiple Field Settings" check "Display all values in the same row". You will be presented with further options. You will probably want Display options to be Simple Separator, then change "Display [all] value(s)" to "Display [1] value(s)", apply and save your view.


How do I ignore a module .git directory?

Your analysis is correct; git_deploy is only useful for projects that are ultimately hosted on drupal.org.  The pm-* commands only operate on drupal.org projects, and have no facility for ignoring projects from other sources.  This is a limitation of Drush; improvements in this area would be welcome.


The Omega theme is a grid based theme that will allow the developer to use a shared CSS file and three different CSS files for different screen resolutions. This way the same site can be served to different devices without having to do a ton of work to make it look nice on all of them.


if((empty($form_state['values']['field_institute_event']){
form_set_error('field_institute_event', t('YOURMESSAGE'));
}

That should do it. If you  want to validate on empty value on a required element.
You could also add the '#required' => true on your form element.


How to alter commerce checkout form in a custom module?

I think you're looking for commerce_checkout_form() (commerce_checkout_form_checkout doesn't exist as far as I can tell from greping Commerce's code):

function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

or

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}


how do I organize the input fields in fieldset?

If I understand correctly you want to move existing form elements into the fieldset you created.  Try this, I'm assuming the fields you want to move are $form['field-14sq'] and $form['field-510sq']

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {
    $form['cpmonth'] = array(
      '#type' => 'fieldset',
      '#title' => t('test'),
      '#weight' => 5,
      '#collapsible' => TRUE,
    );
    $form['cpmonth']['field-14sq'] = $form['field-14sq'];
    unset($form['field-14sq']);
    $form['cpmonth']['field-510sq'] = $form['field-510sq'];
    unset($form['field-510sq']);
  }
}

If you have custom submit and validation functions this shouldn't affect them, since fields in fieldsets still come back in the root level of $form_state['values'] .


I get a syntax error when I try to execute a query

You should do

$result = db_query("SELECT id FROM {mg}");

It doesn't look like you should get parse error unless you really use “” and not ""


Implement a Facebook login without breaking the privacy

I can suggest you a module called Janrain engage drupal.org/project/rpx , this does not add links, it helps you during the registration to collect the user data as well. Have a look to it.


You need to set up a virtual host on your server and put the xhprof front-end HTML files on it (the ones that come with the the xhprof download). Give the host an address (e.g. http://xhprof.localhost/xhprof_html as suggested), then give that path to Devel.

Then you should get the link at the bottom of each page to check the profiling information for that request.


I did build a fancy timeline using module 'jQuery timelinr integration', which only is a style for Views letting you render your data as a timeline.

Check the library demo : http://www.csslab.cl/ejemplos/timelinr/latest/horizontal.html

Here the full project : http://www.csslab.cl/2011/08/18/jquery-timelinr/


Is there a way to pass additonal php.ini settings to a drush command?

In the Drush README file, in the section titled "CONFIGURING PHP.INI", you will find instructions on how to set php configuration variables without modifying the drush script:

export PHP_INI='/path/to/php.ini'
export DRUSH_INI='/path/to/drush.ini'
export PHP_OPTIONS='-d memory_limit="128M"'

The first option replaces the entire php.ini file with one of your choosing.  The second option allows you to specify an ini file that is merged in with the standard php-cli ini file.  The last option allows you to specify commandline options to set configuration values.  Note that the second option effectively works the same way as the third option -- all of the settings are converted to commandline options.  See the php documentation for more information on php commandline options.

If you want to do this for just one call:

alias specialdrush='/usr/bin/env PHP_OPTIONS="-f /path/to/my/php.ini" drush'


How do I use jQuery code through a module/theme?

In Drupal 7 and 8 your JS code needs to be wrapped like this:

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //custom code goes here

  }
};
})(jQuery);

To test, put the following code inside your JS file.

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $("body").click(function() {
      alert("Hello World");
    });
    //code ends

  }
};
})(jQuery);

Now when you click in the body, you should get an alert saying hello world.

For more info read the JavaScript API in Drupal
 8


I always use the vhost file for this:

# Enforce domain.
RewriteCond %{HTTP_HOST} !^example.com(:.*)?$
RewriteCond %{HTTP_HOST} ^(?:.*?)(:.*)?$

RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

I would much rather to this on the Apache level, than PHP, to keep it as fast a possible.

Similar configuration for nginx here.


Something along the lines of this, &node[title]=testnode&node[type]=story&node[field_test][0][value]=testtting

Also, if you are ever unaware of what to send, just look at the tests.


I am not able to override the form #access setting

$form['field_usage_restricted']['#access '] the #access key has a space in it. Only reason I can think of you would get two items in the array like that. Remove that space, and dump the item out again. It should be overwritten and have FALSE for a value.


How do I create hierarchical select for state, district, city, and location using AHAH?

It seems Hierarchical Select does exactly what you need.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


403 Error on AJAX Request in add new item (collection field)

for what it's worth we just wrestled with this for a while on our own sites. The solution actually ended up being disabling cloudflare on 'system/ajax' URLs. If you're running CF and have this problem - try it!


How to attach files using mimemail (Getting 0kb file)

I usually do mine I little different from you, I add the attachment in hook_submit then pass it as a param to hook_mail, but even then some of our variables differ. here is an example from a working solution I have implemented, but changing to your text. I also added in the headers, maybe they arent necessary because I use it when dealing with jpeg file types.

function tellafriend_form_submit($form, &$form_state) { ...
    $attachment = array(
      'uri' => $filepath,
      'filename' => 'counciltax.txt',
      'filemime' => 'text/plain',
    );
    // Add attachments
    $params = array(
      'attachments' => $attachment,
      'file' => file_create_url($attachment['uri']),
    );

    drupal_mail('tellafriend', 'notify', $email, language_default()), $params);
}

function tellafriend_mail($key, &$message, $params) {
  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['subject'] = t('Your friend thought you might like this site');
  $message['body'][] =t("Hello,\nYour friend thought you might like this site.  Please click the link below to visit.\n\n!link", array('!link' => $base_url));
  $message['params']['attachments'][] = $params['attachments'];
}


Using "Add another" field widget on non-fields (extra_fields or Entity API properties)

The Examples project has an "ajax example" submodule that shows how such a thing can be done with #ajax in a form. Should get you far.


How do I remove the "My account" and "Logout" links?

Try going to Appearance settings on your sub-theme admin/appearance/settings/... and uncheck Secondary menu.

If that doesn't work, check menu settings at admin/structure/menu/settings and make sure you haven't defaulted the main menu to "User menu".


Figured it out. I was using Adminimal for my admin theme, and I changed the skin to "Alternative" and tried again ... and it worked. So it was something in the theme that caused the conflict, though I don't know what.


How to add contextual fields to breadcumb links?

I'm not aware of any contrib module that is capable of adding custom fields as suffix to breadcrumb links.

Fortunately, Drupal 8's modular architecture enables you to add your own breadcrumb builder service with a little bit of custom programming.

You will have to create an own module (within the following example, I'll call it my_module or MyModule respectively; you'll have to replace it accordingly) and add a my_module.services.yml file to its root directory.

Within this file you can define your own breadcrumb builder service. Make sure to let Drupal know, that it is a breadcrumb builder and in which order it should be processed by adding the relevant tags (read more about service tags here):

services:
  my_module.breadcrumb:
    class: Drupal\my_module\Service\MyModuleBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 10001 }

Now that Drupal knows about your breadcrumb builder and will process it fairly early because of the high priority given, you will have to create the according class.

Create a service class MyModuleBreadcrumbBuilder.php in your my_module/src/Service/ folder. Apart from the convention to letting its name end on BreadcrumbBuilder, you can actually name it to your liking. Just make sure to change the class name within the .services.yml file and the follwing example accordingly.

As you are up to creating a taxonomy breadcrumb builder, a good starting point is the TermBreadcrumbBuilder of the taxonomy core module, which we will extend in our example:

namespace Drupal\my_module\Service;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\taxonomy\TermBreadcrumbBuilder;

/**
 * My custom breadcrumb builder for Animalia.
 */
class MyModuleBreadcrumbBuilder extends TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {

}

As your requirements seem to apply to a certain taxonomy vocabulary only, you should implement the BreadcrumbBuilderInterface::applies() method to check whether you are on a term page of that vocabulary.

This assures your breadcrumb builder won't run on other entities/vocabularies that don't feature your custom field (I used the ID my_vocabulary for your vocabulary; you will have to replace it accordingly):

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\taxonomy\TermInterface;

[...]

/**
 * {@inheritdoc}
 */
public function applies(RouteMatchInterface $route_match) {
  return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
    && ($term = $route_match->getParameter('taxonomy_term')) instanceof TermInterface
    && $term->getVocabularyId() == 'my_vocabulary';
}

The next step is to implementing the BreadcrumbBuilderInterface::build() method, that returns the actual breadcrumb. Here, we'll add your custom field value to the shown parent term link labels.

As we extended the taxonomy breadcrumb builder before, we already have the entity manager and term storage available, which enable us to loading the localized versions of the terms.

Most of the proceedings match the TermBreadcrumbBuilder::build() method, so that I added a comment only where the term field value is added:

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;

[...]

/**
 * {@inheritdoc}
 */
public function build(RouteMatchInterface $route_match) {
  $breadcrumb = new Breadcrumb();
  $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
  $term = $route_match->getParameter('taxonomy_term');
  $breadcrumb->addCacheableDependency($term);
  $parents = $this->termStorage->loadAllParents($term->id());
  array_shift($parents);

  foreach (array_reverse($parents) as $term) {
    $term = $this->entityManager->getTranslationFromContext($term);

    // The 'magic' happens here by loading the field value and
    // adding it to the link title; alter 'field_common_name' to
    // match your custom field ID.
    $my_field = $term->get('field_common_name');
    $term_name = $term->getName() . (!empty($my_field->getValue()[0]['value']) ? ' (' . $my_field->getValue()[0]['value'] . ')' : '');

    $breadcrumb->addCacheableDependency($term);
    $breadcrumb->addLink(Link::createFromRoute($term_name, 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
  }

  $breadcrumb->addCacheContexts(['route']);
  return $breadcrumb;
}

After enabling the module (or flushing the caches, if you already enabled it before), you should now see your custom breadcrumbs when you open a term of your vocabulary.


Looking at the code for menu_edit_item_validate(), which is the function that validates the input from the user when creating a new menu item, you will notice it calls drupal_valid_path(). If that function is not enough, you could look at the code of menu_edit_item_validate() to see if that code can be useful to create your own validation function.

  $normal_path = drupal_get_normal_path($item['link_path']);
  if ($item['link_path'] != $normal_path) {
    drupal_set_message(t('The menu system stores system paths only, but will use the URL alias for display. %link_path has been stored as %normal_path', array('%link_path' => $item['link_path'], '%normal_path' => $normal_path)));
    $item['link_path'] = $normal_path;
  }
  if (!url_is_external($item['link_path'])) {
    $parsed_link = parse_url($item['link_path']);
    if (isset($parsed_link['query'])) {
      $item['options']['query'] = drupal_get_query_array($parsed_link['query']);
    }
    else {
      // Use unset() rather than setting to empty string
      // to avoid redundant serialized data being stored.
      unset($item['options']['query']);
    }
    if (isset($parsed_link['fragment'])) {
      $item['options']['fragment'] = $parsed_link['fragment'];
    }
    else {
      unset($item['options']['fragment']);
    }
    if ($item['link_path'] != $parsed_link['path']) {
      $item['link_path'] = $parsed_link['path'];
    }
  }
  if (!trim($item['link_path']) || !drupal_valid_path($item['link_path'], TRUE)) {
    form_set_error('link_path', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $item['link_path'])));
  }

If you need to verify if the anonymous user has access to the menu item, you can use code similar to the following one:

drupal_save_session(FALSE);
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

$result = drupal_valid_path($link, TRUE);

$GLOBALS['user'] = $original_user;
drupal_save_session(TRUE);

To change the code I shown from menu_edit_item_validate(), you should rewrite the last control statement as the following code.

  drupal_save_session(FALSE);
  $original_user = $GLOBALS['user'];
  $GLOBALS['user'] = drupal_anonymous_user();

  if (!trim($item['link_path']) || !drupal_valid_path($item['link_path'], TRUE)) {
    form_set_error('link_path', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $item['link_path'])));
  }

  $GLOBALS['user'] = $original_user;
  drupal_save_session(TRUE);

This is the only possibility you have, if you don't want to rewrite all the code Drupal uses to verify if a user has access to a menu item, as that code verifies the currently logged-in user has access to the menu item, not a user for which the user object is passed to the code.


Undo/Cancel in individual vote

Head over to relative path /admin/structure/rate, and use the edit link for the rate widget for which you want to be able to Undo/Cancel a vote.

Next, within /admin/structure/rate/id/edit (with id corresponding to the widget you selected), scroll down to the section titled "Interaction". There you'll be able to change the value for "Should a second click on the same button delete the vote?" from "No" to "Yes". Save your changes, and repeat for each of the rating widgets for which you want to enable this facility.

Set or delete votes for selected roles

There doesn't seem to be a Drupal interface for this. However, you may want to use the Services Voting API, which provide Services endpoints (actions) for Voting API module. From its project page:

  You are allowed to get votes as flexible as Voting API allows it.
  You are allowed to set votes as flexible as Voting API allows it.
  You are allowed to delete votes.

From its README.txt:

  After enabling the module as usual...

  Go to admin/people/permissions
  Enable the following permissions for your desired user role(s):

  Retrieve votes
  Set votes
  Delete votes

  Go to admin/structure/services
  Click 'edit' next to your endpoint
  Enable the following resources under the 'votingapi' service:

  select_votes
  set_votes
  delete_votes

And the issue about How to use this services resources? contains an interesting (JSON) samples about how to actually set votes*.


Change Drupal Views Rows before they were rendered

A custom module which implements hook_views_pre_render() will give your that ability:

<?php
MYMODULE_views_pre_render(&$view) {
  if ($view->name=='myview') {
    // limit the results to 3
    array_splice($view->result, 3);

    //other modifications can be done as well:
    foreach($view->result as $r => $result) {
      // do something
    }
  }
}

to find a specific row you'll have to code a bit, but that's not drupal related, check https://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php for further informations.


Remove every Javascript except own theme scripts

In your template.php you can override the generation of $vars['scripts'] to be just your file.

However, I suspect that this is a really bad idea and may have a lot of consequences.


Better Exposed Filters and a Node Relationship

I don't think this is related to the relationships. It looks like Drupal core date fields (post, changed, etc.) are not getting the proper BEF options, namely the datepicker. That's a bug in BEF -- it was mentioned at the end of this issue, but I never saw that because that issue is closed. Feel free to post a bug in the BEF issue queue for this.

Thanks.


drupal 7 remove logon & password for anonymouse users

Go to admin/structure/block and look for the user login block set Region dropdown to none. If you are using the default Drupal theme, it would be under sidebar first category

UPDATE

but users can still create new accounts from /user page. To disable this, go to

configuration -> people -> account settings -> registration and cancellation and set "Who can register accounts?" -> "Administrators only".


How do I replace comma with a line break in a views field?

You can use the options_form() method on your field handler to provide a setting. That setting could be a text field in which you enter separator to be used, , or
 or whatever you need. Or that setting could be a select list that contained only , and
 options.

Here is an example of an field handler that uses that method:

http://cgit.drupalcode.org/views/tree/modules/node/views_handler_field_node_link.inc?h=7.x-3.13

The key pieces are the options_form()

  function options_form(&$form, &$form_state) {
    $form['text'] = array(
      '#type' => 'textfield',
      '#title' => t('Text to display'),
      '#default_value' => $this->options['text'],
    );
    parent::options_form($form, $form_state);

    // The path is set by render_link function so don't allow to set it.
    $form['alter']['path'] = array('#access' => FALSE);
    $form['alter']['external'] = array('#access' => FALSE);
  }

and then the usage of the option

  $text = !empty($this->options['text']) ? $this->options['text'] : t('view');


Views - Excluding a nid screws up "More" link

Add "Content: Nid (Nid)" field and mark it 'Exclude from display'.
Now add "Global: Custom text" field, in its configuration add 'More link' into text box and then select "Output this field as a link" under REWRITE RESULTS and provide node/[nid] as a link path.


You need

a hook_menu() implementation that will provide you with the url:
a page callback funtion that does print() or echo on the html snippet, then exit(). So no drupal_to_js() or drupal_json().


Thickbox -- nothing to do with Drupal -- is no longer supported. I highly recomend using Colorbox. (On Drupal)

(edit) The problem doesn't have anything to do with a modal image viewer. I inspected the code to find the URL of each image and they don't work. Chances are that the images are not being uploaded complete because of an upload limit or they are too large for image cache to successfully manipulate.

In php.ini make sure that:

max_execution_time to around 120 and
realpath_cache_size to 512K, 1M or even 2M.
max_input_time to around 120.
post_max_size = 12M to 16M (or large enough for your images)
upload_max_filesize = 12M to 16M (or large enough for your images)

In the content type widget configuration make sure that Upload Max size is set accordingly.


Calling another function using drupal_get_form

$form['#submit'][] = 'myform_form_submit';

You can call your function as above. Or

function myform_form_submit($form, &$form_state) {
  //execute your function here
}


hook_form_alter() "og_group_ref" editable field's #options?

It's not a form alter but it's an easy solution using rules.. I added a second entity reference field that only listed the nodes I wanted. Then I used two rules to make sure the two fields always match, whichever is updated.

This is one of the rules for when og_group_ref changes. The other one is the same except for when the second entity reference field changes.

Why am I posting this as a solution when it's different to the question? Because it's very quick, most people use rules and it's applicable in many situations.


How do I show product attribute fields in a view?

Answer borrowed from my answer over here.

Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display_suite or panels to get more advanced control over what your products look like when rendered.


Why are DIVs in the wrong order in Zen theme

I'd guess it has mainly to do with SEO.

From SEO Tutorial:

  In the HTML code for the page, the body text should be as close to the
  beginning of the code as possible, because there is a limit to how far
  down into a page a search engine spider will go to try to find text.
  So make sure your text comes before some really long JavaScript menu
  in the code for the page, or else the search engine won't make it far
  enough into the page to index the text. The search engine spider may
  never see the text if it is buried way down at the end of the code.

From 27 Quick Tips to Top Search Engine Rankings:

  If you have a persistent (on most or all of your pages) navigation bar at the side of each page, your table is almost certainly set up in
  such a way that it pushes your page's body text down the HTML
  document. Search engines give prominence to keywords nearer the
  beginning of a HTML document. So, design your HTML table so that the
  navigation bar is placed after your main body text.


It may or may not be important to understand, but Panels does not handle menues at all, it only deals with the layouts their UI. Page manager, a part of Ctools, however does handle menues, which is probably what you are using.

To figure out where the issue is:

Start by going to admin -> structure -> menues and check, is the expected menu entry in the right menu?  If so, go to step 2. If not, you have a miss-configuration or bug in Page manager.
Page manager seemingly has done it's part, and now the question is, how do you render the menu on the different pages? Do you output the menu at all on the page where it doesn't show up?


maybe you can add this to your if condition:

if($view_mode == 'full' && node_is_page($node)){
   //your code here
 }


How to change (re-order) the deltas programmatically in node_presave

You would want to set the field value to an array in the order you want them. Since you are doing this inside hook_node_presave, you don't have to bother saving the node. It will be done for you.

Something like this should work:

$values = $node->get('field_mv')->getValue();

... your sorting function ...

$node->set('field_mv', $values);


How to print only src path of taxonomy image

A quick look at a download of the current version of the module (1.7) shows that there is a function based on the $tid that returns a lot of formatted and unformatted information:

/**
 * Function to get an image object with more useful data for custom formatting.
 * @param
 *   $tid - the term tid.
 * @return
 *   image object.
 */
function taxonomy_image_get_object($tid, $recursive = NULL)

with one of the things being returned being the url to the image.  Assuming this function exists in your version, would this work for your use case?  If so, there is even a helper function available as well:

/**
 * Function to get a url for an image, for use in css, html or other client-side code.
 * @param
 *   $tid - the term id
 * @return
 *   The url string.
 */
function taxonomy_image_get_url($tid) {
  $image = taxonomy_image_get_object($tid);
  return $image->url;
}


Views 2 - Embed a View inside Empty Text of another View

In D7, Views 3 you can enable "NO RESULTS BEHAVIOR" which is under the "Advanced" tab.  Here you can add "Global: View area" (or just "hello world" as a text area for testing) which will allow you to display a view when there isn't any results.

If you want this is code, you can always export the View after it is configured and see how it was done.


Status report for Commerce Kickstart 7.x-2.41 reads Not supported

This is a common problem. The best solution, but not necessarily the easiest, is to use drush. You can find the instructions at Installing & upgrading Drupal Commerce under the "Updating your files" section.

tl;dr

Here’s the workflow. Be sure to backup your files and database first!

Move your /sites folder, .htaccess and all non Drupal stuff out of your docroot
Delete your old commerce_kickstart installation. Your docroot folder should be empty.
Run drush dl commerce_kickstart. It will fetch and intall the latest commerce_kickstart version
Move back your /sites folder, .htaccess from above
Run drush updatedb -y


New node created on one site automatically created on others?

Isovera wrote a good article on how to do this "Syndicate content between Drupal"

You'll need Views and Feeds at a minimum to get started.

In views you'd create an RSS feed (there are several views modules available to help with this) for the data you'd like to share between sites. You would then set up Feeds to import your newly created RSS feed. You can map each field from your feed to the content type you'd like to import into. Feeds can be configured to run on cron, allowing content to be imported from one site to another.


Delegate user administration to a limited set of users

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


How to move the form label into the input field on all node edit forms

I overrode the form in the template.php

$form['title']['#attributes'] = array(
  'onblur' => "if (this.value == '') {this.value = '".$form['title']['#value']."';} this.style.color = '#333333';",
  'onfocus' => "if (this.value == '".$form['title']['#value']."') {this.value = '';} this.style.color = '#333333';"
);


Saving 1 vocabulary deletes all terms of all vocabualries in the site | Data mining

You should look into the database if the taxonomy terms are deleted indeed or just have changed the tid, the language or anything else.

The most probable is the terms are not deleted but when you try to load them by some parameters the parameters has changed and the result is no terms.


Redirect to referring page after form submission

You can't rely on the referrer header, because clients can refuse to provide one. For this use case Drupal has implemented a query parameter destination. Configure the webform with a default Confirmation URL, like <front>, and then add the current url as destination query string to links pointing at the webform.

For example add a feedback link to nodes:

use Drupal\Core\Url;

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mymodule_preprocess_node(&$variables) {
  $variables['content']['feedback'] = [
    '#type' => 'link',
    '#title' => t('Feedback'),
    '#url' => new Url(
      'entity.webform.canonical',
      ['webform' => 'feedback'],
      ['query' => ['destination' => Url::fromRoute('<current>')->toString()]]
    ),
    '#cache' => ['contexts' => ['url.path']],
  ];
}

This overrides the configured confirmation URL and returns to the referring page after the webform is submitted.

In a page template you don't need the cache context and you can use this Twig only solution, as @PaulH has suggested:

href="/form/feedback?destination={{ path('<current>') }}"


Edit all of your footer's child menu links and check-mark on each of them show as expanded.


communicate new/changed values between taxonomies

Unfortunately you are probably stuck writing your own module. You need to implement hook_taxonomy_term_update and hook_taxonomy_term_insert.  In each you can check the item being updated and force a change on any associated terms in the other taxonomy.

The one thing to be careful of is an update spiral. Forcing an update on associated terms will then force an update of the original term, because it is now associated.  Because the changes in those two hooks are not committed to the db until the whole mess resolves it will lock up unless you put in a variable to keep it from spiraling.

For example:

if ($term->tid == args(2)) _update_related_terms($term);

should check the term being updated against the current page.  If they do not match it won't fire. (I haven't tested this snippet, so test thoroughly!)

Then in _update_related_terms

function _update_related_terms($term){
  $associated_terms = $term->associated_term_field;
  if (isset($associated_terms['und'][0]['tid']) && $associated_terms['und'][0]['tid'] != ''){
    foreach ($associated_terms['und'] as $key => $value){
      if (isset($value['tid']) && $value['tid'] != ''){
        //check the associated term here.  You could load it, or check the db, or all sort of things
      }
    }
  }
}

I know I am using und in this example, but it is off the cuff.  Again, not tested

Please note: this example is for d7.


Import Data with Commas into Term Reference Field

Using the Feeds Tamper module, you can explode that field, then use ", " (comma space) as the separator.


'Userpoints Transactions: Description' doesn't appear in Views

There is no 'Reason' field: it is named 'Description'. When you're creating a new 'Userpoints Transaction' view, you can simply add a 'Userpoints Transactions: Description' field and everything should work out fine.

Edit: I've imported your view and everything works fine on my website. Try reinstalling the User Points and the Views modules and clear caches. Hopefully that solves your problem.


You can do this but its probably more of a jquery problem than a Drupal one since you're changing the background of the page based on an asynchronous web call. Rough idea of how this would look:

attach an onsubmit handler to your form that would load the video from the url
add your logic to find the artist from this url (?) and then find the appropriate image
then modify the body background using this image, ex:

$('body').css('background-image', 'url(' + imageUrl + ')');


How to break up long words in a views display?

There are no universal solutions to this issue. But the currently acceptable ones are to use the wbr HTML tag (perhaps with some JS), or to, as you have seen, use break-word (as opposed to Chrome's break-all) along with some fallbacks. Both of these solutions are proposed here. Drupal.org uses or used to use the word-wrap: break-word; solution.


Hudri's comment ultimately led me to the answer, so huge thanks!

The real issue is the mismatch between the file's real size on the server and the size Drupal stores in the file_managed table, filesize column. Firefox will only download files that have matching values for the HTTP response's Content-Length header and the real length of the file sent to the browser. As to why the value's greater than the real one I'm still finding the answer to.


As reported in New render element #type 'table' and theme() renamed to _theme() and should not be called directly, the equivalent of $table = theme('table', array('header' => $header, 'rows' => $rows)) for Drupal 8 is the following.

$form['table'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

(Replace $form with the variable containing the rendering array.)


How to print a flag in a block programmatically?

You are adding raw PHP code as block content; you should execute it directly instead.

Try this:

$block['content'] .= flag_create_link('mymodule_interested', $node->nid);

UPDATE

You were using Flag API v1, instead of v2. Below is the full code:

function get_involved_block_info() {
  $blocks = array();
  $blocks['get_involved_block'] = array(
    'info' => t('Get involved block'),
    'weight' => 10,
  );

  return $blocks;
}

function get_involved_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'get_involved_block':
      global $user;
      $node = menu_get_object();
      // First of all, if the user is the author, do not show this node.
      if ($node && $node->uid != $user->uid) {
        $block = array();
        $block['subject'] = t('Get involved');
        $block['content'] = flag_create_link('get_involved_interested', $node->nid);

        return $block;
      }
    break;
  }
}

function get_involved_flag_default_flags() {
  $flags = array();
  // Exported flag: "Interested".
  $flags['get_involved_interested'] = array(
    'entity_type' => 'node',
    'title' => 'Interested',
    'global' => false,
    'types' => array(
      0 => 'ad',
    ),
    'flag_short' => 'Join',
    'flag_long' => 'I want to join',
    'flag_message' => 'Your interest was registered',
    'unflag_short' => 'Cancel',
    'unflag_long' => 'Cancel my interest',
    'unflag_message' => 'Your interest was deleted',
    'unflag_denied_text' => '',
    'link_type' => 'toggle',
    'weight' => 0,
    'show_on_teaser' => false,
    'show_on_form' => true,
    'status' => false,
    'locked' => array(
      'name' => 'name',
      'types' => 'types',
      'global' => 'global',
    ),
    'module' => 'get_involved',
    'api_version' => 3,
    'import_roles' => array(
      'flag' => array(),
      'unflag' => array(),
    ),
    'show_in_links' => array(
      'full' => true,
    ),
  );

  return $flags;
}


Since you're not declaring an access callback, the access callback defaults to the user_access() and passes your access argument into it based on the hook_menu().

Now, when we check the code of user_access(), we notice the following code.

// User #1 has all privileges:
if ($account->uid == 1) {
  return TRUE;
}

So the first created admin account will always have access. You then said:

  But I could not able to prevent other Role's users that has access to
  admin pages from accessing its configurations,

If you added another user with the Administrator role, and the permission is unchecked for the Administrator role in the Permissions page, your code should work and I can confirm it. So please check if:

You have the permission unchecked
You have cleared all caches or maybe just the menu cache
The admin user you are currently using to test the page's access is NOT the first admin user created


I was wondering the same and maybe this code is related:

function refreshless_page_attachments(array &$page) {
  $request = \Drupal::request();

  // Refreshless is only sensible when there is an actual session (otherwise the
  // entire page can be cached by the page_cache module, and be sent more
  // quickly than Refreshless could).
  // @see \Drupal\big_pipe\Render\Placeholder\BigPipeStrategy.
  $session_exists = \Drupal::service('session_configuration')->hasSession($request);

  $page['#cache']['contexts'][] = 'session.exists';
  if ($session_exists) {
    $page['#attached']['library'][] = 'refreshless/refreshless';
  }
}

It could be that for anonymous user the library is not loaded at all(check the comments in the function).

However I am not 100% sure.

Update: if you log in, you can see that refreshless.js is loaded.


How to make the module Node Embed work for any content type?

SOLVED!!! The body text was rendered through a view, and therefore it did not show the node embed content! So I changed it to "Node being viewed" Body....and there it was :)


How to pass theme variables in #theme in a form element?

Minor syntax change required...

function storeinv_uc_product_description($product)      {
  $description = array(
    'pickup' => array(
      'product' => array('#type' => 'value', '#value' => $product),
      '#theme'  =>'storeinv_pickup',
      '#weight' => 1,
    ),
  );
  return $description;
}

Your product variable doesn't need to be prefixed with a hash character. Thats used for specific keys/properties of the render array.


Adding a button to a form that links to an external URL

You should use $form_state['redirect'] to redirect in form submit instead of drupal_goto
,I mean

function MYMODULE_change_pass_submit($form, &$form_state) {

  $form_state['redirect'] ='https://example.org';
}


Thanks to comments and doc , i have moved the whole module in modules/custom/ and for info file:

name: 'amu hal'
type: module
description: display publications from HAL
core: 8.x
version: 8.x-3.0
package: AMU
project: amu_hal
'interface translation project': amu_hal
'interface translation server pattern': modules/custom/amu_hal/translations/amu_hal-%language.po

Placing the po file at

  modules/custom/mymodule/translations/mymodule-fr.po

now i could update the translation at

  /fr/admin/reports/translations

and make string translations

Note that the same po file is not found if the module is placed in sites/mysite/module


Unable to add patches via composer when we run "composer install" or "composer update"

The solution was
composer require cweagans/composer-patches

we need to be sure that above package is included
After adding the above I was able to add patches via composer.json


How do I redirect example2.com to example.com

There are many ways to do this. I just give you the most straightforward (of course for me!) and simplest one.

In hook_preprocess_html use this code

THEME_preprocess_html(&$var){
      $host = $_SERVER['HTTP_HOST']. request_uri();
      if(strpos($_SERVER['HTTP_HOST'],'example2') !=false)
           header("location:example.com/".request_uri());
}

I can't test this code right now, but this is the main idea:

Get current url components separately, the host ($_SERVER['HTTP_HOST']) and what comes after it (request_uri()), if its $_SERVER['HTTP_HOST'] contains example2 as a substring, then redirect the user to example.com/request_uri()

For redirection you can also use drupal_goto or anything else you want I just gave you the pure PHP.


How to convert Rules 'text' data type to 'text_formatted' type?

I tried fixing this myself but I'm not sure if this is the best.

I took a peek at entity/includes/entity.property.inc and found the definition of entity_property_text_formatted_info() enough for me to define it properly.

I simply wrapped the plain 'text' with an array definition of a

    $text_formatted = array('value' => $text_plain,
                            'summary' => $text_plain,
                            'format' => 'full_html');

And fed $text_formatted to the event invoke call.


Seems you're looking for the jEditable inline content editing module. I tried this module for one of my project and working fine.

Using this module you can do inline edits for individual fields. you can make inline edits at node output and views output too.

Note: Right now There is only dev version available  for Drupal 7x so make sure to install and test on local instance first.


How do I add view header content in code?

Use hook_views_pre_render().

/**
 * Implements hook_views_pre_render().
 */
function cv_views_pre_render(&$view) {
  // dpm($view); // dpm view here to see its properties.
  // and replace $view->name and $view->current_display with actual values from your view.
  // Note that my example uses Global: Text area for header, that's why I use $view->header['area'].
  // Other options available for header have different names. Try to find one that you use.
  if ($view->name == 'homepage' && $view->current_display = 'homepage_page_display') {
    $view->header['area']->options['content'] = t('TEST message');
  }
}


Creating a custom module for this in Drupal would be quite easy if you focused on your specific use case.  You can find more info on that here:
https://www.drupal.org/docs/8/creating-custom-modules

More specifically, you may want to look at a custom block implementation:

https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks


D7 Custom Module: Turning tabs into contextual links

Place the for loop inside an if statement

$tabs = menu_primary_local_tasks();
if($tabs)
{
      foreach( $tabs as $tab ){
          $element['#links'][$tab['#link']['path']] = array(
            'title' => $tab['#link']['title'],
            'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
          );
      }
}


How to show language specific search result in Solr search

use entity translation ...Regarding Entity Translation introductions:

Enable language fallback
Display shared labels
Select which entities can be translated: Node;Commerce product
Details for Commerce product: Selected Author's language and no
checkboxes at all

Languages selection/detection (admin/config/regional/language/configure):

Selected/added all necessary languages, still leaving English as
default, manually added en prefix for English default, to make clear
separation, as I am using prefix for language separation
User interface text language detection: URL; Default
Content language detection: Interface (moved to top manually); URL;
Default

Commerce product type settings (admin/commerce/products/types/product/edit):

Enabled via Entity Translation

admin/commerce/products/types/product/fields
Replaced regular Drupal Title field with Title module, and in this
field settings checked, that this is the only field in Product type
I'm going to allow translation.

Product display node content type settings from admin/structure/types/manage/{your-display-type}
Published options > Multilingual support - selected: Enabled, with
translation (NOT Enabled, with field translation, as I'm going to use
i18n for language and node separation).
My title field in this display node, which is overridden by Title
module is left for field translation, as these are per field
settings, not per content type.
There are no any other fields let for entity translation in product
display node, even product reference field (used with inline entity
form).

Basically that's all. Taxonomy term translation is handled by i18n modules and Taxonomy vocabulary has Translate... (NOT Localize...) settings - different name for each language tied into translation sets.


How to export all users with all custom fields?

You can use the Drush Entity module:

  With drush entity you can query the entity system available for Drupal
  8, 7 and (some of) 6.

Getting all users with some fields:

drush entity-read user `drush entity-read user` --fields=uid,mail,name,created,access,login

Getting one user with all the fields:

drush entity-read user 1 --fields=* --format=json

Getting all the users with all the fields:

drush entity-read user `drush entity-read user` --fields=*

Getting some users with some fields:

drush entity-read user 1 2 --fields=uid,mail,name,created,access,login --format=export

Output (for the last command):

 1  mail@gmail.com  admin  1353518169  1470089957  1469713365
 2  other@gmail.com  webadmin  1353518169  1470089957  1469713365

If you want to try with another options you can read this page: http://build2be.com/content/drush-entity-support-patch-needs-review


Application of patches after core/module updates

If you find yourself doing this often then it might be beneficial to use a make file for the project. Then you can have your make file contain all the patches and just rebuild the codebase instead of updating in place.

Also, be sure to mark patches that you are using in production as "Reviewed and tested by community" this will make them more likely to be committed to the next release which will stop you from having to include that patch in the future.


How to print formatted contents of Viewfield in a custom template?

I used the following code:

<?php print views_embed_view('myviewname','block_1', $node->nid); ?>
<?php print views_embed_view('myviewname','block_2', $node->nid); ?>

And the view's info is printing just fine now in my tpl files. Hope this can help someone in the future.

Thanks for Worldfallz on the Drupal forum for this suggestion!
https://drupal.org/node/2075411#comment-7800227


You can add a contextual filter "Content: Author uid" which defaults to "User ID from logged in user". Or you could also try to add a relationship to the author of the content and compare it's uid to the uid of the logged in user.


From the code you can use hook_services_request_postprocess_alter() to alter whatever you want from your response.

You can always use arguments to make your changes more specific:

function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  // In my response, I include the request string in the '_links' array.
  // I can use this now to determine which resource was requested.
  if (strpos($result->_links['self']['href'], 'api/1.0/widget')) {
    // Now I know I'm dealing with a widget request, so I'll
    // add the random string here...
    $result->String = "This is a string that I'm adding to the widget response";
  }
}

As result you can see in your response:

Array (
  [_links] => Array (
    [self] => Array (
      [href] => /api/1.0/widget/12345
    )
  )

  [count] => 1
  [_embedded] => Array (
    [0] => Array (
      [id] => 12345
      [type] => widget
      [path] => /node/157601
    )
  )
  [String] => 'This is a string that I'm adding to the widget response'
)

Read more Drupal: Alter API response with Services API, where is this example was taken from.


There is a really simple work around for this.
You can add a button or a hidden input field with an ajax callback and trigger this callback by jQuery.

So declare your button:

$form['my_button'] = array(
   '#type' => 'button',
   '#ajax' => array(
     'callback' => 'my_callback',
     'event' => 'hs_changed',
   ),
   // hide the button and set a unique id:
   '#prefix' => "
",
   '#suffix' => "
"
);

In your javascript you can then easily trigger the event with jQuery.trigger:

jQuery("#my_ajax_button input").trigger('hs_changed');

This will trigger your ajax callback.

http://api.jquery.com/trigger/

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax


Drupal's search platform is rudimentary one. You can't really extend it, best you can do is to replace it. Most popular free platform now seems to be Apache Solr, connected to Drupal with Apache Solr Search Integration.

If Solr's to much, Search API integrates with views pretty neat, you can have one field for search and other as Views filters.