How to override views-view-field.tpl.php in custom module?

You should add the template file on your module info file:

name = My Module
description = Create custom views template.
package = Views
dependencies[] = views
core = 7.x

files[] = mymodule.module
files[] = includes/mymodule.views.inc
files[] = includes/views-view-field--views--ticker.tpl.php

version = "7.x-4.1"
core = "7.x"
project = "mymodule"
datestamp = "1311290520"


I think the best option here is to actually let Panels take care of this. Install panels, create a variant of the node view panel for the specific node type(s) you want, and then place the view on the panel page. There are a few other options (hook_menu_alter(), using hook_url_alter() to rewrite the node links rather than using pathauto), but I would definitely go the panels route.


The Quick Tabs module may meet your needs.

  The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content... Once created, the Quick Tabs blocks show up in your block listing, ready to be configured and enabled like other blocks.

You would create a Quick Tabs instance (Admin > Structure > Quicktabs) with the views blocks you want to display. You are able to configure URL arguments to pass to the block's contextual filters.

Then display the block of the Quick Tabs instance on the user page.

There are various tab styles offered by the module or you can style the tabs with your own CSS.


How do I redirect access denied to front page?

Instead of <front> try using node or 'home page path' if you have customized home page.

...in the 403 field under admin/config/system/site-information.

Ref: Redirect 404 errors to home page?


View with content from Media gallery links to node not working

Looks like you probably have spaces in the field [title], try using the nodeid check it works first then come back.

If you have pathauto you could then use this to rewrite the URL to an aliased URL.


Adding icons from the right or left to menu H2 or Li

What a coincidence. I made good use of this module today because I needed to have bolded text in my menu items:

https://www.drupal.org/project/menu_html

After enabling you'll get a checkbox on each menu item that allows you to add HTML to the menu title (anything inside the anchor essentially). So this is where you would put your <img> tag or the markup necessary for your icons.

Note for security, make sure only trusted users have the ability to use this option, as you can imagine it creates an opportunity to embed malicious code.

EDIT: OP asked how you might add icons using this technique. I would use an icon font. For example with Font Awesome you can put in some markup like <i class="fa fa-refresh"></i> and it will  use CSS to display the icon there. Font Awesome covers most bases. If you can't find something specific try icoMoon or Fontastic.

It's really up to you how you implement this. See the other poster's answer for a pure CSS solution.


If I've assumed your question correctly, you want to show the comment form when displaying the node content page. You can do this by enabling a setting "Show reply form on the same page as comments" in Comment field. Check screenshot below:

Edit Comment field

Enable "Show reply form on the same page as comments" setting checkbox and click on "Save Settings".


How to implement facebook feed which shows the latest facebook wall post

Why not use the facebook like box plugin? If you're just looking for a widget like capability on your site, this is the easiest and pushes the heavy lifting on to Facebook's servers without any more modules or extra PHP:

http://developers.facebook.com/docs/reference/plugins/like-box/

Play around with the options, you probably just want to show the stream. There are other options below to customize the output of this as well.


Replacing initial view of a panel with a content view

I Finally ended up showing both views, and having them hidden depending on the status of the exposed filters via Jquery.


You should be able to transfer the site wholesale, without too much fuss. After transferring, you may need to alter some paths (eg admin/config/media/file-system in D7) if the sites directory has changed paths relative to your Drupal codebase. Odds are you won't need to, though.

For a simple site, the layout will be something like this -

/var/www/index.php
         modules/                  } don't install modules here
         themes/                   } nor themes here
         includes/
         [many other Drupal core files]
         sites/
               default/            } all installed code
                       files/      } lives in the
                       modules/    } site directory
                       themes/     } and its children

For more complex setups you may need to understand multisite layouts, but for now hopefully this answers your question.


Custom module shows in list but not in permissions

You need to implement hook_permission to register any custom permissions that your module exposes.

Once you have implemented this hook you can then use your new permission in user_access or hook_menu.


Add a span and class to menu items that has children

Menu items with no children has the class="leaf". It is possible to style the menu items li (has children) and then cancel the rule-set for the class li.leaf (has no children).

A span can be added to all li's (set to display:none for leafs).
How do I insert a <span> </span> tag inside the <a> </a> tag on my main menu


You can use hook_ccs_alter

function yourmodule_css_alter(&$css) {

  unset($css['misc/ui/jquery.ui.core.css']);
}


When getting back to this issue I did notice the strange behaviour is gone after upgrading to the latest Drupal 8.6.3. All works as expected even using a button.

I am not able to reproduce the behavior/error from above.


You have not defined your theme function in hook_theme

 function yourmodule_theme() {
   return array(
     'wc_challenge_actions' => array (
       'render element' => 'element',
     ),
   );
 }


Adding fields via ajax in form does not show in arrays in form_submit

The form builder function is what Drupal refers to whenever it needs to rebuild the form. Parts of the form should not be built in the ajax callback. Instead, you can return them using something like

function add_img_upload($form,&$form_state) {
  return $form['img_mng'];
}

Your form builder has access to form state information, which allows you to build the form conditionally depending on the state of the form.


Is there an easier way to print taxonomies in the tpl? I get this working code, but it should be a "shorter" way!

Few things here:

Your SQL is open to injection
You're running a query that has already been run, and for which data has already been returned by the core field system. Drupal already runs way too many queries in a page load, adding another unnecessary one should be avoided wherever possible.
Your code should be in a template preprocess function (or module file as you've mentioned). But that's not because of the length of the code. It's because you should maintain a good separation of logic and display.
Drupal has already prepared the display of the field for you, so it would be preferable to use that instead of building up from scratch again.

With those in mind, try simply adding:

<?php echo render($content['field_name_of_term_ref_field']); ?>

in place of your code.

To control how those field items come out (e.g. as links), navigate to admin/structure/types/manage/TYPE/display, and choose appropriate settings for the display widget.


Publish node link to social media on content creation

Take a look at the twitter module:
https://drupal.org/project/twitter

You should be able to then use twitter to send that story to Facebook by hooking up your twitter account to your Facebook account. I'm not sure if the same is possible with linked in though.


So I found an issue about this in the privatemsg issue queue, basically they are overwriting the page title when the form is embedded like this. So you need to use the code below to save the title before the form call and then set the title back to the saved one afterwards.

// Save the title.
$stored_title = drupal_set_title();
// Call the form.
print drupal_render(drupal_get_form('privatemsg_new', $recipients, $subject));
// Set title back to the saved version.
drupal_set_title($stored_title);

Here is the link to the issue if you want to do more research: https://www.drupal.org/node/1621198


How do I assign different colors to each serie of a Google bar chart

It's hard to tell (without access to your site) what's causing your issue. But here is a working sample of a chart using the Charts API (disclosure: I'm a co-maintainer ...):

<?php
  echo '<p>&nbsp;</p>';
  $chart = array(
    '#type' => 'chart',
    '#chart_type' => 'column', // pie, bar, line, column, area, scatter
    '#chart_library' => 'google', // Allowed values: 'google' or 'highcharts'
    '#title' => t('Meals by store'),
   '#colors' => array('#006400', '#000064', '#640000', '#c11d0b'),
  );
  $chart['store1'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 1'),
    '#data' => array(16, 11, 13),
    '#suffix' => ' Meals',
  );
  $chart['store2'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 2'),
    '#data' => array(12, 14, 17),
    '#suffix' => ' Meals',
  );
  $chart['store3'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 3'),
    '#data' => array(9, NULL, NULL),
    '#suffix' => ' Meals',
  );
  $chart['store4'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 4'),
    '#data' => array(5, 10, 20),
    '#suffix' => ' Meals',
  );
  $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#labels' => array('Breakfasts', 'Light Meals', 'Sandwiches'),
  );

  // dpm ($chart);

  $example['chart'] = $chart;

 return drupal_render($example);
?>

If you have the (dangerous) PHP filter enabled, just paste it all in the body of node, and see what happens (make sure you have a working internet connection if you use the Google library).

It should show 3 column charts (1 for each type of "meal"), with each chart having up to 4 columns (1 for each "store").

BTW, make sure you're using the most DEV version (I'm using Version: 7.x-2.0-rc1+5-dev).


How to handle pdo exception error gracefully for user experience

What? ... add a custom FAPI validator to your forms so there is no out-of-range error.

You could build on, or start off by using:
http://api.drupal.org/api/drupal/includes%21form.inc/function/element_validate_integer/7


Custom POST Resource Not Working but GET is

This is the code we are using to determine the POST path:

    $create_path = isset($definition['uri_paths']['create']) ? $definition['uri_paths']['create'] : '/' . strtr($this->pluginId, ':', '/');
    // BC: the REST module originally created the POST URL for a resource by
    // reading the 'https://www.drupal.org/link-relations/create' URI path from
    // the plugin annotation. For consistency with entity type definitions, that
    // then changed to reading the 'create' URI path. For any REST Resource
    // plugins that were using the old mechanism, we continue to support that.
    if (!isset($definition['uri_paths']['create']) && isset($definition['uri_paths']['https://www.drupal.org/link-relations/create'])) {
      $create_path = $definition['uri_paths']['https://www.drupal.org/link-relations/create'];
    }

This would mean it is /snap_shots_resource as path, but you probably want to set a 'create' uri path to the value you want.


How do I get Location / GMap / Views setup to display non-US map nodes?

I can confirm that it is possible to get locations and GMAP running on Drupal 6 for Canadian addresses.  I have done this on more than one occasion.

From your description it simply sounds some setting preventing the reverse geocoding of addresses. Edit one of your nodes with canadian addresses and confirm that the Lat and Lon field are empty.  Save then edit again and confirm it is still empty.

If the lat/lon fields are empty try the following

Make sure you have a valid google maps API key for the URL you are running the site under.
Confirm that the location module has access to this API keys. Reverse geocoding settings for locations module is under /admin/settings/location/geocoding go to Canada and click "Configure parameters"   Or go there directly: /admin/settings/location/geocoding/ca/google  Your Gmap google map api key should be displayed.
Confirm that as a user you have permission to save lat/long info.  Under user permissions (/admin/user/permissions) go to "location module" and check that  "submit latitude/longitude" is selected for users that will be creating the nodes with address information. If not then there will be no reverse geocoding for any address, Canadian or otherwise.
Once you have confirmed the above, revisit a node with a Canadian address.  Edit and hit save. This will re-run the reverse geocoding.  If a lat/long is not saved then I will have to do some more digging. Also if you have lots of nodes in need of reverse geocoding, it is possible to do this programmatically.
Are you using CCK field or location module itself to save the address and lat/on? I am uncertain whether or not reverse geocoding works with the cck location field in D6.


Views Auto-Refresh giving ajax error after some time

It happened to me when views auto refresh ajax had not finished loading and I clicked on a link.

Here is a link to the drupal forum talking about this. https://www.drupal.org/node/1232416

I personally used the sandbox module in comment #183 to solve my problem.


Is Contact module the right choice for multiple ask a question pages?

Depends , you can use the webforms module to create custom forms it's better suited for creating forms than the contact module


How to output a large amount of html markup

You shouldn't output large amount of markup from your module without using the theme layer (unless your markup is actually editable content or large chunk of static content). So, the best is probably to define a theme function or template for your markup, and use it from your module. This way, any theme can change your markup without affecting your module logic. Even if this is supposed to be a single-project custom module, chances are that someday you, or somebody else, will have to update this site. Properly separating your module logic from its presentation will make things easier in the future.

// Rendering code
  $page['region'] = array(
      '#theme' => 'custom_foo',
      '#foo' => t('foo)',
      '#bar' => t('bar'),
      '#count' => 42
  );

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return array(
    'custom_foo' => array(
       'variables' => array('foo' => NULL, 'bar' => NULL, 'count' => NULL),
     )
  );
}

/**
 * Default theme implementation for custom_foo.
 */
function theme_custom_foo($variables) {
  $output[] = '';
  for ($i = 0; $i < $variables['count']; $i++) {
    $output[] = array(
      'type' => '#markup',
      'markup' => ($i % 2 == 0) ? $variables['foo'] : $variables['bar'],
    )
  }
  return $output;
}

For static content, you can use a template (.tpl.php) instead of a theme function. This allow you to keep it outside a your .module (or .inc) file code. Again, this will be easier to maintain in the future.

Also, most of the time you shouldn't put markup into t(). t() is for translatable strings and most markup are not to be translated. One common, an acceptable, exceptions is (simple) link markup.


sess_read() should not be used in a module, as that function is passed to session_set_save_handler() from _drupal_bootstrap(), which is the function that is called during Drupal bootstrap.
The purpose of the function is not to read values from the PHP session; if you need to do that, the you can just read the content from $_SESSION[].
To notice that session_start() is called from Drupal during its bootstrap; that means that after a full bootstrap (or any bootstrap that goes past the DRUPAL_BOOTSTRAP_SESSION phase) a session is initialized, and $_SESSION[] can be used.


You should use Pathauto if you aren't already.

This has a feature (tab) that lets you bulk update the content type urls to /widgets/[node:title].

You should also install the Redirect module, so that all your former /products/[node:title] automatically redirect to /widgets/[node:title]. This is for SEO purposes, you don't want your Google listing pointing to a broken link, non-existent page.


Control where a new field is stored in the database D7

This is no longer done in D7.
You will want to use a proper field (which is stored in its own table and has many benefits over a simple column).


How to get the unrendered contents of a block

The solution I went with is to use the template_preprocess_block() hook as it allows me to render the items as I see fit. The issue with using the block.tpl.php file is that it does not give you access to components that is used to render the block (as by this point in the process, it is already rendered).


alter/remove taxonomy term path if no related nodes

I would do that using hook_menu_link_alter() and Special Menu Items module, which provides special menu items like <nolink > and <separator>.


hook_page_alter to change title on user profile page?

This finally worked for me; it's essentially what was posted at http://drupal.org/node/1262070#comment-5038516, but with some function renaming and generalizing:

function YOUR_MODULE_menu_alter(&$items) {
    // Change the title of user profile pages to the user's name.  Gak.
    $items['user/%user']['title callback'] = 'YOUR_MODULE_user_page_title';
}

and then

function YOUR_MODULE_user_page_title() {
    if (arg(0) == 'user') {
        // Load uid from url
        $user = user_load(arg(1));
        // Get the full user name somehow; here, I'm calling a function of my own.
        $output = get_user_full_name($user);
    }
    // Fallback to username if no fields are present
    if (empty($output)) {
        $output = $user->name;
    }
    return $output;
}

But, come on.  It's nice that the hooks are there, but doing something like setting the title of a page REALLY shouldn't be this hard/obscure...


drupal 7 restful server VS seperate Restful server to access mysql. Can a restful server be on a subdomain

It really depends on what part of your Drupal site your REST service will be an interface to. The Services module provide a great and easy solution to expose parts of of Drupal core and some selected contribs data and feature as REST services. IT also provide a framework to build your own services.

By-passing Drupal in a separated service directly accessing the MySQL DB is only an option if you are accessing custom tables. Accessing nodes (ie. content) directly in the MySQL database is a bad idea. The DB schema to store the nodes is dynamically managed by Drupal (the Field API). It could change whenever you add, remove or edit fields or when updating Drupal. But the Field API is not the only one to manage node data, any module can contribute data to a loaded node or add behaviours on node CRUD operations. If you go directly to the database you loose all these added behaviours. The same is true for most data handled by Drupal.


How can I render plain text as HTML in a template?

A solution by iworkyon from the Drupal community:
field--node--[field name].html.twig:
{% if svg %}
  <div class="my-svg">
    {{ svg|raw }}
  </div>
{% endif %}

MYTHEME.theme:
/**
* Implements hook_preprocess_field().
*/
function MYTHEME_preprocess_field(&$variables, $hook) {
    switch ($variables['element']['#field_name']) {
      case 'field_svg_test':
        $variables['svg'] = $variables['items'][0]['content']['#context']['value'];
        break;
    }
}


Not able to access "Updates" page logged in as admin user

What worked for me was rebuilding permissions under "/admin/reports/status/rebuild" (Make sure to take a db backup).

Right after rebuilding, I saw all the available updates.

Thought this might be of help to someone.


There's a solution here http://www.only10types.com/2011/12/drupal-6-enabledisable-wysiwyg-editor.html

Basically, you need to alter this specific edit form. This is what I did for Drupal 7 (the blog post is for Drupal 6):

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  // Workaround to disable Wysiwyg just in this field.
  if ($form_id === 'FORM_ID_OF_EDIT_FORM') {
    $form['field_CUSTOM'][LANGUAGE_NONE][0]['#wysiwyg'] = FALSE;
  }
}

You may want to use $language->language instead of LANGUAGE_NONE.


Drupal 7 vertical tabs like the ones in Drupal 8

You can use a combination of the Node form columns module and the Renderable elements modules.

Node Form cols separates the node forms into two columns and a footer.
This module alleviates some of the problems with the mile-long node forms in Drupal. Other than that it gives you the possibility to use different weights and collapsed states for your forms than for your presentation.

Renderable elements is more complicated to use but lets you split out the parts of the vertical tabs part of the node edit form. For example, after enabling these two modules, do the following for the article content type:

Visit node/add/article to add a new article content type
Click the new link at the top of the form which says "Manage Form Display"
Tick all the items you want to break out of the vertical tabs. As an example choose "Publishing options", "Published", "Promoted to front page" and "Stick at top of lists"
Click save
Goto Structure -> Content types -> Article -> Manage form
Set the "Publishing options (Field group)" and "Save" to be in the right region and press save. nb. I had to use the drop downs here, it didn't seem to rememebr my region choices if I used drag and drop.
Visit node/add/article and see the collapsing publishing options block on the right.


For outputing image, you should use theme function, with image theming. And path argument inside.

For example:

$img = theme('image', array('path' => "path to image"));
// $img will containt the image tag.
// path can be relative from drupal root, or it can be 'files' path (public://image.jpg)

Read more about it, you can here: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_image/7

The power of Drupal in overwriting, so I suggest you to use theme way.


The way I accomplished this was to use Rules to detect when a user logs into the site and also when content is about to be viewed.

Rules provides a programmatic  area in the "DO" feature of the Rule. I execute some php code to detect the group the user belongs to and redirect using drupal_goto.


Caption box on my slideshow jumps when you refresh cache

This is a css problem, sorry. If I add position:absolute to my pagers block then the jumping stops, however, my pager block then appears under the text below the slide and the pagers cant be clicked on. I will follow up on stack overflow for css queries.


Drupal 6 Site Duplication - Looks Like My Theme is Broken

/sites/*/files/css/ and /sites/*/files/js should be empty just after migration - do not copy their contend. Clear them.
Before making original site database snapshot, turn off css and js aggregation. If you didn't, turn it off now. If you don't, the duplicated site will be looking for the aggregated content which may, or may not be available on the new site.
On new site, make sure /sites/*/files/ directories are writeable by your php scripts, and that php can delete files too.
Search all theme files for not-relative URIs. There shouldn't be any.
Fix one problem at a time. First, make it work without aggregation (most probably it's URI problem), and only then attempt to fix aggregation issues.
At the end, if you still have problem - disable and then enable theme. This should ensure all theme-related caches are regenerated and theme settings variables refreshed.


As long as Replace custom weights with dependencies in library declarations is not fixed, you have to use weights to control the priorities of JavaScript files.

 js:
   assets/js/GTMscripts.js: { weight: 10 }


You can just change the 1 to your particular variable in the loop.

Example:

foreach ($values as $k => $v) {
  print $node->field_carousel_ . $v . [0]['filepath'];
}

That should output the values you need.


How do we fetch the list of all content types refererencing a particular taxonomy vocabulary?

If you want to check from UI then maybe you can try the Field list page (/admin/reports/fields) for checking which all the places have the required taxonomy field has been referenced/used.


Creating a watchdog log when publishing status changes on my own ContentEntityBase

I would like to go for hooks (maybe events), hook_ENTITY_TYPE_update. You can find more about it in details here.

You only have to check if "status" field is being changed after update, and using the logging factory to put it into logs. This is also "form" independent (means it will run each time when entity gets updated), which is more general approach, and better for your system (more consistency).


Rebuild permissions needed after installation from profile

Finally it seems as it is done from the hook_install.


How to filter view by actual name of logged in user matches field?

Using this post: Views: Filtering nodes on the basis of logged in user role
I was able to filter with contextual filter based on php query for current user


Change the size of the form element for content title

You don't have the options of choosing your title field lengths in standard D7.
However, there is a module that lets you change that:

https://drupal.org/project/title_field_ui

The only problem is, that the module is only in alpha and not widely used. On the other hand, the module author is very reputable, so I'd give it a try.

Other solutions have been discussed before:
Change / Increase the node title length


Try using 2.0 version of docker4drupal, in the new version drush installed globally for www-data user to avoid potentials problems with permissions.


What can I remove after install of Drupal 7

Theoretically, yes if it's not enabled you can remove it... but why? You're not really saving a lot of space.


Does Drupal.t() inside JS file has the same restrictions as the PHP t()?

The string will show up in the translation interface if it is found by the js code parser. And a variable can't be worked on by the parser, it has to be a string. So

$(this).addClass('open').text(Drupal.t(settings.linkText));

can't show up.
It doesn't prevent the string to be translated though, if the js is aware by another way of the translation : if you write somewhere else in your js

Drupal.t('my_string');

then the parser will find 'my_string' to translate, and the js will load it next time it's called, and if settings.linkText happens to equals 'my_string', then it will be translated.

You have to flush the js cache after the js code alteration, so the parser can look again for strings. It may be why the

$(this).addClass('open').text(Drupal.t('@txt',{@txt:settings.linkText}));

doesn't show '@txt' in the translation interface.


How do I use a token to set the default value of a date field to the current date?

Leave the "set default value" button alone. Something about it makes it seem like a really good button to click for setting a default value, but you don't need it. Just enter the token in the default value input on the advanced tab and click save.

This seems simple enough in hindsight, and I'm not sure why it took so long for it to occur to me to try it. Hopefully if someone else has the same problem, this answer can help save them a few minutes, or perhaps even a longer period of time we won't mention here.


Considering your previous question and our conversation you left out quite some details ;)

The sidebar should appear on the band-page (and the child pages photo-albums, etc) only right?

Create a Views block (type: content) with a contextual filter Content: nid and choose Provide default: Content ID from URL.
Then under format make sure it is set to fields not to content.
Add a field Content: path and hide it from display.
Add a field Global: textarea, enable replacement tokens and use the path as a base path, so you enter all your urls like:

Photo gallery
Video gallery
...

This should give you a list of links that all use the path alias of the band-page node, and then attach another path item to it.

The only thing you won't have is an active trail, so the active page will not be highlighted in the menu. I don't know how to achieve that.

And finally make sure to only display this block on band pages and direct child pages, otherwise you'll get some strange links. Since you are using Sub-pathauto all links should continue to work even if you are visiting a child page, as long as you don't use a stand alone node as child (in this case the path will resolve to that node page).


Send email on changing line item field value

There are three approaches I can think of.

 Use a hook to alter the update function to send an email out based on your conditions.
 Add JS to handle the change via a custom AJAX call.
 Create a cron job that monitors changes in the database and emails out messages when changes are picked up.

The first two options are your best and from those, depending on skill level, I would choose one.


It doesn't look like a problem with beautytips module, but instead a lack of styling that's causing the problem. You should be able to fix this with normal CSS.


You could style that special page with css to not display the footer (display:none). Drupal delivers a css class in the body tag that identifies the current node, like so .page-node-x, where x is the node id of the page. So you could go like page-node-x .footer.

You could also use a page.tpl override for the specific page where you remove the footer region. Create a copy of page.tpl.php in your themes template folder and name it page--node--x.tpl.php. Remove footer in this file completely.

And as for fullsize background image, maybe this module could be interesting: https://www.drupal.org/project/supersized


Effecient modules which will give me users location and country information

Take a look at Smart IP.

  Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored at session variable ($_SESSION) with array key 'smart_ip' and Drupal $user->data object with array key 'geoip_location' of the user but optionally it can be disabled (by role) at Smart IP admin page.


Install the DrupalGap SDK on localhost, e.g. /var/www/drupalgap
Open its app/settings.js file, and point its site_path to www.mysite.com
Launch Google Chrome w/ security disabled and open http://localhost/drupalgap/index.html (if you're in web app mode, or use Ripple if you're in phonegap mode).

More information available here: http://drupalgap.org/node/223


Check query of view when you providing HF.00668 value in Object ID.

SQL query of views can be enable from views settings page with name of Show the SQL query.

You can also check operator value in exposed field settings.


Count the no of people who viewed a particular blog

Enable the statistics module and using views module create a mini report. Other modules you could use in combination with the statistic module are Visitors module and Counter module


Define multiple variables in a custom module using hook_variable_info()

I figure out this on my own. Hope will be useful for someone.

/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {

    // Use '[custom]' as a placeholder for the variable name.
    // It will set these properties ('type' and 'multiple') automatically.
    $variables['custom_vars_[custom]'] = array(
        'title'     =>  t('Custom multiple variable'),
        'group'     =>  'site_information',
        'repeat'    =>  array('type' => 'string', 'default' => 'some default value'),
    );

    // if you need to expose your custom variable as token
    // you have to set 'token' key as TRUE,
    // and ought to set the properties (name, description and type)
    // Notice that 'first' it's a name of variable defined in custom_variable_options().
    $variables['custom_vars_first'] = array(
                    'token' => TRUE,
                    'title' => 'Custom variable',                       // name
                    'description' => 'My first variable description',   // description
                    'type'  => 'string'                                 // type
                    );
  return $variables;
}

/**
 * Implements hook_variable_type_info().
 * @return
 *  An array of information defining variable types.
 *  The array contains a sub-array for each variable type
 *  with the variable type as the key.
 *  The possible attributes are the same as for hook_variable_info().
 */
function MY_MODULE_variable_type_info() {
    $type['custom'] = array(
        'title' => t('Custom variables'),
        'type'  => 'select',
        'options callback' => 'custom_variable_options',
    );
    return $type;
}

/**
 * Callback for custom options.
 * @return
 *  An array of variables with the variable name as the key.
 */
function custom_variable_options($variable, $options) {
  return array(
    'first'  => t('My first variable', array(), $options),
    'second' => t('My second variable', array(), $options),
    'third'  => t('My third variable', array(), $options),
  );
}

Want to see how it works?

Install Variable module
Enable: Variable, Variable store, Variable Admin
Place this code in your custom module (replace 'MY_MODULE' to your module name)
Clear caches.

Results:

admin/config/system/variable -> site information

admin/config/system/variable/group/site_information

admin/config/search/path/patterns


How do I install dependencies for commerce using the Composer manager module

Please refer to our installation instructions for Commerce 2.x here:

http://docs.drupalcommerce.org/v2/getting-started.html

Note that we recommend the Drupal console project, not drush. However, the linked Composer Manager instructions in there may help you do it via drush.


Us js file in a theme already use by a module

Okay this was easy...
I realise that the js file is in the library views_slideshow_cycle/jquery_cycle, created by the module.

So i just have to add it has a dependencies to my theme

mytheme
   dependencies :
     views_slideshow_cycle/jquery_cycle.


How to change the Drupal Commerce Stock formatter?

If you want to display the stock of a product with 4+ when it's >5, assuming that you've got stock a field attached to the product and exposed to the node display (default behavior) you can use hook_entity_view_alter or hook_node_view_alter to alter the #markup of $build['product:field_stock']


Can I use plupload to load multiple image files into a single image field

Add this js in your custom js file.

(function ($) {
  Drupal.behaviors.autoUpload = {
    attach: function (context, settings) {
      $('form', context).delegate('input.form-file', 'change', function() {
        $(this).next('input[type="submit"]').mousedown();
      });
    }
  };
})(jQuery);

It will automatically upload all the images on click of upload button using above Jquery.

for more information,look at this link. at http://drupal.org/sandbox/clivelinsell/1587560 .


Unable to send user-entered data to PayPal along with credit card info

From your above code i have seen that dpm($form) showing 2 fields. when you submit your data in form please ensure that your order is created or not. Becuase in your code you are getting customer order details and pass it to the array() (which is empty). Thats why it not going to Paypal website. Please check your custom code.

hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method):  What this function will do, it will alter the array before pass this data to paypal website. So you must ensure that array data you are passing to paypal is not empty or you can check the condition for it.


I used the taxonomy menu module on my latest project for this purpose, works like a champ!
Here is a quote about it (from the module's project page):

Transforms your taxonomy vocabularies into menus with ease!
Features:

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules


To get the query string use

\Drupal::request()->query->all();

To further dig into use kint() and debug the  \Drupal::request()


If you use the module Email Field to create your email field you can set the field to be displayed as a contact form. You will find the setting to turn the field into a contact form under Display settings for the field.


How to display the views page title in a custom fieldable block

Views sets the title configured in a Views page statically in the route definition. Get this title from the current route in a preprocess hook for your specific block content UUID. Add a routecache context, so that the block changes the title when you visit different pages:

function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_content:12345678-1234-5678-90ab-1234567890ab') {
    $variables['title'] = \Drupal::routeMatch()->getRouteObject()->getDefault('_title');
    $variables['#cache']['contexts'][] = 'route';
  }
}


Change add node select field to show data from 2 different fields of other content type

Install the Entity Reference module. It allows you to pull up information from one content type into another. Here is a super helpful tutorial of pretty much what you want to achieve so there is no need for me to provide detail explanation here.
https://atendesigngroup.com/blog/getting-started-references-drupal


How to find the right data selector in Rules Components?

Head over to the settings of your Rules Component, and specify "Node" as an extra parameter (on top of the 3 you already have in place). You can find "Node" within group "Entity".

After doing so, try again to add "Node" as your data selector, more specifically "Node:comment" (for which you want to test if its value is "0"). This time (after you added that extra parm) it should show up as a data selector.

Here is a sample Rules Component (in export format) that does something similar (it has an extra condition for "uid=1", which is probably not what you want).

{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false },
      "node" : { "label" : "Node", "type" : "node" }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } },
      { "data_is" : { "data" : [ "node:comment" ], "value" : "0" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

If you just import the above Rules Component, it already has that "Node" as an extra parameter.

Note: if you get unexpected errors (after enhancing your Rules Component as suggested above), then enable Rules debugging (so see the Rules debugging log). You can do this via /admin/config/workflow/rules/settings


This only works when you also have an MP4 output format. The original video is not used as a source.


As you've mentioned, Rules provides a tagging feature to tag / label rules. You then apply a filter to view that set of Rules only.

Any other grouping of Rules would require custom coding to retheme / template the layout of that page.


1 It appears that there is no site:mode command in the latest drupal console (1.0.0-rc16), but instead site:maintenance (sma) (on/off) is available. Maybe they ditched site:mode at some point because site:maintenance made more sense in Drupal context.

2 Make sure you have this code in development.services.yml:

services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory


I believe this is a caching issue.

'The requested page could not be found.' is not the same as 'You are not authorized to access this page.'

Because you can see the page as the admin account but not as an anonymous user, I believe you can fix this issue by flushing your Drupal caches.

The admin account doesn't show cached content by default but the anonymous users do.

There are several ways to Clear Drupal's Cache but the simplest is likely to go to admin/config/development/performance.

If you use drush, simply run 'drush cc all'


Unable to store value of an property or entity key in ConfigEntityType form

Try this one for saving config.

$config = Drupal::service('config.factory')->getEditable('my_module.settings');
$config->set('my_module.dsu_single_indexing_server',json_encode(array_unique($values)))->save();


Drupal 7 Remove field suffix from search index

You can exclude fields from being added to the search index under the settings for you content type.

Go to the settings for you content type and Manage display. Click on the view mode Search index and drag the fields you don't want to index to Hidden.


You can use url() to generate a base url to any route in Drupal. You can supply the <front> route which, in effect, will be your base URL.

{{ url('<front>') }}

But, render it first if you're concatenating it:

{{ url('<front>')|render ~ file_url('public://image.jpg') }}

For example:

{{ url('<front>') ~ file_url('public://image.jpg') }}
# Outputs: "Array/sites/all/default/files/image.jpg"

{{ url('<front>')|render ~ file_url('public://image.jpg') }}
# Outputs: "http://example.com/sites/all/default/files/image.jpg"


Giving users control of who sees their information?

Assuming that by "best" you mean that you want to avoid custom code if possible (e.g. because you don't have the skills and/or budget for that), then this is a way to make it work with zero custom code:

Implement your "About me" field as an entity reference, which references a node of some other content type (say "Details About Me"). So if somebody wants to complete such field, they should first have created an appropriate node of content type "Details About Me" (so that they can use that node in their entity reference field.
Add a special (required) field, which you define as a single value selection field, to let the user "specify who can see this information" (as in your question). Say you call such field "Visibility".
Whenever somebody wants to browse such "Details About Me" page, let the Rules module decide if such browse is yes or no allowed (based on the content type, and the value of that Visibility field. Refer to the answer to "How to make the permissions of a module more granular?" for a sample rule you could start from, and make it fit your case like so:

Adapt the Rules Conditions.
Tune the redirect URL and message in the Rules Actions.

The above should take care of the "specify who can see this information"-part of your question. The remaining part of your question (= "or their whole user profile") is really a different question, not answered here. Though you could use a similar approach for that also.


How to implement javascript to the theme Bootstrap

Please set z-index to solve it.

.b-left-side__pointer {
  z-index: 1;
}

Also, I have some advices for your code.

make use of Drupal behaviors instead of $(document).read()
use jQuery.once() to prevent event binding multiple times, it would happen if your page contains ajax.
use jQuery.toggleClass() to simplify the complexity of logic.

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.sub_theme = {
        attach: function(context, settings) {
            $(".b-container__left-side", context).once('b-left-side', function() {
                $(".b-left-side__pointer", this).click(function(){
                    $(this).toggleClass('show');
                });
            });
        }
    }

})(jQuery, Drupal, this, this.document);

You need to change your CSS and also class name on HTML. I can't give opinion with that due to lack of information of your requirement.


How can I load CSS files located outside the web root from within a custom module?

drupal_add_css() expects a path relative to the site root. As such, if you're going to use drupal_add_css() you need to add a path within webroot to access the file.

One way to that is to use a symlink. For example

ln -s /srv/assets/css/my_site/general.css sites/all/modules/my_module/css/general.css

As long as the file is readable by your web server, you can use drupal_add_css to reference your symlink path.

drupal_add_css(drupal_get_path('module', 'custom') . '/general/custom.css', array('type' => 'file'));


Notice: Undefined index: main_profile in include() (line 54

Your mistakes is here main_profile , profile type always start with profile_name . just need change main_profile to profile_main

global $user;
$user->uid ;
print_r($user->uid);
print "print out the user value" . $user->uid;

$uid =3;

$account = user_load($user->uid);
$profile = profile2_load_by_user($account);

$print_first_name =  drupal_render(field_view_field('profile2',$profile['profile_main'], 'field_first_name'));
print $print_first_name;

If you want see all your profile type and correct name and it's contents print_r or var_dump $profile

$profile = profile2_load_by_user($account);
print_r($profile);


So i have similar issue, and i solve this by creating 2 views.
First view show taxonomy terms and i group them by theirs parents (add relationship Taxonomy term: Parent)
Second View is override on taxonomy/term/% and i add more Context (Arguments) for each level add an argument, and finally i add into header another view, who shows only children terms of current term.

You can view my work at http://www.attorney-directory.net/practice-areas


Field formatter module throws cannot declare class error

Here are some pointers that might help:

Run drush cr to clear cache and see if the error persists.
Enable error backtraces from the Config > Development > Logging & Errors page to see if you get more info in the error message about where the class is being redeclared.
Search your project for the name MyFormatter and see if you find anything besides the MyFormatter.php file you've mentioned.
File, directory and class names are case-sensitive – in what you've shared, they seem to be correctly named.
Make sure you're not manually using require or include anywhere to include this file.

Probably, not applicable in your case.


You have got two options. Ubercart or Drupal commerce With Ubercart you have to do some bits of configuration to get your store ready.

With commerce, you have a basic store setup for you if you use the Commerce kickstart distribution.

  Commerce Kickstart is the quickest way to get up and running with
  Drupal Commerce. It includes the latest versions of Drupal core,
  Drupal Commerce, and the other modules it depends on. It also gives
  you a set of options to create a fully-featured demo store out of the
  box complete with an attractive theme, catalog and search
  configuration, and a custom back office interface.

  Who should use Commerce Kickstart? Anyone who wants to skip weeks of
  configuration to build a commerce site on the Drupal Commerce
  framework.


Running drush sql-sync between linux drupal alias as source and windows drupal alias as target throws rsync:chgrp error

Okay, i got it running. Followed instructions at this blog and i'm able to run it.

Specifically:

  The best way to solve this, is simply to add the following to your
  alias definition file for your local site:

  'target-command-specific' => array (  //commands used when this alias is the target
'sql-sync' => array (
  'create-db' => TRUE,  //create new database(merged databases can be trouble!)
  'mode' => 'rultvz',  // override sql-sync default $mode = '-akz' from rsync.core.inc
),

),


View that link to content in other languages

You have to add NID field before the Title in Fields and make it Exclude From Display, I mean this

Then click on Title and in Show Rewrite results, check the Output this field as a link and use the following configuration

Now the Titles are linked to /en/node/[nid]


Store token replacement values in the database rather than tokens themselves

The gist of it is to execute token_replace in a suitable location. Here's an example.

hook_node_presave($node) {
  if ($node->type == 'page') {
    $replaced_text =  token_replace($node->field_with_replacements['und'][0]['value']);
    $node->field_with_replacements['und'][0]['value'] = $replaced_text;
  }
}


Is there a template for the comment links field?

Why don't you use the default selectors to get the url? some thing like this:

(function($) {
    $(document).ready(function() {
        $("YOUR-COMMENTS-WRAPPER").find('a').click(function(){
             var url = $(this).attr('href');
        });
    )
    });
})(jQuery);

then use the url to load the DIV


How to get drupal to remove /drupal/ from all the links on the website

The entry in the .htaccess file you should uncomment is the /drupal one:

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /drupal


Yes, you could set up a view, filtering on Location: Distance / Proximity, and configure what the origin or "starting point" is, eg, the location of the logged in user, a node that has a location, or, in this case, a static lat/long, and then have it display whatever fields in the filtered nodes you want.


Drupal Commerce default amount before adding a product

You can do this, but I doubt that this is possible with rules.

What you want is a custom checkout flow. Either this can be done by altering the checkout flow provided by Commerce, or disable it completely and write your own.

Either way you will need to write your own code to create this custom checkout experience, and this is beyond what Rules is capable of.


How do I add attributes to a single menu's links?

You might try the Menu Attributes module.  This looks like it will do what you want.


Delete Custom Content Type Content with Custom Fields

You could use node_delete or node_delete_multiple to do this:

// Retrieve all nids for your custom content type.
$result = db_query("SELECT nid FROM {node} WHERE type = :node_type", array(":node_type" => "<YOUR_CONTENT_TYPE>"))
  ->fetchAll();

// Delete all nodes.
foreach($result as $nid) {
  node_delete($nid);
}

// You should also be able to use node_delete_multiple().
// node_delete_multiple($result);


How to share fields between commerce variation types?

It sounds like what you're wanting to do is create a group of product variations where you only have to specifically set the unique field value per variation. If that's the case, it isn't possible. We tried to implement some sort of field inheritance model where you could set default field values for each variation at the product display level, but it never developed.

The closest thing is the Bulk Product Creation module, which does let you create a whole set of related product variations at once. I don't believe it's been integrated into Inline Entity Form / Kickstart 2.x, though, so you may want to play with it first in a development environment before trying it in your live database.


Table 1 matches how it is in Drupal 6, table matches more or less how it is in Drupal 7.

So to answer your Question, the newest Drupal does indeed use a schema close to what you proposed.


Can you allow user to add another item without editing the administrator post?

My suggestion is to use hook_form_alter for your node edit page and set '#disabled' => TRUE for your content field (assuming here as body field) by checking the current user role or something.


Theming with Views generates error undefined variable

Not sure what the variable $fields are but try and do a dpm($rows) this should return an array of the fields from the views.


How to pass a nid to panel, and load a node with the given nid as context?

Settings -> Basic -> Path -> something/%node/something_else
Settings -> Arguments -> Change ->  Content: ID

Then at 'Variants -> Contexts' you should see the loaded 'Argument 1'.


How do I port my hook_alter module to D8?

Considering that the Editor module in Drupal core is the equivalent of the Wysiwyg module for Drupal 7, and the core CkEditor module is the equivalent of the Drupal 7 module with the same name, I would say that the hook you are looking for is hook_editor_js_settings_alter() that, for a module whose machine name is ckeditor_show_blocks, it is implemented from the ckeditor_show_blocks_editor_js_settings_alter() function.

If you need to know the ID of the editor plugin used for a input format, you can get that from $settings['editor']['formats'][$format_id]['editor']; that is the case, for example, when you need to change settings if the used editor is the one implemented by the CkEditor module.

To make it clearer, the Editor module is the module that associate editors to the input formats used from a Drupal 8 site, while the CkEditor module in core contains an implementation of editor.


Replacing the updated module in drupal 7 without effecting the database from previous module?

That's what hook_update_N is used for:

  For each change that requires one or more actions to be performed when updating a site, add a new hook_update_N(), which will be called by update.php. The documentation block preceding this function is stripped of newlines and used as the description for the update on the pending updates task list. Schema updates should adhere to the Schema API.

e.g. Adding a new column to a table:

function MYMODULE_update_7100() {
    db_add_field('foo_table', 'bar_col', array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'description' => 'My new integer column.'
    ));
}


How to assign content to user for manage turns?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to link to Entityform submissions page?

Entitform module comes with pre-built Views that list the Submissions. It is called Entityforms (Entityform Submission) and you can access the Page through

/entityform-submissions/submissions/accommodation_contact/list

or the Table where you can see submissions directly:

/entityform-submissions/submissions/accommodation_contact/table

Display one of these links in the Block you created for your owners:

View submissions

These Pages use the access permission View any entityform submission so allow your owners role this.


There is OG Vocabulary module for D6 (and just a basic D7 port) that

  "provides each Organic Group with its own vocabularies (i.e. taxonomy). This lets groups logically segregate their content into categories which make sense for them. This module is integrated with Token, Rules and Services modules."
  read more...


How to print render Location's sub-fields?

If you have devel module installed than you check the exact contents of the array as: dsm($content);
Even if you don't have the devel module installed than check the contents of array as:

echo '<PRE>';
print_r($content);
echo '</PRE>';

I guess you probably have missed the language attribute - for regular non-location fields it's: $content['field_location']['und'][0]['#street']; and $content['field_location'][0]['#city'];


In short: use hook_field_widget_form_alter()

/*
* translate the form
*/
function mymodule_field_widget_form_alter(&$element, &$form_state, $context){

if(isset($element['#title'])){
  $element['#title'] = t($element['#title']);
}
if(isset($element['value']['#title'])){
  $element['value']['#title'] = t($element['value']['#title']);
}
if(isset($element['#description'])){
  $element['#description'] = t($element['#description']);
}
if(isset($element['value']['#description'])){
  $element['value']['#description'] = t($element['value']['#description']);
}
}

This translates titles and edscriptions of textstrings.

To show the fields title and description in the given language in node_view:

function mymodule_preprocess_field(&$vars) {
if ($node = menu_get_object()){
  if($node->type == 'immoclient'){
    // Check to be sure there's a label and it's visible.
    if(isset($vars['label']) && $vars['label_hidden'] === FALSE){
      $vars['label'] = t($vars['label']);
    }
    $field_name = $vars['element']['#field_name'];
    $trans_fields = mymodule_trans_fields();
      if(in_array($field_name, $trans_fields)){
        $items = $vars['items'];
        $result = count($items);
        for($i = 0;$i < $result; $i++){
          $vars['items'][$i]['#markup'] = t($vars['items'][$i]['#markup']) ;
        }
      }
     }
    }
   }

and mymodule_trans_fields() returns an array of fields to translate.

To show the items (and here the answer) in the appropriate language for selects and checkboxes in the form, I used hook_form_FORMID_alter:

function mymodule_form_[mynode_form]_alter(&$form,&$form_state,$form_id){
    foreach($form as $key => $value){
      $field = strpos($key, 'field_');
        //only for fields!
          if($field !== false){
            if(isset($form[$key]['und']['#description'])){
            //seems so that every field has a description, to use it for items too
            //build variables
              $res = $form[$key]['und'];
              $desc_t = t($form[$key]['und']['#description']);
              $form[$key]['und']['#description'] = $desc_t;
                }
               }
             }
           }


emailing users in user reference field with rules

I think you are fetching the user reference wrongly. You should try this:

On the Action:Fetch Entity by ID
Value:User
Data selector :node:field-name:uid (this is your user reference field
Variable label:Fetched entity
Variable name :user_entity

Then you are good to go!


Access Value of variable content in twig template

You can try {{item.url.getUri}}.

You can change to tab Available methods to see other method. Example isExternal. :D


Deleting non-active users (e.g., users who didn't log in for 90 days)

Maybe this module can help: inactive user

From the module page:

  After configurable periods of inactivity, one or more of the following
  actions can be automatically taken:

  send an email to the user
  send an email to the site administrator(s)
  block the account (a warning can first be issued)
  optionally notify user and/or site administrator(s) that account
  was blocked
  delete the account (a warning can first be issued)
  optionally notify user and/or site administrator(s)1 that account was
  deleted


You can set the site uuid variable with drush, but a better solution is to use the "config_installer" module.

See https://www.drupal.org/node/2583113 for related discussions.


Table creation in install module returns error

In your indexes element you're specifying 2 columns, changed & created, that don't exist. You need to have these columns added to your fields element or remove the indexes.


Is there a way to load the content types using DrupalWebTestCase?

Try the SimpleTest Clone module.

SimpleTest performs the test on a clean Drupal installation, so if you have created Content Types they will not be available.

SimpleTest Clone craetes a copy of the database (using a table prefix) and performs the tests over those tables, so all config you have done is present.

Once the tests are donde the extra tables are deleted.

The drawback fo this method is that is a little slower than standard SimpleTest because the table copy operation.

To use SimpleTest Clone just subclass your test class form SimpleTestCloneTestCase class instead of DrupalWebTestCase class.


Thanks Malks. Yip it was the htaccess file i overwrote folks. I just edited that again with my website url in 2 spots and everything was hunky dory again.


How to create a module to process AJAX request?

If you are tying your functionality to Drupal, use Ajax framework commands
.

If you want to process any arbitrary incoming request, (ajax or otherwise) implement a Services resource.


Search for user by specific 12 digit ID number

It seems to me like a typical use case for Field UI and Views. No code needed.

Video tutorials on Drupal 7, (Fields from episode 9), and Views.


How to add secondary exposed form elements using "Better exposed module" in views

Below the field which will be secondary open MORE OPTIONS and check This is a secondary option check box and save.

After that, it will display in Advanced


{{ directory }} not available in parts of menu--main.html.twig

The second occurrence of {{ directory }} is within a Twig macro. As the Twig documentation mentions, you cannot access the outer variables in a macro:

  But as with PHP functions, macros don't have access to the current template variables.

You can however pass _context through a macro parameter and access directory that way, or pass it explicitly.


I believe the reason there is not common "Out of the box" solution for this, is that the statistics module has a long-standing reputation of ruining performance, as it performs a lot of database writes.

While it could certainly be "upgraded" to being entity agnostic, I guess there's little interest in doing so.

The most common solution then, I think is to use a tool like Google analytics for counting impressions, and exposing your video (or other entity) in ways/with urls that make their views easily countable in your tool of choice.

For Views integration, the easiest options seems to be Google analytics statistics, (Thanks Chapabu), but other interesting modules could also be GA counter, GA reports and GA importer


Passing variables that contain HTML through the t() function - ! placeholder has been removed

It appears that any arguments passed to t() function are escaped unless they implement MarkupInterface. So that you need to represent the name as an object.

use Drupal\Component\Render\FormattableMarkup;

$formatted_name = new FormattableMarkup(
  '
    @first_name
    @second_name
    (@user_name)
   ',
  [
    '@first_name' => 'John',
    '@second_name' => 'Hancock',
    '@user_name' => '@JohnH',
  ]
);

drupal_set_message(t('Your name is @name', ['@name' => $formatted_name]));


Is there a good way to set available countries in Drupal Commerce shipping and billing?

Depends what you mean by 'quick', really. Yes, you can do it programatically. With PHP:

$instance_config = field_info_instance('commerce_customer_profile', 'commerce_customer_address', 'shipping');

$instance_config['widget']['settings']['available_countries'] = array(
  'GB',
  'US',
  'FR',
  // etc...
);

field_update_instance($instance_config);

Or with JS (I'll let you work that one out, selecting a bunch of <option> tags based on a bunch of values is very easy).

IMO the time-consuming part is building up the array of default countries in the first place; no matter what automated method you use to put the values in, someone needs to spend the time choosing and preparing them. You can't get away from that.


D7 Simple form with an items catalog grid table

I did it myself with the help of webform, webform_table_element module and by implementing a couple of hooks and a little jQuery snippet. A complete howto can be found here:

Drupal 7 Webform with an item catalog table element

Thanks.


What Multiple contributors means in Drupal Translations site?

See the Working with translation files offline documentation under the Contributing back to the community header:

  When you have finished, contribute the translation back to
  localize.drupal.org by importing the file on the translation team user
  interface. Translations will either be attributed to you or "Multiple
  contributors" depending on which option you choose. "Multiple
  contributors" is a special account you can use if multiple people
  worked on the translations being imported and singling out one
  contributor for attribution would not be correct.


How to allow user login only once at a time?

You can get what you're looking for with a combination of existing modules:

Session limit module
Password policy module
User stats module + Views module

You shouldn't have to write a single bit of code using those 3 modules.

You don't mention which version of Drupal you're using but each of those modules have D6 and D7 releases (albeit a dev release for one of them).


How to display field description right after field label?

The module called Better field descriptions might be the one you are looking for. It describes as following:

Better field descriptions makes it possible to add themeable descriptions to fields in forms.

Would your customers like to write their own descriptions, but can't or won't, since they then need permission to manage the fields in the content type?
Would you like to show the description above the field or even between the title and the field?

The module Label help might also be helpful.


How to get access all images of custom directory in twig template?

The path will be wrong, file_scan_directory() will return a relative path, you need to add the base_path(), you can set a variable in preprocess:

$variables['base_path'] = base_path();

So...

<img src="{{ base_path }}{{ file.uri }}" width="100%" height="100%" alt="{{ file.name }}"/>


It's usually easier to redirect at the Apache level if you're looking to make the entire Drupal HTTPS. You can place this in your .htaccess file:

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


How to prevent "drush up" from destroying my git repo

The deletion of the .git directory and other non-Drupal files when running drush up drupal has been a somewhat randomly occurring problem for many Drush users as documented on this GitHub issue. As far as I know, no definitive reason for this behavior has been found, and there is even debate about whether this behavior is, or should be, by design.

In my experience and that of others participating in the GitHub discussion, this deletion of the .git directory did not happen when using Drush 6, but happens in some circumstances when using Drush 7 or 8. Therefore, there's no surefire way of avoiding the deletion of the .git directory and other non-Drupal files when running drush up drupal besides moving those files out of the Drupal root directory before running the update.

However, the overwriting of .gitignore when running drush up drupal occurs by design. .gitignore is a core Drupal file, and as Drush warns, updating core will discard any customizations:

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal
core files, most noteworthy among these are .htaccess and robots.txt.  If
you have made any modifications to these files, please back them up
before updating so that you can re-create your modifications in the
updated version of the file.

.gitignore isn't mentioned explicitly in that warning, but it is treated similarly since it, too, is a Drupal core file.


How do you change the title of a field collection edit form?

In a custom module (or even theme), you can add this function. Replace YOURMODULE with the name of your module or theme.

<?php
function YOURMODULE_form_field_collection_item_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_title(t('Your title'));
}


Display submitted data using a select field option - webform module

Hi this topic should help you out. https://drupal.org/node/1658784 I used it when i needed to achieve the same thing.


Configuring View output with multiple related nodes

Have you tried grouping by the node id (the same node id used in the node reference)?


How can I render more than one field value in the controller?

What I suggest is the this solution, create a custom template, for your page, in controller pass the data to the twig template.
public function myPage() {

    $data = \Drupal::service('myservice.ran');
    $dataService = $data->getArticles();
    $articles = [];
    foreach ($dataService as $article) {
      $articles[] = [
        'title' => $article->title->value,
        'body' => $article->body->value,
      ];
    }
    $build = [
      '#theme' => 'my_template',
      '#data' => [
        'articles' => $articles,
        'whatelse' => "what esle I want"
      ],
      '#cache' => ['max-age' => 0],
    ];
    $output = \Drupal::service('renderer')->renderRoot($build);
    $response = new Response();
    $response->setContent($output);
    return $response;
  }

then all the data will be available on data in your custom twig template. ( you can change its name to whatever you want).
just be sure you clear the cache when you create your custom template.
A helper article


Custom migration not appearing in the migration UI

Is your module enabled? (Seriously, my Drush Make file forgot to enable the module, and I was clueless, yesterday.)

If you use drush migrate-status from the command line, is your Migration listed?


Rewrite the field label text on node dispaly

You need to override field.tpl.php to do this (the colon is hard coded into that template file).

Create field.tpl.php anywhere in your theme folder, copy the code from the above link into it, tweak it (remove the colon etc), then clear your caches: all will be well!

I found Answer from Here


Your data should not be nodes, as they do not keep any readable content on their own, they only make sense in connection to a product and in statistics, summaries et cetera, and shouldn't really be displayed on their own. So, you have two ways of dealing with them:

Bad way - make them just a multi-value field in product content type. Not optimal for storage, not really good for filtering.
Make them entities. You only need creation date and product reference on them. Making them entities will expose them to Views for easy filtering and aggregation, to search api if you will ever need to sort by "most sold", and, well, to each and every module that knows about entities. There are many answers and tutorials out there. Hint - your entity should not be a fieldable one. Non-fieldable entities always have only fields defined at creation, so storage is much simpler for them. And simpler == faster.


How to configure Facet displays that comes with Commerce kickstart

Ok I could figured it out thanks to this great tutorial

http://vimeo.com/53404289

There is how you can manage your own commerce facets


Why is "drush make" installing a library in /sites/all/libraries instead of /libraries?

drush status tells me that I have version 5.10.0, so that's likely the issue. D8 support was not added until drush 8. Now I need to get upgraded.


Multi-sites local dev alias question for Drupal 6 / OS X

Seems like what you want could be accomplished by creating a symbolic link in the sites directory. Linking to subsite.com by the name subsite.dev would do it:

$ cd [sites-directory]
$ ln -s subsite.com subsite.dev

Mind you, you might need to change the $conf['cookie_domain'] and $conf['base_url'] values in the settings.php file if you want to be able to log in to your local dev site.


How to create a webform submission table with values from the form itself?

Unfortunately, the current stable release of the Webform module doesn't support getting to any of the webform submission fields through Views.

However, if you look at this issue on Drupal.org: http://drupal.org/node/680386, you'll see that integration with views is a highly desired feature!  That's why there's so much activity on it!  The good news is that (look at this comment: http://drupal.org/node/680386#comment-6480250) there's actually a patch applied to version 7.x-4.0-alpha6 of the Webform module, so you can test this new integration functionality.

Let us know if it works well!


Simple jquery instructions attached on form is not executeing

jQuery 101: If you want to manipulate an element in the DOM, the DOM needs to be ready first.

(function ($) {
  $(function() {
    $('#field-ai-event-date-unique-add-more-wrapper').hide();
    $('#field-ai-event-date-range-add-more-wrapper').hide();
  });
})(jQuery);

See jQuery.ready().

If you can convince yourself never to forget this small fact, life will be a lot easier :)


Validate a group of fields so that form can only be submitted if 0 or 2+ fields have been completed

First I assume this must be for Drupal 6 since you are describing CCK fields? I would suggest creating a small custom module, and implementing hook_validate.

You can then check how many fields have been entered by your user to see if it passes your requirements described above.

If the validation fails you can then display the error to the logged in user with form_set_error

EDIT:

Since you're using Drupal 7, you can use hook_node_validate within a custom module.


How do I create a custom Drupal 7 login?

Drupal's administrative permissions are not necessarily linked to any specific role, and individual permissions can define access to anything from viewing individual content types to administrative functions like creating and editing--they aren't all tied to administrative features.

While it is true that all authenticated users will inherit permissions from Authenticated User, you can organize your permissions like so:

Anonymous User: (Permissions for users that don't need to log in.)
Authenticated User: (Remove all permissions except those needed to view documents)
Administrator (new role): (Permissions necessary to administer the site)

Then, give the Administrator role only to the accounts used to administer the site. Nothing says you have to give that role to every Authenticated User. Administrators will be able to view documents (as with any other authenticated user), though this sounds perfectly reasonable if I understand your use case.

Additional contributed modules allow for more fine-tuning over access control. For instance, the Field Permissions module may be useful if the files you're looking to distribute have been attached to nodes via File fields; this will allow you to determine access control at the field level if necessary.


Visit this to find an answer of this question.
https://drupaltreasure.blogspot.in/2017/04/drupal-8-validurl.html

The content of the provided link:

First, include class namespace use Drupal\Component\Utility\UrlHelper;
then use this function, No need to create the object because it is a static function so we can call it by its class name: UrlHelper::isValid($url, $absolute = FALSE);

Parameters:

$url : The URL to verify bool

$absolute: Whether the URL is absolute


How can I show/hide just one menu item based on user role?

You may try Menu per Role

  This module allows you to restrict access to menu items1 based on user
  roles. It depends on the Drupal core menu.module—just activate both
  modules and edit a menu item as usual. There will be a new fieldset
  that allows you to restrict access by role. The fieldset also appears
  in the node edit form.

D7 release is not stable yet its 7.x-1.x-dev


How to Add Taxonomy description or other field value in a textarea with WYSIWYG?

You have to add any wysiwyg module and enable it. Follow the installation instruction on your site (/admin/config/content/wysiwyg). You can use a wysiwyg editor like ckeditor. Then on same configuration page, for Filtered HTML select your editor.

Once an editor is set for a particular text format. You can follow these steps:

Add a Vocabulary to your taxonomy like Hotel Properties (hotel_properties). Edit it and add new fields to it like price.
Now in your content type, you can use Hotel Properties (hotel_properties) as term reference and widget type: autocomplete.
Now you can alter the node tpl or use panels (Node Template) to display information from taxonomy.

Note: To get the wysiwyg editor, use filtered text editor.


Instead of trying to decrypt users passwords, and then re-encrypt them to be stored in drupal. Why dont you:

import the users all over into drupal
get all users to reset there own passwords (through the normal email method) when they next try to login


If you want the logged in user info, try the following (I have not tested, but it should work).

global $user;

$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1', array(':uid' =>$user->uid))->fetchField();

The global $user object will return information from the currently logged in user.  You might want to put some authentication in to check that the user is logged in if this is used in an area where anonymous users can visit.  Maybe wrap it in an if statement like I've done below:

if (user_is_logged_in() == TRUE) {

  global $user;

  $hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1", array(':uid' => $user->uid))->fetchField();

  echo 'Hostname: ' . $hostname;
}
else {
  echo 'You are not logged in.';
}


This is a generic issue that will show for various reasons, often because of a bug in the code handling the server response. Look in your server logs for more information as to what has happened.


Form API-passing on the NID in a hidden field?

Just save the node ID in $_SESSION.

Using variable_set() has another effect, apart saving a value that is valid for all the users: It clears the cache Drupal uses for the Drupal variables, with the effect they are reloaded from the database the next time Drupal bootstraps. Compare the code used by variable_set() and variable_initialize(). (Similar code is executed by Drupal 6.)

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;

  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

As for an example of how to use $_SESSION in a form, see node_filter_form(), the form builder function that handles the form that allows to filter nodes in admin/content/node.

  $session = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
  $filters = node_filters();

  $i = 0;
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#theme' => 'exposed_filters__node',
  );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
    if ($type == 'term') {
      // Load term name from DB rather than search and parse options array.
      $value = module_invoke('taxonomy', 'term_load', $value);
      $value = $value->name;
    }
    elseif ($type == 'language') {
      $value = $value == LANGUAGE_NONE ? t('Language neutral') : module_invoke('locale', 'language_name', $value);
    }
    else {
      $value = $filters[$type]['options'][$value];
    }
    $t_args = array(
      '%property' => $filters[$type]['title'],
      '%value' => $value,
    );
    if ($i++) {
      $form['filters']['current'][] = array('#markup' => t('and where %property is %value', $t_args));
    }
    else {
      $form['filters']['current'][] = array('#markup' => t('where %property is %value', $t_args));
    }
    if (in_array($type, array('type', 'language'))) {
      // Remove the option if it is already being filtered on.
      unset($filters[$type]);
    }
  }

  $form['filters']['status'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('clearfix')),
    '#prefix' => ($i ? '
' . t('and where') . '
' : ''),
  );
  $form['filters']['status']['filters'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('filters')),
  );
  foreach ($filters as $key => $filter) {
    $form['filters']['status']['filters'][$key] = array(
      '#type' => 'select',
      '#options' => $filter['options'],
      '#title' => $filter['title'],
      '#default_value' => '[any]',
    );
  }

Its form submission handler sets $_SESSION with the values entered by the user.

  // Apply every filter that has a choice selected other than 'any'.
  foreach ($filters as $filter => $options) {
    if (isset($form_state['values'][$filter]) && $form_state['values'][$filter] != '[any]') {
      // Flatten the options array to accommodate hierarchical/nested options.
      $flat_options = form_options_flatten($filters[$filter]['options']);
      // Only accept valid selections offered on the dropdown, block bad input.
      if (isset($flat_options[$form_state['values'][$filter]])) {
        $_SESSION['node_overview_filter'][] = array($filter, $form_state['values'][$filter]);
      }
    }
  }


AFAIK your bootstrap theme will be having bootstrap.js or bootstrap.min.js included. Generally, scrollspy plugin related code will be inside these files.

So try to recheck whether you have added nav-scrollspy to your div element. I think you might need to have 'id' for your div element and a proper link to it.

Section 1

Section 1

Try to scroll this page and look at the navigation bar while scrolling!

Also in Drupal 8, caching is a bit aggressive so try to rebuild your cache and check again. For better understanding refer http://www.sitepoint.com/understanding-bootstraps-affix-scrollspy-plugins/


How to sync one menu item into other menus?

My suggestion is to use hook_form_FORM_ID_alter to add a custom submit handler. In that submit handler, you will get the current menu item values. Use those values to create a new menu item for the other menu.

Functions to use:

hook_form_FORM_ID_alter. Here form id will be 'menu_edit_item'
Use form['#submit'][] = "custom submit handler" in form alter.
Use menu_link_save in custom submit handler based on the values you get form the form_state.


The Drupal 8 migration module has been moved into core as explained in this issue. If you're using at least Drupal 8.6.x, you don't need to apply the patch.

Old answer:

I'm going out on a limb and say that currently there isn't one and it can only be done by creating a custom plugin.

Just found this Drupal 8 migration (source), thanks Berdir & Primsi.


How to mandate the password policy in custom form fields?

You can use the 'password_confirm" #type in your form to get the exact field Drupal uses.

Add this to your Form function.

$form['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#description' => t('To set or change the password, enter the new password in both fields.'),
    );

This will give you the field, javascript and the validator without any extra code.


What is the difference between "Autocomplete" and "Autocomplete (Tags style)" field widget type?

For one term, there is no difference.

When you increase cardinality (i.e. allow unlimited number of values), with tag style you will put all tags in one textbox, just like you do with tags on this site, and with regular autocomplete you will need to put each one with it's own textbox.


I don't know how the Context module handles Entity types, but it loads entity type definitions using the entity ID (from the URL). In your case, you are creating a menu item without any arguments, just specifying business logic in the callback, and your menu item path is not a node path. That's why the Context module can't find any entity type definition. In this case you can specify additional context reactions by path (by your custom path) and display blocks.

You don't need to specify double fields method; you can write much simpler code.

$nid_some = db_select('node', 'n')
  ->fields('n', array('nid', 'type'))
  ->condition('n.type', 'SOME_TYPE')
  ->execute()
  ->fetchAll();

If you need to fetch only one row from the database, you can use the following code.

$nid_some = db_select('node', 'n')
  ->fields('n', array('nid', 'type'))
  ->condition('n.type', 'SOME_TYPE')
  ->range(0,1)
  ->orderBy('nid', 'DESC') // Additional sorting
  ->execute()
  ->fetchAll();


Adding metadata to nodes for SOLR search

Apache Solr supports synonyms, and you can add them to the solr/conf/synonyms.txt file.  The path is relative to where you copied the "example" directory to.  This way people searching for "org chart" would find documents containing "Organization Chart" and any other synonyms you wish to add without any modifications to Drupal.


There is a solution that can work for your problem without going into php and this solution will work only in case if twig template is under module directory.

Suppose my module structure is like below:

modules

custom_module

templates

my-template.html.twig

js

script.js

To include script.js in my-template.html.twig file. Use below code in twig file -

{% set module_path = _self|split('/templates') %}
<script src="/{{ module_path[0] }}/js/script.js"></script>

In above script _self returns the path upto twig file and split('/templates') splits the string from /templates AND

module_path[0] = /modules/custom_module/
module_path[1] = /my-template.html.twig

However, this is not the appropriate way. This is only a solution for your problem. Appropriate way is to set module path in a variable in preprocess hook and use that variable in twig.


How to print "rendered node" version of Node Reference field in template?

In your $node object, you will find the subordinate node object at $node->field_fieldname['und'][0]['node']. To render this in a page you have to turn it into a renderable array. You do this with node_view(),specifying the type of display mode. Try:

<?php
if(isset($node->field_fieldname['und'][0]['node'])) {
  $second_node = $node->field_fieldname['und'][0]['node'];
  $view_mode = 'teaser'; // or 'full' as the case may be
  $render_array = node_view( $second_node, $view_mode);
  print render($render_array);
}
?>

EDIT

MPD is correct. The above assumes that the field is a Node Reference field. If you are using an Entity Reference field, the code should be changed to:

 <?php
    if(isset($node->field_fieldname['und'][0]['entity'])) {
      $second_node = $node->field_fieldname['und'][0]['entity'];
      ...


How not render a region on specific page programmatically on Drupal 8

Got to /admin/structure/block on your domain. Click the configure button beside your block. In the lower part of the configuration form you have a section called visibility. One of the tabs in this section is labelled pages. This is where you configure where the block is permitted or forbidden to be rendered. In your case one would write <front> and choose the radio button labelled "Hide for the listed pages".


What is x-speed-cache-key? What is its purpose?

Best I can find on Google is that this header (and its companion header 'X-Speed-Cache') are added by a web server level module called "Speed Booster" touted as part of the Drupal Platform 'BOA': https://groups.drupal.org/node/173219 and https://omega8.cc/features .

The purpose of the header seems to be nothing more than a debug header to check which key has been used to retrieve the cached version in Speed Booster.

You probably want to contact your hosting company to see if they can disable that header.


Feeds importing unique nodes over and over

My bad! The "Unique" option in the feeds module isn't working without the module "Field Validation". I added an unique rule to the contenttype "evenement" and now it works like a charm!


What file and folder permission changes does the Microsoft Web Platform Installer make when it installs Drupal?

You may be interested in this question.

However, a manual install of Drupal has a few variables.

For all versions of Drupal you will need to install PHP.  The recommended way to install PHP is with Fast CGI.  (That is also how the WebPI installs it.)

Since you are running Server 2008, it is recommended that you use Mirosoft's URL rewriter if you want clean URLs.  (That is also how the WebPI installs it.)  If you are using Microsoft's URL rewriter, it will automatically look for a web.config file.  Drupal 7 ships with a default one, which I believe will work for Druapl 6 as well.

Then, you need a database.  For Drupal 6 your only practical option is MySQL.  For Drupal 7 you can choose between MySQL and the more native MSSQL.

Once those three items are installed you are pretty much left with permissions.  By default IIS uses C:\inetpub\wwwroot\ for all web served files.  For IIS to read those files the local IUSR account needs read permissions.  To write the local IUSR account needs write permissions.  I believe the recommended behavior currently is IUSR gets read permissions to everything in C:\Inetpub\wwwroot.  However write permissions are restricted to only where absoultly needed.  The traditional location is ..\sites[sitename]\files as that is the default location for user uploaded files.  However Drupal 7 has a fancy web installer for modules.  For that to work ..\sites[sitename]\modules and ..\sites\all\modules need to be writeable by the local IUSR account.  One final note.  For the default Drupal install process to work ..\sites[sitename]\settings.php needs to be writeable by the local IUSR account.  However, post install it is usually recommended that file be read onle.


Yes the length of the field name is hard-coded to 32 characters. It's most likely because the maximum length for a table name in MySQL is 64 characters, and the field API creates tables with names like field_revision_field_name. I imagine the core developers were erring on the side of caution.

It looks like you could squeeze an extra 17 characters out of the field name (64 - 32 - len('field_revision_')), but to do that you'll need to alter the field_config and field_config_instance tables in the database to increase the length of the field_name column (I guess to 49 characters).

I would imagine you'll also need to hook into the field UI forms to increase the #maxlength of appropriate text fields.

It might be easier to re-think your matching logic :)


Drupal 7, hook permission for view published content only for certain content type/blog

You can use content_access module, you can control any content type permissions individually. here is a nice video tutorial


Why do I get "Page not found" with my code?

_content is no longer used, wherever you found that is outdated. Use _controller instead.


How do I load the $form_state for a form loaded with drupal_get_form?

When you do drupal_get_form() the form and state is cached, otherwise other Drupal form functions wouldn't be able to get it back later.

The only way I know to get it is like this:

// Get the form.
$form = drupal_get_form('my_form_id');
// Get the default form state.
$form_state = form_state_defaults();
// Get the form and form state from the cache for the form you just got.
form_get_cache($form['#build_id'], $form_state);

Since form_get_cache() returns the form also you could do the last line like this:

$form = form_get_cache($form['#build_id'], $form_state);

and it would overwrite your form with the cached one and update your form state (since $form_state is passed by reference) but in the case of calling it right after drupal_get_form() there is no need to do that.


Site crashes after running 'composer install' to update modules

Your composer.json probably has this in it (many do):
"autoload": {
  "files": [
    "load.environment.php"
  ]
}

But you don't have load.environment.php present in the file system.
Either remove the line from composer.json if you don't need to use dotenv, or add the file which typically contains something like this:
<?php
/**
 * This file is included very early. See autoload.files in composer.json and
 * https://getcomposer.org/doc/04-schema.md#files
 */
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
/**
 * Load any .env file. See /.env.example.
 */
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();


Just disable the Payment module and edit the default checkout completion rule that emails the customer to include an action that emails the administrator.


Invalid response object from API: (HTTP response code was 0)

I downloaded the stripe api and ran all it's unit tests. That way I could find that curl was disabled. By enabling following functions in php, all unit tests succeeded and it got working:

shell_exec
proc_open
curl_exec


How to handle exceptions in a batch process

So in the end I took and overrode the plugin provided by the VBO.
This will put the exception message into the summary displayed with a drupal_set_message at the end of the batch process (VBO 3.0.0-alpha2).

namespace Drupal\my_module\Plugin\Action;

use Drupal\views_bulk_operations\Plugin\Action\EntityDeleteAction;

/**
 * Delete entity action with default confirmation form.
 *
 * @Action(
 *   id = "my_module_delete_entity",
 *   label = @Translation("MyModule Delete selected entities"),
 *   type = "",
 *   confirm = TRUE,
 * )
 */
class MyModuleEntityDeleteAction extends EntityDeleteAction {

  public function execute($entity = NULL) {
    try {
      $entity->delete();
      return $this->t('Delete entities');
    }
    catch (\Exception $e) {
      return $e->getMessage();
    }
  }

}


hook_form_alter() and hook_nodeapi() to alter fields and insert additional data on insert

As mentioned in the comments any extra fields you add to to a node form won't automatically be persisted to the database, the node module only takes care of the fields that it knows about.

Traditionally there are 2 options:

Use CCK instead and add fields to the node that way. Then you don't need to take care of data storage/loading yourself.
Add your own table for data storage using hook_schema(), making sure you have a column for nid (node id). Then in hook_nodeapi() use the insert and update ops to run a db_query() to insert/update the data in that table for the current node.

Then you just need to load that data back from the DB on to the $node object in the load op of hook_nodeapi(). Your data will then be available at $node->field_name when you have a node object loaded with node_load().


The geolocation field module solved this problem.


Entity browser or Media Library for PDF uploads?

Going to Home >> Administration >> Configuration >> Content authoring >> Entity Browsers and creating a new entity browser is the right way actually.
But you probably have attached a media entity field to your content type therefore you must configure your new entity browser to be used on the media form display level.
Lets say your new entity browser is called Document browser you should go to the media form display for document media and make use of the new entity browser.
Here is a screenshot that might help understand better

The content type form display widget for the respective field should remain as Media library in order to pick up the media library from previous step.


You can revert features in an update hook

e.g, in MYMODULE.install:

/**
  * Revert the 'field' component in my_feature_module
  */
function MYMODULE_update_7001(&$sandbox){

  features_revert(array('my_feature_module' => array('field')));

}

http://drupalcontrib.org/api/drupal/contributions!features!features.module/function/features_revert/7

Note, if you have manual access to the code, you can check in the wrapper if the field isset first prior to use, preventing that EntityMetadataWrapperException:

e.g:

// Check if field is set prior to use, avoid EntityMetadataWrapperException
if (isset($wrapper->field_target_nodes)) {
  drupal_set_message('<pre>'. $wrapper->field_target_nodes->value(). '</pre>');
}


Programatically add module block to dashboard

It can be done in a simple way by mentioning a region key to the $blocks array in the HOOK_block_info(). Follow the code for reference,

    /**
     * Implements hook_block_info()
     * @return array
     */
    function my_module_block_info() {
      $blocks = array();
      $blocks['leaderboard'] = array(
        'info' => t('Leaderboard'),
        'status' => 1,
        'region' => 'dashboard_main',
        'weight' => 99,
        'cache' => DRUPAL_CACHE_PER_ROLE,
      );

      return $blocks;
    }


The markup in Drupal is always overridable.  In this case, you may either need to use a hook_form_alter() in a custom module to modify the label html, override the theme_file() theme function (which is responsible for producing the markup for the file input element), or theme the form specifically.  Any of these three methods should be able to meet your needs (although I'm partial to the theme_file() approach).


Add a condition to show menu link in YML

you can add custom access on route_name: double_vue_klesia.backuser.switch

double_vue_klesia.backuser.switch:
  path: '/path-of-you'
  defaults:
    _form:  '\Drupal\my_module\Form\DemoForm'
    _title: 'title'
  requirements:
    _custom_access: '\Drupal\my_module\Controller\ApplicationController::accessCustom'

Inside \Drupal\my_module\Controller\ApplicationController:

 /**
   * Check user has permission.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function accessCustom() {
    if (if (\Drupal::service('userswitch')->isSwitchUser())) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }