Content type field with term reference or users

If you install References and Views, you should be able to use a view to determine which content/terms/etc. are shown. These settings appear on the field settings page for the Term Reference.


Displaying multiple File entity types in a view, when they have different fields to display

What I ended up doing was just add custom tpl.php files for each of the types I was interested in (audio/video/images; e.g. file--image.tpl.php). Then, in the views, just say to render the entity instead of using fields.

I'd have liked a more elegant way, since I now have 3 more tpl.php files to worry about, but it DID fit the bill.


Treat it like any bug:

Find a way to reliably reproduce the problem (this is essential to debugging any code issue for obvious reasons; the question "how do I debug this problem I can't reproduce?" doesn't have an answer, let alone a Drupal-specific one). You may need to set up a clone of your production environment as the issue might not be related to Drupal (e.g. you could have a rogue process duplicating MySQL records that Drupal doesn't get involved with)
Fire up XDebug or your debugger of choice.
Step through every single line of the code that gets involved in the problem you're seeing, keeping an eye on what parameters are being passed to methods, and if they contain the expected data. Basically run through an entire bootstrap for the page(s) you're having problems with, starting at index.php, narrowing down your target search area as you go.
Fix when you've identified the problem (you're not done yet though...)
To help for next time, write a test that fails before you implement your fix, and passes afterwards. Make it part of your deployment workflow to run this test after every change you make. Consider adding tests for other major pieces of functionality as you decide which are the most important, to help avoid this sort of situation in future.


i did a module with a custom text format filter :

function my_module_filter_info() {
   $filters ['to_https_compatible_converter'] = array (
        'title' => t ( 'HTTPS compatible convertible filter' ),
        'description' => t ( 'convert http:// to // for https  compatiblity' ),
        'process callback' => '_module_filter_process',
        'tips callback' => '_module_filter_tips'
   );
  return $filters;
 }

 function _module_filter_tips($filter, $format, $long = FALSE) {
switch ($filter->name) {
    case 'to_https_compatible_converter' :
        return t ( 'convert http:// to // for https  compatiblity' );
}
    }

  function _module_filter_process($text, $filter) {
      switch ($filter->name) {
    case 'to_https_compatible_converter' :

        $dom = new DOMDocument ();
        @$dom->loadHTML ( utf8_decode ( $text ) );

        $images = $dom->getElementsByTagName ( 'img' );
        foreach ( $images as $image ) {
            $image_src = $image->getAttribute ( 'src' );
            $image_src=str_replace(['http://','https://'],'//',$image_src);
            $image->setAttribute ( 'src' ,$image_src);

        }

        $links = $dom->getElementsByTagName ( 'a' );
        foreach ( $links as $link ) {
            $href = $link->getAttribute ( 'href' );
            $href=str_replace(['http://','https://'],'//',$href);
            $link->setAttribute ( 'href' ,$href);

        }

        $iframes = $dom->getElementsByTagName ( 'iframe' );
        foreach ( $iframes as $iframe ) {
            $src = $iframe->getAttribute ( 'src' );
            $src=str_replace(['http://','https://'],'//',$src);
            $iframe->setAttribute ( 'src' ,$src);
        }

        return $dom->saveHTML ();

}
 }


I came across this issue myself when starting my first Drupal 8 project.
This is most likely due to the version of Drush you are using being not compatible with Drupal 7. You can check your Drush version by running drush --version in the command line.
If Drush 9 or above, you should downgrade to version 8, i.e. composer require drush/drush:^8.
Tip: if ever wondering which Drush (local or global) you are using, type which drush in the command line.


Install the views module and then go to ?q=admin/structure/views.

You will find a disabled view created by default named "Taxonomy term" with an ID equal to taxonomy_term.

Enable this view; it will override the default taxonomy page. Configure the view to match your case, and click save.


Hook to compare the already saved value of moderation state of node and updated value

I Used hook_entity_presave and compared values by using  $entity->original
and $entity


adding yet another domain to multi-site but this time symlink not working

This has nothing to do with your database. At this point you have probably a problem completely unrelated to Drupal. Instead your Apache is not aware of your Drupal installation.

Here is a list of things you should check:

Is that domain we're talking about pointing to your server (or do you see the test page of a different one): compare IP by ping yourserver.com

If it's a "testdomain" you might want to add an entry to /etc/hosts

Is your virtual host configured correctly?

Did you set a ServerName or a ServerAlias
If you were setting up a new VHost, did you enable it (sudo a2ensite yourhost for instance)
Did you restart Apache/reload configuration after doing this (sudo service apache2 reload)?
Did you configure your VHost/your root directory to follow symlinks?
Have you set NameVirtualHosts?

Are your symlinks pointing to the right folder?

Do you get the contents of your settings.php by typing cat /var/www/html/sites/symlink/settings.php in a terminal or an error?

As an example:

<VirtualHost *:80>
  ServerName yourdomain.com
  ServerAlias sub1.yourdomain.com sub2.yourdomain.com # etc ...
  DirectoryIndex index.php
  DocumentRoot /var/www/html
  <Directory /var/www/html>
    AllowOverride All
    Options -Indexes FollowSymLinks Multiviews
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Again, it's most probably not Drupal related. It would be if you'd see a different one of your multisites or Drupal complaining about something but since you got the Apache test page you might want to ask on a different board (serverfault) and provide some more information (OS, directory structure, current host configuration and so on) if my checklist didn't help you.


Display content type in custom display format

you can use node--NAMECONTENTTYPE.tpl.php in your directory template. Please see this documentation and comments about templates in Drupal 6 http://drupal.org/node/17565, this will give you a guidance to recognize some few differences with Drupal 7.

to be more detailed, you can copy/paste to your theme directory the file node.tpl.php (located in modules > node or already located inside your theme directory) and rename it according your content type. for example, if the Content Type is Article the name will be node--article.tpl.php

already inside in node--article.tpl.php you can see the variable $content or you can use $node. $content (or $node) variable is carrying the content of your node. you can use print_r($content); to see the list of the fields that you can use to your node (or if you use Devel module, is best use dsm($content);)

see this example:

I have a field called field_demotext1, then this is the way that I can use to call their respective value inside any custom html zone of my node layout:

echo $content['field_demotext1']['#items'][0]['value'];

here is the example of zone in the node--article.tpl.php where you can use a custom html:

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      //print render($content); comment to hide all content
      echo $content['field_demotext1']['#items'][0]['value']; //will only show field_demotext1 value
    ?>
  </div>


Disclaimer: Keep in mind I am neither a lawyer nor a PCI QSA.

After doing more research - I'm convinced that using Drupal Commerce with authorize.net AIM (which is the method used by the authorize module that comes with the commerce kickstart profile) should land you directly into SAQ-D in almost all cases (do not pass go, do not collect $200).

This means you need all the things above plus much more management and policy on your end (or your clients end). It wouldn't be feasible for a small company without a huge budget for a custom project.

Here is the best/most robust explanation i've found of which SAQ to use in one place.

To reduce the scope of the CDE using Authorize.net, one would need to integrate with SIM (offsite form generation) to use SAQ-A, or DPM (direct post) to use SAQ-EP. This assumes you can say yes to the entire list of qualifications i.e. only take payment online, no POS etc. The latter option offers more customization but is more work.

This module looks like it will allow you to do so with Drupal Commerce, but I have done no testing or verification.

Looks like smaller budget clients should be briefed on PCI (always) and plan to use the off-site methods such as Authorize.net SIM or Paypal WPS where the form is generated by the CC processing organization's servers, and never touches your environment. This way your environment should be out of scope with proper configuration.

Here is a (albeit pretty old) thread from authorize.net development forum that has some general and scalable config insights I found very useful.

Here is another (1 year old) white paper that sets forth a framework for PCI compliance on AWS in general. Some of these pieces are not applicable to just a Drupal Commerce server, but still interesting and good.

Any more thoughts still welcome.


field.content is the rendered field. And in views that means it is no longer a render array, but the finally rendered markup. So this is very problematic to use it as a class name, not only because of twig debug.

Better use the row data, where you find the entity object with the field data from the database. Use clean_class to escape it for using it as a class name:

{{ row._entity.field_myfield.value|clean_class }}


#attached css in render array not working

You are saying, you have already rendered content array for the block and after that you are adding css to this block. If block array is already rendered then where you are applying this css because array is already rendered for you. Now you have two options here.

Option 1: Add custom CSS to your block
It should be something like this.

function foo_block_view($delta = '')
{
  if($delta == 'foo_delta')
  {
    $block = array
    (
      'subject' => t('Foo title'),
      'content' => array
      (
        '#markup' => '<p>' . t('Lorem ipsum text.') . '</p>',
        '#attached' => array
        (
           'css' => array('path/to/my.css'),
        ),
      ),
    );
    return $block;
  }
}

Option 2: Add custom CSS to your page before this block rendered (Not a great option for your case).

$content = array();
$content['#attached']['css'] = array(
  $path . 'my.css' => array(
      'group' => CSS_AGGREGATE_THEME,
      'weight' => 999
    ),
  );
return $content;


Create a new View and add the two content type in Filter criteria

Add the two image fields in Fields section

Under Multiple field settings set "1" in display option for both images

Select your Format for views, hope it helps you!!


If you want to map different URLs corresponding to the same view in different languages, this answer will help you. Basically you have to enable "Translation sets" and "Path translation" modules, both part of i18n module. Then in admin/config/regional/i18n_translation/path, add the translated paths and then add a "translation set" which will map all these pages together.

If you want to restrict the view to specific languages because it yields no results for the other languages, you can filter your view results by the user's current language and set a "No results behaviour" to display the view results for a different (default) language, using a Global: View area. See this question for more details. Of course you can also display a specific node (404 page or other) as a "No results behaviour".

@jumper: I've put this answer in case you want to give the bounty :)


Adding "onclick" event to links in text areas

Sorry all, I discovered my question was invalid.
I was able to user onclick directly in the "full html" text area, and while the value of the attribute didn't show in the view source, it was working.

I'm not sure if D6 always handles onclick in full html text areas or not. I choose to believe there is something causing this in my theme.

Thanks for your attention!!
Steph


How to add up all items of a field collection field using Rules?

At first I thought your Rule needs to perform a Rules Component with 2 parameters (say 'current_total' and 'next_item') and simply calculate the sum of both, and return that sum to the Rule (using "provides" for that component parm). And then in your Rule update current_total with the provided sum, before the loop in your Rule ends.

However you don't need such Rules Component, only 1 rule will do. Have a look at this Rule (in Rules export format), which IMO is a prototype that does exactly what this question is about:

{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

Some more details about this rule are below ...

Rules Event:

Content is viewed (of type Article), adapt the machine name of the content type article to whatever fits (or use any other Rules Event that fits).

Rules Condition:

Entity has field, whereas the entity is "node", and the machine name of my field collection field is field_article_details (adapt this machine name to whatever fits, but make sure you use the field collection field itself).

Rules Actions:

Here is where the magic will happen ... These are the Rules Actions involved:

Show a message on the site, with a message like so:

  Drupal calculator started ...

Add a variable, whereas it is a variable named total_price, decimal (2 digits), initial value 0.
Add a loop, to iterate over each item of my field collection field (with machine name field_article_details), and perform these Rules Actions for each iteration:

Calculate a value, which calculates the sum of total_price (defined in Rules Action 2 above) and article-details-item:field-price (this is the machine name of the field in the field collection that contains the prices, decimal with 2 digits), and stores the result (sum) in variable calculation_result.
Set a data value, which simply copies the value stored in variable calculation_result in my total_price (defined in Rules Action 2 above). Remark: not sure (not tested), but maybe this calculation_result variable can be replaced straight by total_price (in the previous action), so that you would not need this action.
Show a message on the site, with a message like so:

  After adding a price of 3.40 for field collection item with id 3, subtotal is 15.00.

Show a message on the site, with a message like so:

  The Total price for all prices included as field collection items is 26.23.

Show a message on the site, with a message like so:

  Drupal calculator ended ...

Obviously, this rule is rather a prototype. After you're convinced it works as it should, just remove all Rules Actions with Show a message on the site. So that only item 2 and 3 (without its last sub-bullet) is left as Rules Actions.

Showtime ...

Here is a sample of my test results, i.e. the Drupal messages that are shown:

Drupal calculator started ...
After adding a price of 2.45 for field collection item with id 1, subtotal is 2.45.
After adding a price of 9.15 for field collection item with id 2, subtotal is 11.60.
After adding a price of 3.40 for field collection item with id 3, subtotal is 15.00.
After adding a price of 1.23 for field collection item with id 4, subtotal is 16.23.
The Total price for all prices included as field collection items is 26.23.
Drupal calculator ended ...

More info

Processing Field collection items with Rules is fun, really! If you're not familiar with that, try to first digest the answer to "How to iterate over all field collection items in an eMail body using Rules?".


Importing pages with different node ids to the live site

I've had this problem myself in the past, and importing nodes into a livesite can be quite a head ache at times.

Luckily there's a great module available for D6 called Node Export. It allows you to import / export nodes using a host of different formats such as JSON, CSV, XML etc.

I've used it before exporting a large dataset and I was impressed with how easy it was to implement.

Hope this helps.


How do I control the available options for an exposed filter?

I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).

To do this in the most efficient/easy way possible, you should create your own filter handler.

For a really simple example:

<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

Then, in your module's .info file, add the file containing this class (in this example, 'custom_handler_filter_countries.inc') to the .info file's files array (files[] = includes/custom_handler_filter_countries.inc).

To make your particular view use this views handler instead of the default handler, you should be able to change the handler in hook_views_pre_view(), I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.


Is it possible to create a rule on the event "after saving an existing block"?

How is the user getting to the edit block screen? If its via contextual links then that should already be taking you can to the page you were on?

Or do you provide them the link to end the block? If so you could use the destination parameter to redirect then automatically (Same as what contextual links do) e.g.:

/admin/structure/block/manage/block/1/configure?destination=MYPAGETHEYSHOULDGOBACK


Enable storing of taxonomy term name instead of ID in views filter criteria

I couldn't find a solution for filtering via term name. However, I came up with a workaround where I was able to featurize the taxonomy terms too.
I'm using UUID Features Integration for the same:

  The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.


If your are writing your own validation u can use finfo_file from php

http://www.php.net/manual/en/function.finfo-file.php

Example #1 A finfo_file() example

<?php
  $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
  foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
  }
  finfo_close($finfo);
?>

The above example will output something similar to:

text/html
image/gif
application/vnd.ms-excel


How to relate two profile2's profile in one single form?

If you're trying to display 2 profile on the same registration path you can use Profile2 Registration Path and enter the same URL path in the settings. The 2 profile will be added to each other. You can also set the weight to choose which one come first.


Use Exposed Filter value in no result Global text

set no result text area of view from advanced "No result behavior"
then edit your view using hook views_pre_render

Access your exposed input in same hook using :

$view->exposed_input['your field name']

then in same hook set these fields:

$view->empty['area']->options['content'] = "Set your message"; ( append exposed filter here)
$view->empty['area']->options['label'] = "Set your label"


We use the signup module for this - we actually used it for tax appointments this year. Yes, it's 7 version is in development but I don't see it being very much different from the 6.x version.

It enables you to attach "slots" to nodes and have people sign up for them. They can be timed or untimed. As the 7.x version is a straight port from the 6.x version, all the tutorials should be the same.


Found this excellent code snippet for Drupal 7: https://gist.github.com/pascalduez/1418121

It offers a way to have $script and $head_scripts so that you can specify which JS files need to go in the head. Example, Modernizr should go into the head scripts.

I'm copy pasting below the solution in the link to future proof the answer.

Cheers.

html.tpl.php

<!DOCTYPE html>
<html<?php print $html_attributes; ?>>
<head>
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $head_scripts; ?>
</head>

<body<?php print $body_attributes;?>>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $scripts; ?>
<?php print $page_bottom; ?>
</body>
</html>

template.php

// Used in conjunction with https://gist.github.com/1417914

/**
* Implements hook_preprocess_html().
*/
function THEMENAME_preprocess_html(&$vars) {
// Move JS files "$scripts" to page bottom for perfs/logic.
// Add JS files that *needs* to be loaded in the head in a new "$head_scripts" scope.
// For instance the Modernizr lib.
$path = drupal_get_path('theme', 'THEMENAME');
drupal_add_js($path . '/js/modernizr.min.js', array('scope' => 'head_scripts', 'weight' => -1, 'preprocess' => FALSE));
}

/**
* Implements hook_process_html().
*/
function THEMENAME_process_html(&$vars) {
$vars['head_scripts'] = drupal_get_js('head_scripts');
}


drupal_http_request() returns "Invalid JSON primitive"

If your request URL accepts only JSON object data, then you need to pass the value as JSON object,
To convert the PHP array/object to JSON object use

drupal_json_encode($input);

If your request URL's output in the form of JSON object, you need to print the array/value after conveting into a JSON object and you need to add the header as 'application/json'

header('Content-Type: application/json');
echo drupal_json_decode($output);


Is this in a hook function? It's possible your hook function is being called more times than you expect which gives you your extra debug statement.


WYSIWYG + TinyMCE: Pressing Enter inserts break instead of paragraph

Give shift+enter a try.

That shortcut tends to be the default in a lot of different text editing apps for break type switching.


Using Drush, you can run drush vset maintenance_mode 0 to disable the maintenance mode on a Drupal 7 site.


Resource for understanding Drupal Core functions?

The Examples module is a good way to see "how to do things".  Another useful tool is grep - you can download all of contrib, and search for examples where other developers have implemented the hook or function that interests you.  You can "upgrade" to ack for more powerful searching.
The book "Pro Drupal Development" used to be a good resource, but sadly the 7.x edition is rubbish.


How can I extend a module and it's library with custom functionality?

i usually do this by adding fields to the sliders content type, then displaying them out through views then use css to position the text over the images


What is the Drupal 7 bookmarking module (a la delicious.com) that is equivalent to userlink in Drupal 6?

For Drupal 7, I am using the Link module. It defines simple link field types.


How to display data in blocks of a given size?

copy the file into your custom theme folder and change it in the manner you want , then clear the cache and drupal will use the new file instead


"Home" not changing in Breadcrumbs when switching languages (Locale)

Navigate to "Translate strings" interface in "Regional and language" admin section (/admin/config/regional/translate/translate).

Search for "Home" and translate all untranslated instances of that string. This should fix the issue with translation of default breadcrumbs.

Useful tip: strings search is case sensitive, so make sure you enter your strings as they appear in html source (this condition gets easily overlooked).


Is it possible to disable a content type?

You can't disable a content type, but you can prevent (almost) everyone from creating/viewing/modifying etc. an Article it with setting the permissions accordingly.
If there's no Article content on the site, it's 100% safe to delete it. (It's interesting to check out how the default and minimal installation profile provide different sets of content types. Article is just a "stock" content type which is by no means necessary to have.)


Maybe implement hook_theme() in your template.php and add an extra template for the test_node_form:

return array('test_node_form' =>
    array('arguments' =>
        array('form' => NULL), 'template' => 'test-node-edit'
    )
);

Now you can write a test-node-edit.tpl.php for the form. But that's only for the form, not the whole page.


To add a cache dependency on user roles you don't need a cache tag, but a cache context user.roles.

However, you rarely need this context, because there is already a default render context for the hashed user permissions user.permissions, set in the container variable required_cache_contexts, which is applied on all render arrays:

default.services.yml:

parameters:
  renderer.config:
    # Renderer required cache contexts:
    #
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    #
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']


As long as you only query for fields, entity query does the joins automatically for you.

Note that entity query can only return entity ID's, you then need to load them.

$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('roles', 'pubblisher')
  ->execute();

$users = User::loadMultiple($ids);


How can I show two users what taxonomy terms they have selected in common?

You are looking for Taxonomy Filter module

  if vocabulary A is set to be 'filtered' by vocabulary B (which may be
  vocabulary A), then whenever someone views the taxonomy listing of a
  term in vocabulary A they will see a 'filter' menu of terms from
  vocabularies A and B. This allows the visitor to narrow down the
  listing by choosing another term - effectively showing them the
  intersection set of nodes from the two terms.


Procedurally, you should skip steps 3 and 4 in the first list.  For views, reverting will delete the view's config from the database, which is why you had to re-re-edit the title.  FYI, reverting works differently for other objects.

  In some cases (e.g. views), the revert operation will delete the respective configuration in the database, so the system will instead use the default configuration that is defined in the feature module's code.

https://www.drupal.org/node/582680

I am not sure what caused the error you received.  It might be related to the steps you used.  I'd try again and see what happens. :)


How to get the media title and url to the media entity

Got it figured out. Steps:

In Structure > Media Types > File > Manage Display, set the format as Generic File, click the gear icon, and turn on Use description as link text.

Next, inside of Structure > Media Types > File > Manage Fields, edit the field_media_file field and make sure the checkbox for Enable description field is checked. Now, when creating a media file entity, there is a description field that can be filled and will display as the link text.


Use the Global Redirect module to achieve this: https://www.drupal.org/project/globalredirect


Actual output in view is different than preview

Change your filter to include content of that particular content type. Does it pull just that gallery?

Also, screen shot of your view admin panel would be helpful.


Translate a JS string from interface translations doesn't work

Which string you want to translate before that you can use  Drupal.t

like

var optionsList = '<option value="" selected>' + Drupal.t('Navigate...') + '</option>';


How to validate dependent fields for a content type?

I'm not aware of a way to get this to work using the Rules module. Because even if you use Rules Action "set a message" (of type = error) the node will still be saved. For more details on this, and/or possible work arounds, refer to my answer to "How to add a confirm dialog to node add and edit forms?".

If you really want to get this to work with Rules, a possible work around for your case might be to also use the Conditional Rules module, so that in your Rules Action you could "add a Rules Condition" (yes!) to check which option got selected for "venue". And if it is NOT "other", then within your Rules Action you set some dummy value (like "n.a."?) for "venue address" and "venue name".

Plan B

An alternative solution that you may want to experiment with (to see if it works in your case), is the Conditional Fields module. Excerpt from its project page:

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.

  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

  You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


Load JS only on specific content_type node creation

you need to write a simple module where you hook into the page you need and add drupal_add_js()

e.g. when you create a content type the form node_type_form is being called. so you have to hook into the form with

/**
 * implimentation of hook_form_alter()
 */
yourmodulename_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
}

I asume you need to add a JS to a content_type being viewed. in this case you will need to use hook_view() :

/**
 * implimentation of hook_view()
 */
yourmodulename_view($node) {
    if ($node->type == "your_type") {
        drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
    }
}

Update:

of course you can modify your template.php in the theme directory as well. remember that the theme for administration is different than the site theme by default. be aware which template.php file you are changing.


Changing a user password through phpMyAdmin

Drupal 7 uses a hash salt (see your settings.php) in addition to several other bit of information in order to create a SHA2 of the users PW. You should really use drush to change a user's pw if you need to.


An array with #markup is a render array, just the most basic version of it. If you want to use a theme or template, then just do so. Using and defining templates hasn't changed that much compared to D7, the biggest difference is that they're now html.twig files and not .tpl.php.


How to configure a server with 4g of memory to run drupal 7

If you already have Drupal7 Data, you should load it into a staging environment and perform some buffer sizing based on the amount of data you have.

Step 1) You must first compute the buffer sizes for your dataset.

Step 2) If the recommended sizes exceed 75% of your installed RAM (in you case 3GB) then cap the needed buffers at 3GB.

Step 3) If you have InnoDB data and you did not enable innodb_file_per_table, you need to cleanup InnoDB by segmenting each table into its own physical tablespace (this only needs to be done once).

Once you have done this, you should plan to perform this configuration audit (Steps 1 and 2) every 6 months to make sure you have the proper MySQL caching in place.

Interestingly, I addressed a question similar to this and answered it on April 15th, 2011.


Try this tricky method

{% set slider2 =content.slides %}

 {{content.slides}}

{{slider2}}


Missing group audience field(og) from node add form by panel

It's a bug in "og/includes/og.field.inc". When the form is built twice "og_field_widget_form()" returns an empty array, thus the element has no options and seems to be missing.

Here is a link to the bug tracker: https://www.drupal.org/node/2481709

Issue is still open. For now I just commented the offending if-block out.


How to have custom ajax commands on element using InvokeCommand

These are some examples you can try:

$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'addClass', array('show')));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'removeClass', array('show')));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'attr', array('value', '123')));
$response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('.message', "Show this text"));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'css', array('background', '#dff0d8')));

Peace.


How do you redirect anonymous users to another page without rules?

I think something like below should work.

function modulename_init() {
  global $user;
  $args = arg();
  if(!user->uid && ($args[0] == 'user' && $args[1] == 'login')) {
    drupal_goto('page_you_want_anony_to_redirect_to');
  }
}


Show available languages, but remove "Language Undefined"

I know I'm not answering the question directly, but you can disabled 'Language Neutral' (and other languages) on a per-content type basis using Disable "Language neutral".


How do I access variables displayed in devel?

If you want to do any theming to node use node.tpl.php instead of page.tpl.php

in page it is not suggested. If you want to render a field in node.tpl just write the following

<?php print render($content['menu_name'])?>

or simply

<?php print $node->book['menu_name']; ?>


1 - Use captchas and spam filtering; Mollom is a good place to start. There is also  info on hardening Drupal in the drupal handbook, ie. http://drupal.org/writing-secure-code.

2 - For starters, turn on the performance module that comes with Drupal.

3 - This is a big question. I have heard good things about Context HTTP Headers, a module contributed by the White House Drupal team. You can find a comparison table on Caching: Moduls that make Drupal scale.


How to hide user profile(edit current password, email, picture, everything) based on role?

You can set access for fields as FALSE as per user roles.

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state) {
  global $user;
  if(in_array('your_role_name',$user->roles)) {
    $form['account']['pass']['#access'] = FALSE;
    // Similarly other fields, but fields can not be required fields on profile.
  }
}


The right way is to uncheck the "Views API" flag in display settings.


How to add Javascript in Drupal 7 with jQuery?

I may be wrong but I would remove your inner foreach and just use your $b variable instead of $no.

Alternatively here is another way to do it:

http://jqueryui.com/accordion/


Why am I failing to programmatically create a webform in hook_entity_insert?

The problem was at line:
'elements' => Yaml::encode($elements)

The solution is to replace the Yaml in the use statement:
from:
use Drupal\Component\Serialization\Yaml;

to:
use Symfony\Component\Yaml\Yaml;

I don't know the exact explanation, it just works on my code.


Web form Report crashes upon adding date field

I'm not in situation where we can easily update Drupal because of work environment, the solution was forena reports, which offer full freedom in sql queries(not limited by Webform report or Views limits when creating sql) also result(report) based on query can be shown in drupal interface, just needs some more css adjustment in table header/table data widths for columns

Nikola


Views is ignoring my field .tpl.php file when the field is used as a replacement pattern in a rewritten field

Have you tried using the other method? Using template.php. I don't have time to test this, so consider this as a possible answer.

Add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder)

function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){
        $vars['fields']['field_name']->content = 'hello world';
      }
    }

replace themename with your theme name
replace view_name with your view name
replace block_1 with your machine name
replace field_name with your field name


this hook_uninstall isn't deleting fields in my module!

It looks like your uninstall hook is incorrectly named and not invoked.

Current (line 137):

function _customer_testimony_uninstall() {

Try change it to:

function customer_testimony_uninstall() {

(No underscore in the beginning)


How to disable Webform form element validation without removing required flag?

After some more trial and error I found my mistake. The '#needs_validation' property of the element is set at a later stage than the hook_form_alter() call.

In my hook_form_alter() implementation I added a custom validation function in which I unset the property. The trick is to actually unset it, because it's only validated with an isset() call.

function mymodule_webform_client_form_FORMID_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#validate'], 'mymodule_validate_FORMID');
}

function mymodule_validate_FORMID(&$form, &$form_state) {
  unset($form['submitted']['FIELDNAME']['#needs_validation']);
}


How can I set “This block (override)” programmatically on a view's display

If you can't find a way to do this with the methods of Views API, you can try another approach by using the view entity (storage), which provides a more direct access to the display settings in an array.

Example

$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
// add a new display
$storage->addDisplay('block', $new_title, $block_id);
// get the new display by reference
$new_display = &$storage->getDisplay($block_id);
// copy the configuration and change the filter settings
$old_display = $storage->getDisplay($old_display_id);
$new_display = array_replace_recursive($old_display, $new_display);
$new_display['display_options']['filters']['nid']['value']['value'] = 123;

$storage->save();


I want to put values from additional database in drupal 7. How can I do it?

This thread: https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data discusses this issue quite thoroughly.


How do I check if a node is an organic group in an access callback of a custom module?

You've stumbled across an early design flaw on my part, I didn't realize how important it would be to be able to make async calls when determining access to elements (pages, blocks, etc). To get around this (and other related issues), I added some helper functions to DrupalGap core.

The idea behind it is that the built in pages in DrupalGap are there for very simple applications, and more complex applications should build their own pages.

More info: http://docs.drupalgap.org/7/Entities/Rendering_Entities

The general idea is that you build a custom page(s), which will have a fully loaded entity delivered to its page_callback (which under the hood is actually a pageshow callback masquerading as a page_callback: http://docs.drupalgap.org/7/Pages/Page_Events).

Then in your page_callback when you are building the content object you already have access to the fully loaded entity, so you can make intelligent decisions about what is displayed.

With your example (and using the first link above), I'd recommend making a page with a path of group/%, and in your page_callback you can use custom widgets to simulate the block you are looking to render:

function my_module_group_page(node) {
  var content = {};
  content['my_nav_block'] = {
    theme: 'my_module_nav_block',
    node: node
  };
  content['foo'] = { /* ... */ };
  content['bar'] = { /* ... */ };
  content['etc'] = { /* ... */ };
  return content;
}

function theme_my_module_nav_block(variables) {
  var html = '';
  var node = variables.node;
  html += node.title;
  return html;
}

In hindsight it was silly of me to try and replicate Drupal's built in pages within DrupalGap (besides the user login/registration pages, etc) because every application should be unique. I now stricly use this approach and no longer use the vast majority of the built-in pages within DrupalGap.

So to answer your actual question, I would recommend building a Views JSON page display which only returns Group nodes, then your app can feed off of that and display a list of Group nodes, that when clicked go to your custom Group page.


Can I define the minimum php version for my module in my .info.yml file?

Sometimes the answer to a question is best found by trying. If you add php: 8.0 to your module.info.yml file you will see this:

So it can still be used. (I have updated the linked documentation as well.)


How to make autocomplete search by an entity field instead of by name?

Create a new view with the display type "Entity Reference"
Add "Fields", "Filter criteria" and "Sort criteria" like in any other normal view
Under "Format > Settings", select the fields you want to be searchable
Under "Show > Settings", select the fields you want to show as search result
Save the view
Now visit "Structure > Content type > NODETYPE > Manage fields"
Edit your entity reference field, set the "Reference Method" to "Views: filter by an entity reference view"
Select your previously created view


how to add link to null path in menu in drupal 7

You can use the Special menu items module.

  Features:

  User can create a new menu item and place either "<nolink>" or "<separator>" to the Path field, without quotes.
  "<nolink>" item will be rendered similar to a normal menu link item but there will be no link just the title.
  You can change HTML tag used for menu item
  "<separator>" item will be rendered to an item which is no link and by default title will be "-------".
  Breadcrumb of "<nolink>" will be rendered same as "<nolink>" menu item.
  CSS class "nolink" is added to "nolink" menu item.
  CSS class "separator" is added to "separator" menu item.


Programmically add multiple empty fields on a multiple value field/form

Have tested this in Drupal 8 but I think it is the same for drupal 7.

if($form_id == 'node_MYCONTENTTYPE_form') {
  $item = $form['FIELD_MY_FIELD_NAME']['widget'][0];
  for ($n=1; $n<5; $n++) {
    if(!isset($form['FIELD_MY_FIELD_NAME']['widget'][$n])) {
      $form['FIELD_MY_FIELD_NAME']['widget'][$n] = $item;
    }
  }
}


Type hinting - which is better, UserInterface or AccountInterface?

UserInterface extends ContentEntityInterface, EntityChangedInterface, and AccountInterface. This means there are methods an object implementing UserInterface needs to have but objects implementing AccountInterface don't need to have. For example, there is UserInterface::hasRole(), but AccountInterface::getRoles(); in the first case, there is a helper method allowing to check the object has a specific role, while in the second case you would need to write your code for that, getting the list of the roles with AccountInterface::getRoles().
Which hint should be used is given from the documentation. For example, hook_user_logout() gets an object implementing \Drupal\Core\Session\AccountProxyInterface, since it gets the object returned from Drupal::currentUser(). See user_logout(), the function invoking hook_user_logout().
  $user = \Drupal::currentUser();

  \Drupal::logger('user')->notice('Session closed for %name.', array('%name' => $user->getAccountName()));

  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

Sometime the documentation for a hook doesn't show a specific hint, such as in the case of hook_user_login(). In this case, it could help to see which hint is used from the implementations of that hook, for example system_user_login(), which uses UserInterface as hint for its argument.
When you aren't sure about the correct interface implemented by the object passed to a function (including a hook), use the most generic one as hint. In the case you describe, that would be AccountInterface.


How to implement a user profile attribute to indicate "Where did you hear about us"?

This question does not say if it is about D6 or D7, but how about just a pull-down selection list (could be a checkbox as well if you prefer)? Similar to what you can see on this registration page, around the middle of the page (still a D6 site, D7 should be similar).

If it makes sense, I'd be happy to further enhance my answer to include the details of how I implemented that (piece of cake).

Note: please do not submit a real registration request if you checkout the link I added here ... unless you really want to sign up there (which requires prior approval ... ).


How to filter a view by the value of a global variable (as with the variable module)?

Use contextual filter and Provide default value = PHP Code


Access control for announcement users to view via link

Try Node authorize link.

  Generates link for view, edit, or delete content without login.

  Module maintains authorization key for every node and gives additional
  grants (view/edit/delete) to every user (anonymous too) who accesses
  page with correct key in URL. Module offers function
  node_authlink_get_url($node, $op = 'view') for generate absolute URL
  to selected operation (e.g. for e-mail notifications).

Although the module is minimally maintained I used it two years ago and I did the work.

You can generate links that an anonymous user can use to get access to view a node, for example. I think it works with Conent Access, but not I'm not sure. May be you have to tweak precedence.


How do I access a custom variable in block.tpl.php?

You have defined your block with hook_block_info(). Now you need to use hook_block_view() to add your variables to the content array which can be called in your template file.


You could use Profile2 to get you started. It will allow you to assign profile fields to roles and have them available upon registration. You could then use jQuery to display the proper register form on selection.


A little late but there's this module: https://drupal.org/project/location_feeds
Location Feeds :D

Haven't actually tried it yet but It seems to do exactly what you want.


How to define custom messages in Drupal 7

I just did this the other day, it's a bit of a hack, but I couldn't find another way.  The basic premise is to get and clear all current messages, loop through and call drupal_set_message() on all of them over again, changing the one you want:

<?php
/**
 * Submit function for the message node form.  Check for new message notification and change it.
 */
function mymodule_message_node_form_submit($form, &$form_state) {
  $node = $form_state['node'];
  $t_args = array('@type' => node_type_get_name($node), '%title' => $node->title);
  $replace_message = t('@type %title has been created.', $t_args);

  // This call will get all messages and clear them from $_SESSION
  $messages = drupal_get_messages('status');
  foreach ($messages['status'] as $message) {

    if ($message == $replace_message) {
      drupal_set_message(t('Thank you your message has been sent successfully.  We will be in touch shortly.'));
    }
    else {
      drupal_set_message($message);
    }
  }
}
?>


Is there any security risk to use getenv() inside settings.php to populate databases variable from a .env file?

If the .env file is outside the server document root, using getenv() is similar to putting the hash salt in a file and reading it with file_get_contents() as the following comments in the default.settings.php file suggest to do. (The same comment is present in the default.settings.php file for Drupal 7, so it's not a matter of which Drupal version is used.)

/**
 * Salt for one-time login links, cancel links, form tokens, etc.
 *
 * This variable will be set to a random value by the installer. All one-time
 * login links will be invalidated if the value is changed. Note that if your
 * site is deployed on a cluster of web servers, you must ensure that this
 * variable has the same value on each server.
 *
 * For enhanced security, you may set this variable to the contents of a file
 * outside your document root; you should also ensure that this file is not
 * stored with backups of your database.
 *
 * Example:
 * @code
 *   $settings['hash_salt'] = file_get_contents('/home/example/salt.txt');
 * @endcode
 */
$settings['hash_salt'] = '';

If that is considered enhanced security, the same can be said for reading some values using getenv(), if the file containing the values of the environment variables is not in the server document root.

Keep in mind that, if somebody would be able to write a PHP file on the server, it would also be possible for them to read the environment variables and the file containing the hash salt.


How can I make the fields in my views "searchable?"

I would recommend checking out the Search API module. It's an extremely powerful extension to regular Drupal search, allowing you to use many advanced search backends and also integrates with Views to allow you to search on any field you wish.


How to save the "user agent" in the Drupal logs?

Using hook_watchdog, you can manipulate all, or some of your log messages. You can find the user agent string in the super-global $_SERVER['HTTP_USER_AGENT']. This way you could for example prepend all "notices" with the user-agent, and all errors with both user-agent and remote IP.


How to get a friend's education and work history information using FBoauth module

You may want to check your permissions to make sure that FB hasn't changed anything as they are notorious for changing their code. Here are the Permissions Reference.


Based on what you've mentioned, you will want to install drupal 7 separately and try Wordpress Migrate.

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

It only needs the export of Wordpress which can be done in the Wordpress admin.

You will want to try this out first on your own machine, Acquia Dev Desktop will work for you. Read through some of the docs and walkthroughs on the migration. I've done it a few times, it's very quick and typically works fine.

https://www.acquia.com/products-services/dev-desktop

Once you are setup and established, you can migrate to Drupal 8.2.x-8.3.x without much trouble.


The db columns for a date field's start and end are value and value2 respectively. The usual method to set them would be:

$node->field_date[$node->language][0]['value'] = $from_date;
$node->field_date[$node->language][0]['value2'] = $to_date;


I want to subscribe an user to a Mailchimp list as soon as their account is activated

Try below code ... You are missing 5th argument in mailchimp_subscribe_user

function mymodule_user_presave(&$edit, $account, $category) {
  if ($account->uid // user is not new
      && $account->status === "0" && $edit['status']==1) { // user is being activated

        $mcapi = mailchimp_get_api_object();
        $list_id = 1;
        $list = mailchimp_get_list($list_id);
        $mergevars = mailchimp_lists_load_user_mergevars($account, $list);

        watchdog('mymodule_log', 'account->uid '.$account->uid);
        watchdog('mymodule_log', 'list->id '.$list_id);

        mailchimp_subscribe_user($list, $account->mail, $mergevars, TRUE, $mcapi);

        watchdog('mymodule_log', 'got this far!');
  }
}


Adding an entity reference field to entity

You need to go to the admin section for your entity / entity types, and add fields with the Manage Fields tab (just like you would for content types).


How to add product details to Drupal Commerce order confirmation email

you can do that by using php code inside text message body.

$wrapper = entity_metadata_wrapper('commerce_order', $commerce_order);
    $line_items =  $wrapper->commerce_line_items->value();
    foreach($line_items as $line_item){
        $product = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
            echo "Product Title :".$product->title;
            echo "Product Title :".$product->type;
     }


What is the database relationship between node_type and taxonomy_vocabulary tables?

Not to discourage database deep-diving, but if you're bootstrapped into the Drupal system with your system (i.e. programmatically creating nodes), then you don't have to necessarily understand how the DB works to get this working. Just use the functions in the node and taxonomy API to generate your array.

Specifically, lets say you wanted to try for option #1. You could use

node_type_get_types()

to pull a list of all of your content types, and then iterate through that to generate a list of taxonomy terms for each vocabulary. Here is a function I've used before to that effect, from VicTheme.com

/**
 * Helper function return all the taxonomy terms of a given node type
 * @param $type
 * The array of machine name of the content type that the function should look for taxonomy terms
 * the array format should be : array('machine_name');
 * @return
 *   An array of taxonomy terms containing tid => human name.
 */
function vt_commerce_api_get_vocabulary($type = array()) {
  // break if there are no types specified
  if (empty($type) || !is_array($type)) {
    return FALSE;
  }

  $output = array();
  foreach (field_info_fields() as $field) {
    if ($field['type'] == 'taxonomy_term_reference' && is_array($field['bundles']['node'])) {
      foreach ($field['bundles']['node'] as $content_type) {
        if (in_array($content_type, $type)) {
          foreach ($field['settings']['allowed_values'] as $value) {
             $output[$value['vocabulary']] = $value['vocabulary'];
          }
        }
      }
    }
  }

  return $output;
}


How to delete a content type field without deleting the whole view?

As per the following issue registered on Drupal.org, that is what  happening with D8 views hence you are observing that phenomenon. While in drupal 7 the view  gets automatically updated. You  can find the registered issue with drupal 8 core on  drupal.org at following link.

When deleting a content type field, users do not realize the related View also is deleted

That issue is in review phase, hence probably significant work would have been done on that issue. You need to refer that.

If you read the entire discussion there, currently they are working on the idea of Comment #59. suggested by @dawehner which is stated/pasted below,

  Here is alternative approach:

  Don't delete existing views
  Disable existing views and tell people which ones got disabled
  Then the user can go back to this view, fix missing fields and call it a day


You need to use l function to print links in Drupal... It has support for language

global $language;
print l("Info", "info",  array('language' => $language->language));


Drupal already includes jQuery. You should not add another jQuery library because this can cause conflicts with the existing one.

I suggest you to use jQuery Update if you want to use another version of jQuery.

If what you want is to run your own javascript code, you could add it using drupal_add_js().

Hint: Try first with alert('hello world'). See Working with JavaScript and jQuery.


4k4's comment was helpful in that it indicated the correct behavior.  This isn't what was happening; the POST requests were returning correctly, but I assume they're not returning a correct part of the dialog to replace.
However, with this knowledge in mind, I was able to use Configuration Management to export the View and the Entity view display, pull the appropriate setting names from the Entity view display, and manually apply them to the View YAML and reimport.  It's imperfect, but knowing that this should be possible was a great help in finding a workaround.


Replace data from command line: site name

The values are serialized using the built in PHP function serialize() so setting them directly shouldn't work if I understand what you did correctly. You can use drush since it appears you have that available.

Simply use:

drush variable-set site_name "Some name here"

Otherwise you can always configure from the Drupal admin interface.


How to fix millions of Alt Text are missing on body content?

Try using the Search and Replace Scanner module to search through the text of your body field. You could use a regular expression to search for image tags without alt attributes.

Some excerpts from the module page:

  Features

  Can search and replace text in CCK text fields, in addition to standard node title and body fields
  Plain text search and replace regular expression search and replace
  Case sensitive search option

This module is designed to work on MySQL and dedicated servers, be sure to review the module page and accompanying documentation.


How get commerce order total(excl vat, exlusive dicount), vat price, discount price, order total(incl vat and discount) in rules?

There appears to be a feature request for this in the Commerce issue queue.

This post here describes what you'd need to do to add this to your site.


You can use Pathauto and Global Redirect Module.


Pass a variable from a node to a block module that uses a custom template

When using a custom theme wrapper for your block output, you actually theme the content parts, before the block will be rendered using the actual block theme wrappers.

If you like to pass in variables to your custom template, you need to provide them via the second parameter of the theme() function:

/**
 * Implements hook_theme().
 */
function jsblock_theme($existing, $type, $theme, $path){
  return array(
    'jsblock_custom_theme' => array(
      'variables' => array('my_title' => NULL),
      'template' => 'jsblock_custom_theme',
      'path' => drupal_get_path('module', 'jsblock') .'/theme/',
    )
  );
}

/**
 * Implements hook_block_view().
 */
function jsblock_block_view($delta) {
  $block = array();

  if($delta == 'jsblock') {
    $variables = array();
    $variables['my_title'] = get_the_page_title();
    $block['content']['#markup'] = theme('jsblock_custom_theme', $variables);
    $block['content']['#attached']['css'][] = drupal_get_path('module', 'jsblock') . '/css/styles.css';
  }

  return $block;
}

Note the difference between the $variables and the $block array.

To also cover your second question (which surely should go into a separate question on Drupal Answers):

Keep in mind, that blocks are cached by default for performance reasons, until you clear the caches. So with your current implementation the block view will be generated only once and hence the JavaScript only attached to the first page you render after a cache clear.

Therefore you should attach your JS to the block output as you did with your CSS (attach it to the content part of the block output) and make sure to have a distinct cached version of the block for every page by using appropriate cache tags in your hook_block_info():

/**
 * Implements hook_block_info().
 */
function jsblock_block_info() {
  $blocks = array();

  $blocks['jsblock'] = array(
    'info' => t('My JS block'),
    // Use DRUPAL_NO_CACHE for no caching, or
    // DRUPAL_CACHE_PER_PAGE if you are fine with
    // cached versions per page.
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}


How to get the site url in views custom output

Try to add field handler "custom text" and rewrite result as on the screenshot

but put there your field name instead of [title].


Hidden form values updated with multiple submission

You can use jQuery to change the submit button to a loading gif when the save button is clicked. Thus, preventing any more clicks.

(function($) {
  $('.form-submit').click(function() {
     $('.form-submit').html('<img src="https://media.giphy.com/media/TtZqlvHid7BjW/giphy.gif">');
  });
})(jQuery);

JS Fiddle Example


Show only unread content; remove item once read or option to remove items

You can filter nodes exactly this way (a node filter called timestamp I think).

I'm not sure what the best way would be to solve the "x" button thing. Maybe add an extra binary field to the contenttype which you set via ajax (triggering a function you defined via "page callback" in hook_menu()) when clicking the "x". Then you have to add this field to your views filter as well.

Edit:

Instead of an extra CCK field you could also insert data into the history-table (uid, nid, timestamp) of drupal and pretend the user has already viewed the node. This way you would only need first views filter.


How to create user like drop-down filters for a custom module in admin side

Well you have 2 options:

Declare your custom tables with Views. This can be tricky, and take some trial and error, but gives more flexibility going forward.
Declare a custom page in your module (using hook_menu). Then just build a form with the search options you want and build a query. See the Examples modules if you're not sure how to build a page.


For a Drupal 7 site using Cloudflare CDN and a Bootstrap theme, this worked for me: Set the base URL in your settings.php file, without including http:// or https://.

$base_url = '//my.domain.name';

For another Drupal 7 site with a different theme, just removing $base_url worked.
In both cases, I needed the site to work with secure URLs and without.


I believe that your problem would be solved by adding a relationship to your view. Here are the steps:

Add Relationship: taxonomy terms on node
Select the vocabulary you want to use.
Add Relationship: parent term

Now you should be able to add fields from any of the terms or their parents, and to use them as contextual filters as well.


Meanwhile I got this figured out. The second argument of MigrateSQLMap is a field => schema array and you can fill in those fields in function prepareKey($source_key, $row) as necessary, say

function prepareKey($source_key, $row) {
  $row->vendor_id = $this->vendorId;
  return parent::prepareKey($source_key, $row);
}

Note: prepareRow is too late, you want prepareKey.


jQuery only works if I hard code it into the html.tpl.php

Drupal core ships with jQuery. You can check the version in your <drupal_install_directory>/misc/jquery.js file. If you want to use the later version of the library, you need to install the jQuery Update module.

  Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
  Updates...

  Drupal 5 to jQuery 1.2.6
  Drupal 6 to jQuery 1.3.2
  Drupal 7 to jQuery 1.5.2/1.7.1/1.8.2, and jQuery UI 1.8.11


WSOD while sending headers, probably Cache-related

Now I could solve it myself. My Apache error logs did show

AH00052: child pid 7363 exit signal Segmentation fault (11)

so it must have been a problem with the Apache config.

I took the opportunity to reinstall Apache and configure it with FCGI/FPM according to this and now the problem is gone.


How do I hide the page title in Drupal 7?

You can update the template for the Content type or that specific node.

I tend to use CSS to hide the page element if it is only one page title/node I am trying to hide.


The throbber has a class of .ajax-progress-throbber.

Before the Ajax call, add an element with that class to wherever you want it in the DOM, and simply remove it again when the Ajax request completes. Drupal doesn't have any helper methods for this, just use jQuery.


Content Type Display different per theme

Those settings are one per content type and will be applied for all themes you enabled.

I suggest to do that within the themes themselves - start by adding the node--[content type machine name].tpl.php and then exclude/move around the fields you need.

Example for hiding a specific field:

hide($content['field_name_goes_here']);

Other useful things:

hide($content['links']);
hide($content['comments']);

To see a full list of fields and exact names, install devel and do a dpm($content); in tpl file.

Also check the template_preprocess_node() function for more and better control of the fields values.


How to get rid of auto generated classes in secondary menu links and add my own classes

You can use this preprocess hook to modify the menu classes.

For example, modify the output of the secondary menu links like this.

function YOURTHEME_links__system_secondary_menu(&$variables)
{
   $output = "";

   foreach ($variables['links'] as $item => $link) {
      $classes = array('class1', 'class2');
      $output .= sprintf('
%s
', implode(' ', $classes), l($link['title'], $link['href']));
   }

   return $output;
}


Services 3 - updating a custom field in a user account

Switch between different content types and test, for example, application/json works perfectly for me. You need to do the following steps:

Request CSRF token /services/session/token (sample request below)

request.get({url:'https://serveraddress/services/session/token'}, function(error, response, body) {
if(!error && response.statusCode == 200) {
  console.log('CSRF Token obtained : ' + body);
} else {
  console.log('Failed to retrieve CSRF token.');
}
Make use of the obtained CSRF token to perform authentication (if needed), sample below

// Set the headers
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token' : token
};

// Configure the request
var options = {
  url: 'https://serveraddress/servicesendpoint/user/login.json',
  method: 'POST',
  headers: headers,
  body: 'username=yourusername&password=yourpassword'
};``

// Start the request
request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
      var jsonBody = JSON.parse(body);
      console.log('Authentication succeeded, cookie value is : ' + body);
      console.log('SESSID : ' + jsonBody.sessid);
      console.log('SESSION_NAME : ' + jsonBody.session_name);
      console.log('Token : ' + jsonBody.token);
    } else {
      console.log('Authentication failed. Error is : ' + error);
      console.log('Authentication failed. Body is  : ' + body);
      console.log('Authentication failed. Response is : ' + JSON.stringify(response));
    }
});

Now that you have SESSION NAME & SESSION ID, you can proceed with updating a node. See sample below.

//set headers
  var headers = {
              'X-CSRF-Token' : authResult.token,
              'Content-Type': 'application/json',
              'Cookie' : authResult.session_name + '=' + authResult.sessid
            };

  // Configure the request
              var options = {
                  url: 'https://serveraddress/serviceendpoint/node/' + user.result.nid,
                  method: 'PUT',
                  headers: headers,
                  json: data
              };

  request(options, function (error, response, body) {
            if(!error) {
                console.log('Drupal node is updated successfully!');
                console.log(body);
            } else {
              console.log('Updating Drupal node failed! Error status : ' + response.statusCode);
              console.log('Updating Drupal node failed! Error body : ' + JSON.stringify(body));
            }
          });

If you notice above, I am console logging all the errors that is returned from the Services, so that I have something to Google and figure out.

For those who wish to know how to upload a file and associate them to a node. Assuming that Service Endpoint is configured to accept file uploads. You will need a sample request as below:

     //data
     var data = {
       "uid":"1",
       "filesize":fileSizeInBytes,
       "filename":user.firstName + '_' + user.lastName,
       "file": base64Image
     };

 var options = {
       url: 'https://serveraddress/servicesendpoint/file',
       method: 'POST',
       headers: headers,
       json: data
     };
request(options, function(error, response, body) {
       if(!error) {
         //photo is uploaded, returning fid
         console.log('Publishing Image to Drpual succeeded. FID is : ' + body.fid);
       } else {
         console.log('Publishing Image to Drpual failed. Response is : ' + JSON.stringify(response));
         console.log('Publishing Image to Drpual failed. Body is : ' + JSON.stringify(body));
       }
     });

Attach the returned FID to the request that is supposed to update the node.

Sample JSON to update a field of a content type would look like this:

data = {
      "body": {
          "und": [
              {
                  "value": user.profile,
                  "format": "full_html"
              }
          ]
      },
      "field_member_position": {
          "und": [
              {
                  "value": user.title
              }
          ]
      },
      "field_member_photo" : {
        "und" : [
          {
            "fid" : fid
          }
        ]
      }
    };
  }

Hope above help those struggling with using Services 3. The code is written in Express JS 4 and I have used the request NPM module.

A simple checklist for Services 3 would be:

Configure the module (request content type, as well as allow CRUD on nodes/files as per your need)
Make sure you are hitting the correct URL to get token, authenticate and update node, upload file
Watch for famous errors such as Not Acceptable Content type, Trying to Authenticate as anonymous user, A particular field is required (username/password), others

When trying to update a custom field, it is more useful to SEE that particular node's structure via DEVEL and then accordingly structure your JSON data.


Have you looked at the view permissions?  They override drupal core permissions.

Also, is there an order content type, or entity type?  You have to grant anon and auth users access to view their own order content type in drupal core permissions.


How to add class to specific TD in view table?

1) click on desire field under 'Fields' in your view

2) select 'Style Settings'

3) check 'Customize field HTML' checkbox

4) check 'Create a CSS class' checkbox

5) enter 'replace-this-class' in 'CSS class' text field

then you should look into hook_views_post_render - this where you can access the actual html output for each row. if you add a class to the field as described above, you will be able then do php find and replace based on any logic.

my_module_views_post_render(&$view, &$output, &$cache) {

    foreach ($view -> result as $result) {

        //not sure about that - you would need to debug that
        $result_status = $result -> status;

        //your php logic and new class assignment
        if($result_status == 1) {
            $class = 'new-class';
        }

        //what you want to replace - again double check that
        $replace = '<td class="replace-this-class';

        //alter `$output` variable
        $output = str_replace($replace, '<td class="'. $class .'"', $output);

    }

}

This is very ugly but it works. Of course you will need to look into the $output variable to make sure that you are targeting correct html.


How can I watermark images with a taxonomy term from the node they belong to?

Problem solved — Rainer Feike's comment prompted me to examine the field setup and I realized I had made an error in the way I set it up that was causing the token not to resolve (there were two taxonomy fields on the original product content type, referencing two different vocabularies, and I had matched the wrong field name with the vocabulary in setting up the test content type I was trying out the new image style on).
Once I corrected that it worked. My apologies for posting about what turned out to be a self-created problem.


Try using this old method

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Replace example with your domain name.

Still if you have the problem check your Redirects in Hosting Control Panel or you can contact them to support this.


Content not displaying for anyone other than Admin

Ok,
So...In fact I verified the permissions of a body field of a block within a mini panel (yeah right...) and there were no permissions for anonymous user to view. So I checked that for only one block and somehow it all went right without changing anything else. So there's that.

Thx anyway for your precious time.


The passed arguments are kept in $form_state['build_info']['args']. You can find a documentation of the $form_state structure here: drupal_build_form().


How can I add password fields to the account creation page?

Although it doesn't mention it on the module description page, this is one of the features of LoginToboggan, which also addresses a number of other common login confusions (ie: a user can log in with their email address or username, prompt for login instead of permission denied page).

From the documentation:

  Set password
  Ticking this will allow users to enter their desired password when they set up their user account.


remove theme tab on blocks for certain roles

function HOOK_menu_alter(&$items) {
  global $user;
  if(in_array('administrator', $user->roles) == FALSE && in_array('admin/structure/block/list/seven', array_keys($items)) == TRUE) {
    // This allows the path to still be registered but not displayed
    $items['admin/structure/block/list/seven']['type'] = MENU_CALLBACK;
  }
}


Custom translatable content entity appears twice when choosing the entity type to create a view

I don't think it's directly associated with translation handling - it looks like it's the distinction between the entity and entity_field_data table. The "working" option in the dropdown is a class derived from WizardPluginBase.

I fixed my problem by making sure both of these were in my Drupal\custom_entity\Entity\CustomEntityViewsData::getViewsData

$data['custom_entity']['table']['wizard_id'] = 'custom_entity';
$data['custom_entity_field_data']['table']['wizard_id'] = 'custom_entity';`


Put footer/signature on every blog post?

I see 3 pretty easy solutions :

(The easiest) You add a new field textarea to your blog content type. You configure its default value to the content you want (your blog footer content) which can be html (so you're free to type in whatever you want). Then configure the display of your blog post to have this field as the last one displayed. Done.
You can  add a entity_reference field (Entity reference module) to your blog content type. Then create a node which represent your footer, and use it as your default entity_reference field value for your blog content type. (Then you'll have to configure your display modes however you want it ...)
You can probably do this with a hook_form_alter() and insert your footer directly in the form

Hope it helps


You appear to be using stdClass objects for the values in your options array. Drupal expects a string for each of the options.

You probably have code like:

foreach ($something as $item) {
  // $item is a stdClass.
  $options[$item->key] = $item;
}

when you need to have something like

foreach ($something as $item) {
  // $item is a stdClass.
  $options[$item->key] = $item->name;
}


Disable the navbar in a Bootstrap sub-theme

So to add this as an optional setting we can look at how it's done for other navbar variables. For example the navbar positioning which is on line 112 of that settings.inc

  $form['components']['navbar']['bootstrap_navbar_position'] = array(

Let's see where the variables you can select in that are referenced, such as fixed-top. It's referenced in html.vars.php where they implement the hook_preprocess_html() function to take that selection using theme_get_setting('bootstrap_navbar_position') and create some related variables to pass into the classes_array for the html.tpl.php.

So you can create a similar field with options like enabled and disabled and pass that on to the page.tpl.php using YOURTHEME_preprocess_page (which would probably go in template.php) to create a variable like navbar_on when it's enabled

if (theme_get_setting('bootstrap_navbar_enabled') == 'true') {
  $vars['navbar_on'] = '';

 }

and then check in page.tpl.php to see whether or not that's true or not before printing the page.

     <?php if ($navbar_on): ?>
          NAVBAR CODE
     <?php endif; ?>

EDIT: actually maybe this is already in the theme, just not very clear
https://www.drupal.org/node/2287185


How do I get paragraph fields text data without the  tags?

Does your field contain other
 tags you want to preserve? Or just this one in the beginning and end? If you don't need to preserve other
 tags, you could simply use Twig's |striptags filter.

{{ my_var|striptags('
') }}

Or as @Hudri suggested in the comments under your question you may change the field type to something other than formatted text. Or maybe try changing the text format to plain.


Adding a block where an admin can create users on the fly

Well, it's a great opportunity for you to learn how to write a custom block, and a custom form in it:

Create a new block in one of your module
Create a custom form in it.
Place your block somewhere in your page. You are done!

For both block and form creation there are nice articles just for Drupal 8.

Good luck!


How do I modify a core field to use Ajax and add markup?

After much testing and finding a missing character in one line even I was able to come up with some working code:

<?php
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

function fsed_entry_form_eform_submission_fsed_entry_submit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_faculty_member']['widget']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'fsed_entry_faculty_member_ajax_callback',
    'wrapper' => 'faculty-member-details-wrapper',
  );
  $form['field_faculty_member']['widget']['#prefix'] = '
';
  $form['field_faculty_member']['widget']['#suffix'] = '
';
}

function fsed_entry_faculty_member_ajax_callback($form, &$form_state) {
  $nid = $form_state->getValue(array('field_faculty_member', 0, 'target_id'));
  if ($nid) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $storage->load($nid);
    $build = $view_builder->view($node, 'eform_preview');
    $output = render($build);
  }
  else {
    $output = '';
  }

  $form['field_faculty_member']['widget']['#suffix'] = $output . '
';

  return $form['field_faculty_member']['widget'];
}


What you want is the Domain Conf module which is a sub-module of Domain Access and provides you per-domain configuration.

  The Domain Access: Site Configuration module (called Domain Conf), is
  an optional extension of the Domain Access module.  Domain Conf
  provides options for configuring basic settings of your affiliate
  sites to be different.


Can't find custom block php code in the database

Universal solution to find something you know is in the database is:

Dump the entire database to SQL file.

No compression, or uncompress after downloading.
Use one row - one line format - disable "insert many rows in one INSERT statement" and similar options.
Also, disable anything that looks like "save BLOB columns in hex format" - you want serialised variables in human-readable form.

Use grep or similar text search tool to search for the string parts you think characteristic enough to the row you need to find.


How to disable user and e-mail input auto-fill?

Something in the core stores user login and drupal use this information in every form submit, in other lines, I can't let user change 'user' and 'e-mail' inputs. BUT, I found how to change markup and correct my design. Follow...

In 'mytemplate'\templates\form\form-element.html.twig I changed:

...[omitted]...

78.   {{children}}

...[omitted]...

for:

{% if logged_in and element['#type'] == 'item' %}
  <input type="text" name="{{name}}" value="{{element['#value']}}" disabled>
{% else %}
  {{ children }}
{% endif %}

And my form now looks like this:


You can do this by altering the form in your custom module hook_form_alter(){} or
in template.php of your active theme.

Just add the classes in the attributes array().

Or you can create a user-login.tpl.php file following this link, Its already answered here with this code.

<?php
    function operationscheck_theme_theme() {
    $items = array();
    $items['user_login'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
   'template' => 'user-login',

    'preprocess functions' => array(
   'operationscheck_theme_preprocess_user_login'
   ),
);
    $items['user_pass'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
   'template' => 'user-pass',
   'preprocess functions' => array(
   'operationscheck_theme_preprocess_user_pass'
  ),
);
 $items['user_register_form'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme', 'operationscheck_theme') . '/templates',
'template' => 'user-register-form',
'preprocess functions' => array(
'operationscheck_theme_preprocess_user_register_form'
 ),
);

return $items;
}
?>

<?php
   function operationscheck_theme_preprocess_user_login(&$vars) {
      $vars['intro_text'] = t('This is my awesome login form');
    }
   function operationscheck_theme_preprocess_user_login(&$vars) {
     $vars['intro_text'] = t('This is my awesome pass form');
   }

function operationscheck_theme_preprocess_user_register_form(&$vars) {
    $vars['intro_text'] = t('This is my super awesome reg form');
   }

 function operationscheck_theme_theme(&$existing, $type, $theme, $path) {
  $hooks = operationscheck_theme_theme($existing, $type, $theme, $path)

  $hooks['user_login_block'] = array(
 'template' => 'user-login',
 'arguments' => array('form' => NULL)
 );

// @TODO: Needs detailed comments. Patches welcome!
return $hooks;

}

function operationscheck_theme_preprocess_user_login_block(&$variables) {
  $variables['intro_text'] = t('This is my awesome login formX');
  $variables['rendered'] = drupal_render($variables['form']);
}
 ?>

Please check if it is the code snippet you were looking for.


How can I rewrite the values of facets shown in the Current Search block?

The feature is not available by default, but there is a patch to add this to Facet API.


How to make the 'Module Updates' report available again?

Here is a list of items to check:

Make sure core module update (= Update Manager) is enabled.
Clear all caches: if you get a WSOD while doing so, it indicates memory shortage.
Try running update.php: if you get a Fatal error like "Allow memory size of ... bytes exhausted", it indicates memory shortage.
Verify if it is a memory shortage issue: try increasing the memory a bit to check if there is any difference.


Block form: radio buttons selection not saved

I found the problem with this: it was the name attribute. As soon as I removed it, $values['colour_select'] stored the selected color.


How to attach email from a private folder(outside root)

You can use the drupal private file directory notation:

file_get_contents('private://counciltax.txt')


How to remove the click event on an Ajaxified form's submit buttons?

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    $( "#form #submit-button" ).click(function( event ) {
      event.preventDefault();
    });
  }
};

Can you try like this. This will trigger for every AJAX call.


disable the preview and delete buttons on node edit form

Since you are not checking for any particular condition in your code, I would suggest that you remove the preview option from the content type settings.

admin/structure/types/manage/[you_content_type]

Regarding the delete button if you can do it using permissions, you should always do it using permissions. If you do not want to revoke the permission but just want to hide for a particular screen then use

$form['actions']['delete']['#access'] = FALSE;


Why are IDs showing in URLs when clean URLs are enabled?

The Clean URLs setting turns your URLs from index.php?q=node/123 to /node/123.

The path module that comes with core Drupal enables the URL path settings tab on node add/edit forms. Here you can specify any URL alias that will load the node instead of /node/123. These aliases must be entered manually for each node.

The Pathauto module allows you to automatically generate URL aliases. By enabling pathauto and not doing any further configuration your URLs will turn into /content/title-of-node. You can change how the URL is generated in the pathauto settings (so it can be /node/title-of-node for example).


To answer your question: Yes. All you should need is your code sitting on a web server and your data sitting in a database for your Drupal site to go live.

As for suggestions, I have a few regarding workflow. Drupal has a lot of pain points with deployment because not only is the content stored in the database, but most of the configuration is as well. So while you can upload modules, the settings need to be manually set on production, automatically deployed with the Features module, or automatically deployed with update hooks in modules.

Uploading your site for the first time via FTP will work, but it's usually a lot more complicated when deploying updates. Here are a few things that you should learn to help combat this:

My first suggestion would be that you set up a development server (your local dev will work), a staging server to test your deployments, and a production server which will host your live site. It's crucial to have this (or something similar) so you can catch any problems and avoid a production down situation.

Second, you should learn how to use Git for version control to manage and deploy your code. You should use it for all projects, actually, even if you're not deploying them. I cannot tell you how many times I've rolled a change to production that broke the site and was able to roll back with one command. I'm not going to try and convince you why using version control is a good idea because there is an entire internet that says you should. Here is just one article: http://www.git-tower.com/learn/git/ebook/mac/basics/why-use-version-control

Third, assuming that you're using Drupal 7, you should use the Features module to store your settings in code and deploy them via git. Features is a necessary evil in order to accomplish this, and there are a ton of quirks that give it a huge learning curve, but it's worth it in the long run. This answer seems pretty solid. A more advanced and custom approach is to use calls to hook_update_n in your modules to automatically deploy database updates and settings. This article Does a good job explaining it.

Fourth, and probably most importantly, BACK UP YOUR DATABASE AND YOUR CODE. As I mentioned before, Drupal makes heavy use of the database. If you lose that, you lose your site. Make sure you have scheduled backups for your database (and your code if it isn't in Git).

I'm not trying to scare you, but I'll be honest: if you do decide to go this route (and I believe I'm not the only one who thinks you should), there will be a lot to learn and a ton of frustration at first. I can tell you that you're going to have a maintenance nightmare on your hands if you plan to deploy updates by uploading files via FTP.

I have been to a lot of talks and training on this subject at Drupal Camps, Drupal Cons, and Drupal meet-ups, and I'm still learning how to manage deployment. Once you learn the tools and get your workflow down, things will go a lot smoother and you'll be able to recover quickly if anything bad happens.

I hope this helps. Let me know if you have any questions!


Getting exception 1003 when importing images via feeds module

The answer was that the image wasn't found, because my path/to/my/image.jpg was incorrect on my spreadsheet, path/my/to/image.jpg.


How to change the text format of the body field of 200 nodes at once?

The query you suggested is great but if you want to make sure you're only including body fields from the content type you want to update you need to extend it slightly:

UPDATE field_data_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'

You'll also need to run the same query for the field_revision_body table or nothing will happen:

UPDATE field_revision_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'


can we change block title using template_preprocess_block?

See the block_example.module. It's hook_block_view_alter you can use to do this programmatically. You can probably use it in a *.theme as well.

Source block_example_block_view_alter.

use Drupal\Core\Block\BlockPluginInterface;

function MYMODULE_block_view_alter(array &$build, BlockPluginInterface $block) {

  // We'll search for the string 'uppercase'.
  $definition = $block
    ->getPluginDefinition();
  if (!empty($build['#configuration']['label']) && mb_strpos($build['#configuration']['label'], 'uppercase') || !empty($definition['subject']) && mb_strpos($definition['subject'], 'uppercase')) {

    // This will uppercase the block title.
    $build['#configuration']['label'] = mb_strtoupper($build['#configuration']['label']);
  }
}

Most often you find answers to questions like that really fast when you google for Drupal X how to X programmatically or similar.


Go to CCK Time then open cck_time.module

find this:

function cck_time_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items)

change this:

if (($items[0]['hour'] === '') || ($items[0]['minute'] === ''))

to this:

if ( empty($items[0]['hour']) || empty($items[0]['minute']) )

It helped solving my problem getting the same error Undefined index: cck_time_field_presave()


Please make sure your webserver (nginx/apache) is using the same PHP version as your cli one. For example, you may encounter this issue if your cli PHP version is PHP 7.1 and your webserver is using PHP 7.0.


Multiple Registration forms (with unique roles)?

Sounds like profile2_regpath will help you.


How to store temporary metadata for the remainder of a request?

Drupal introduced the Drupal\Core\Cache\MemoryCache\MemoryCache class to, as Added memory cache says, allow classes that would previously maintain state on a protected property (as a static cache to avoid persistent cache or database lookups) to inject a service to hold that state instead.

Drupal core implements two services that use that class, one of them is the entity.memory_cache service, which is defined from the following code.

entity.memory_cache:
  class: Drupal\Core\Cache\MemoryCache\MemoryCache

The other service using that class is the cache.jsonapi_memory service, which is defined from the following code.

cache.jsonapi_memory:
  class: Drupal\Core\Cache\MemoryCache\MemoryCache
  public: false

A module that needs to store data that is valid only for the current request can define a similar service. Setting the service as private is optional, but it avoids other modules uses it, making the stored data private for the module.


Have a child node inherit taxonomy from a parent during /node/add?

I ended up using the Rules module for this. It couldn't do it in AJAX when the parent field was specified, but it could make this happen as soon as the child was first saved, and only if its taxonomies were left blank.

The main rule fires a Ruleset component when a child event is saved, and if the parent event is specified. This Ruleset has two parameters: 1) the parent node and 2) the child node.

Next, the Ruleset component just fires two child rules one after another, one for each set of taxonomy terms:

Finally, each individual child rule checks to see if the child event left its taxonomy blank, and if so, sets it to the parent's. I needed one child rule per taxonomy, so that the empty conditions could be checked individually.

That's it! New child events, upon saving, would get the parent tags if it had none of its own.
The code for the rule:
{ "rules_inherit_parent_event_taxonomies" : {
    "LABEL" : "Inherit Parent Event Taxonomies",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--event" : { "bundle" : "event" } },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "event" : "event" } } } },
      { "NOT data_is_empty" : { "data" : [ "node:field-program" ] } }
    ],
    "DO" : [
      { "component_rules_set_child_taxonomies" : { "parent_node" : [ "node:field-program" ], "child_node" : [ "node" ] } }
    ]
  }
}

And the ruleset component:
{ "rules_set_child_taxonomies" : {
    "LABEL" : "Set Child Taxonomies",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "parent_node" : { "label" : "Parent Node", "type" : "node" },
      "child_node" : { "label" : "Child Node", "type" : "node" }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : {
                "node" : [ "parent-node" ],
                "type" : { "value" : { "program" : "program" } }
              }
            },
            { "node_is_of_type" : {
                "node" : [ "child-node" ],
                "type" : { "value" : { "event" : "event" } }
              }
            },
            { "data_is_empty" : { "data" : [ "child-node:field-topic" ] } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "child-node:field-topic" ],
                "value" : [ "parent-node:field-topic" ]
              }
            }
          ],
          "LABEL" : "Inherit parent\u0027s topics if child has none"
        }
      },
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : {
                "node" : [ "parent-node" ],
                "type" : { "value" : { "program" : "program" } }
              }
            },
            { "node_is_of_type" : {
                "node" : [ "child-node" ],
                "type" : { "value" : { "event" : "event" } }
              }
            },
            { "data_is_empty" : { "data" : [ "child-node:field-audience" ] } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "child-node:field-audience" ],
                "value" : [ "parent-node:field-audience" ]
              }
            }
          ],
          "LABEL" : "Inherit parent\u0027s audiences if child has none"
        }
      }
    ]
  }
}


How to displaying translate tab in the node

This tab does show when:

You have more than one language installed. Locale module needs to be enabled.
You have Content Translation or Entity Translation modules enabled (not i18n)
You have set up the content to be translatable, in the the content type settings page (if it's a node). When using Entity Translation, prior to that, you should define the entity type (e.g. node) to be translatable.
Your user has permissions to translate content.


You need to turn the new form item test into a widget by declaring the item in $form['#info']

So your code should look like the following:

function my_module_form_alter(&$form, &$form_state, $form_id){
  $form['test'] = array(
    '#type' => 'select',
    '#title' => 'New Filter',
    '#options' => array('value 1', 'value 2')
  );

  $form['#info']['test'] = array(
    'value' => 'test',
  );
}


How to resolve the error when posting a new node with Image Field and Entity Reference?

In the end I changed the entity reference field to select list and posted like this:

{
 "title":"test",
 "type":"activity_photo",
 "language":"und",
 "field_node_reference":{
 "und":[1273]
 },
 "field_photo":{"und":[{"fid":"8880"}]}
}

also, I found my own modules was implementing hook_form_alter for this form, and this had further complications to be addressed to get it to work. So any hook_form_alter is something to remember when looking for similar problems.


How do I get the menu block choice "Expand all menu items" to stay checked

That is not the default behavior. I suppose you have installed Menu Block module.

In that case the "expand all" option from Drupal Core does not seem to work, you will need to use the "expand all" option from the Menu Block module. You can find this at "Advanced options" in the block configuration.