Radioactivity and Rules- difference between "add an incident" and "set the energy"

You can do any custom logic you want using the Rules module which integrates with the radioactivity module.

Add an incident to a field - this increments or decrements the energy level by a specified amount.
Set the energy of a field - this sets the energy level to the specified amount.


Error when submit a Webform with Ajax using Jquery

If you want to submit a webform, or any form for that matter, with jquery try calling the .click() event for the submit button or call the .submit() function for the form object.  If it's properly 'ajaxified' by drupal (using the use-ajax class) the click on the submit button should def submit the form.

jquery .click()

jquery .submit()


Personally, I would either write module that abstracts away the need for a global variable, or at least has a getter function for retrieving it.  Something like

function foo_get_the_service ()
{
  static $service;

  if (! isset($service)) {
    $service = foo_init_the_service();
  }

  return $service;
}

Several Drupal API functions do something similar (eg, menu_get_active_trail() and menu_set_active_trail());

And then preferably, your module would also have helper functions so you don't need to access the global directly.  If something really does need the global, then you would use the getter.

If your global is an instance of a proper PHP class, then you could look into using a real singleton.


How to customize a link with a custom module?

The CSS class is a sub-key of the #attributes of a render array like $build:

function private_message_contact_button_node_view_alter(&$build) {
  if (array_key_exists('private_message_link', $build)) {
    $build['private_message_link']['#attributes']['class'] = array('button button--primary', 'btn');
  }
}


$node->type throwing PHP errors, occasionally

If your site is barfing on

$type = $node->type;

then it more than likely means that $node isn't a real node.  If you are using this in page.tpl.php, then I would guess it is because the code is being called on a non-node page.

BTW, you shouldn't need to place any code in template files.  That is what the preprocess functions are for.  If you need to do things with the page template, then check out template_preprocess_page.


I did this previously on Drupal 7 and it might be possible to adapt the process I used:

Via hook_form_alter add an additional submission handler (i.e. form['#submit'][] = '_webform_submit_handler';)

Inside the submission handler function:

Create a new node (i.e. $node = new stdClass();)
Assign the relevant fields (i.e. $node->title = 'Title';, $node->type = "type";, etc.)
Save the node (i.e. $node = node_submit($node); and node_save($node);)


How do I set descriptions to each checkbox option

The #title will be displayed as a description next to the checkbox, description below it if you use single checkboxes in a for-loop.

You need to change it a bit:

$options = array('Option 1' => t('Description1'), 'Option2' => t('Description 2');
$i = 1;
foreach ($options as $title => $description) {
    $form['field_options']['option_' . $i]= array(
      '#type' => 'checkbox',
      '#title' => $title,
      '#description' => $description,
      '#default_value' => 0,
    );
  $i++;
}

Set the value with #default_value = 0; (not an array).

About the 0 value in the array: From drupal.org Form API about checkboxes:
Description: Format a set of checkboxes. #options is an associative array, where the key is the #return_value of the checkbox and the value is displayed. The #options array cannot have a 0 key, as it would not be possible to discern checked and unchecked states.


It should be possible to remove core validation from the field by adding the #form_validate array element to the form element you want to edit, then pass a custom validation callback that passes the field by default.  That should work.


Custom block template doesn't print content

Avoid short tags as not all servers support them.

Use:

<?php print $block->content; ?>

Instead of:

<?= $block->content; ?>

Also in block.tpl.php I would expect to see <?php print $content; ?> instead of $block->content.


I do not have admin access to drupal API but have access to the DB and IIS. I assumed that the content from these tables would export into an editable markup file but this does not appear to be the case. Can i do this without the drupal API?

Kai


Is there a way to have a single field behave as a text field and a file upload/browser at the same time?

Somehow the users have to decide what type of data they want to enter. An option would be to let them choose and then show the appropriate field only. The condotional field module could comme in handy here.


Custom block for anonymous users is shown to every user

First of all, you have to remove the first slash in the show block on specific pages text area :

user/
user/*

will hide your blocks in user pages as expected, while /user/ /user/* won't.

This will solve half your issue. Then check if maybe your theme was complaining because of this misconfiguration detail, and may show now your block for anonymous users only.


In Drupal 8, the core Drupal hook hook_entity_view() is only called when the entity is "being assembled before rendering". See the documentation at https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook_entity_view

After the entity has been rendered, core Drupal will cache the rendered entity and serve the rendered entity from the cache when needed. The entity is not rendered every time it is used. So BY DESIGN hook_entity_view() will not be called again when the rendered entity is loaded from the cache, it will only be called when the entity needs to be re-rendered - that is, when the entity is changed and/or the cache of that entity is invalidated.

This behavior is different from the way it worked in Drupal 7 because Drupal 7 did not cache rendered entities like this.


Hierarchical Select reset when I click add another item

Temporarily I fixed it by rearranging the hierarchical select field at top and add another item field(image field) at the bottom of that field.

You can rearrange the field under Mange Fields.


Permission to create new users but not to manage them

Don't forget to also give those same users the permission to access administration pages -- otherwise they'll be denied anytime they try to access any URI beginning with admin.

Also, I don't think it's necessary (or even desirable) to unset the menu items like that... You should just be able to do this:

function fm_users_more_menu_alter(&$items) {
  $items['admin/people/create']['access callback'] = 'fmu_add_user_access_callback';
  $items['admin/people/create']['access arguments'] = array(1);
}

Finally, remember to rebuild the menus after making such a change.


Try something like this:

file_dir  = $file_create_url("public://");

print 'content . '';


Release naming conventions reports exactly the format used for the release names, and how they are formatted.

In short, the format is [Drupal version].x-[major version]-[minor version]-[flags].

Drupal version is the Drupal version with which the module is compatible
flags are extra identifiers that starts with one of the following string:

unstable
alpha
beta
rc [a.k.a. release candidate]

For a development snapshot, the format is [Drupal version].x-[major version]-x-dev.

"Major version" and "minor version" refer to the module version, where "minor version" is a progressive number.

As for the module not working if the release number doesn't follow the schema, I think the problem is another one; as far as I know, Drupal doesn't check the format, and the release name is only used from the update manager, when it is looking for the module updates, and the module is hosted on Drupal.org.

You should not be worried about the format used for the release version identifier, if not when you are developing a module that is host on Drupal.org. If you are developing a custom module that is not hosted there, you don't need to report the module version. In fact, in my test site I have a test module that doesn't report its version, and Drupal is still able to use it; the only difference is when another custom module depends from that, and it is reporting with which version of the first module is compatible. Then, Drupal will not show the module version in the module page, if the .info file doesn't report that.


Unable to render fields in node.html.twig

This was an issue to do with the Field Layout module. Once that was uninstalled my markup worked as it should.

Field Layout (and also Layout Builder module) moves Drupal towards theming within the UI, so if you're looking to theme with twig files, I'd recommend not installing them.


Using taxonomies to enhance SEO: Hard Situation

From an SEO perspective I'm not sure its a great idea, I have little experience optimizing for SEO. But....

If the title of your Node is the cityname. I would simply make its url path pattern in Pathauto as city/[node:title].

That takes care of the url /city/cityname.

Then you can simply use the Tagging taxonomy installed by default to tag the city with relevant keywords.

Then install the 3rd party contributed module: view_mode_page

It allows you to define alternate pattern(s) to get to a piece of Node content.

Then use its API to create the alternate urls based on the tags.

Something like this example code in a custom module (untested, as I dont have your exact setup):

/**
 * Implementation of hook_view_mode_page_get_patterns() from module
 * view_mode_page.
 *
 * This lets me define additional node urls (per NID) with a custom
 * view mode.
 *
 * Creating a custom view mode, and using Display Suite for example could let
 * you customize these pages so they're slightly more unique in content layout
 * and values.
 */
function MYMODULE_view_mode_page_get_patterns($results, $content_type, $view_mode) {
  $results = array();
  $defaults = array('content_type' => 'CITY_CONTENT_TYPE', 'view_mode' => 'full' /* or a custom view mode */, 'show_title' => 0, 'title' => '');

  // Load the terms for keyword vocabulary by its vocabulary name.
  $keyword_terms = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load('city_keywords')->vid);

  // Loop through the Term objects and build the sub-url using the nodes pathauto alias denoted by %.
  foreach ($keyword_terms as $pos => $Term) {
    $results[$pos] = (Object) array_merge($defaults, array('url_pattern' => '%/'.$Term->name));
  }
  return $results;
}

If every city is to have different keywords, this may not work. Or you may have to load all the city nodes and iterate through them to get the correct paths and attached keyword terms. This is just taking a generic keywords list and building additional urls for each city.


Find permission page (/admin/people/permissions) and You can give Authenticated users  permission to "Edit own Order orders"


hreflang links added to page source without translation

These are added via a hook_page_attachments() implementation in content_translations.module. The code looks like it should not add any hrefs unless an entity translation has been created.

Some tests on my site seem to indicate that this is working correctly.  Do you have another module that is trying to add these and doing it incorrectly?

That said, you should be able to implement a hook_page_attachments() function (in something with a execution weight that runs after the content code).  In this look at the $page['#attached']['html_head_link'] array for the items to remove.


In the view, set the path to company/affiliates and the contextual filter to taxonomy ID (or whatever) and set the default value to type fixed value of Oregon. So company/affiliates goes to the Oregon page but company/affiliates/New-York goes to the New York page and company/affiliates/Massachusetts goes to the Massachusetts page while after all that the plain company/affiliates and company/affiliates/Oregon goes back to the Oregon page.


How can I move the location of the advanced search form?

One option is the Advanced search block module which makes the advanced search form available as a configurable block.

  Provides the advanced search form (normally displayed above search results) as a block. The block includes default values for the advanced search fields making it easy to refine searches.

From a brief glance at this module's code, it looks like it hides the default form and re-creates the advanced search form in a block.


not able to map all my product Attributes in commerce feeds

https://www.drupal.org/node/1031064 Try the dev version.

I had the same problem and after updating to the dev version all the missing fields were back. Seems there was a bug


How do I backup a site when it weights is more than 200MB and host can't do it?

Refer to my answer to "Which tables are safe to clear?", which should help to get the size of your database reduced.

And/or use the Backup and Migrate module, which also support exclusion of selected tables (typically the ones that are safe to clear also). Here is a quote from its project page (bold markup added here):

  Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


How can I delete taxonomy terms for a specific node type?

The field isn't part of the type, but the terms remain assigned to the existing nodes.

That doesn't sound right; to the best of my knowledge removing the field from a content type will (normally) remove all data attached to nodes of that type. They get moved to a field_deleted_* table and then purged on a cron job.

It might indicate there's a problem somewhere in your installation, or it might just be 'one of those things'.

The 3 tables you mentioned are the only places you'll need to delete data from, but you'll also need to flush the caches after the purge (or at least truncate cache_field)


The issue was actually due to I was running php 5.5.*. The following code resolved my issue for any who come across it themselves.

To discover if you too are running over that version type the following:

php -v

Once you've determined your running PHP 5.5.* type the following:

sudo yum install php55-gd

sudo service httpd restart
sudo service mysqld restart

That should resolve your issue.


Ok, you want to expose your taxonomy to your nodes to change the background.

Using the Context Module

  Add a condition Taxonomy and select your term (football) and the
  reaction Theme HTML add the class (football). As far as I got here you
  will need one rule for each term, you can't use a token directly.

Using a custom module

You can do it with a custom module or just throw a preprocess_page it in your theme:

function my_theme_preprocess_page(&$vars, $hook) {
  if (module_exists('taxonomy') && $vars['node']->nid) {
    foreach (taxonomy_node_get_terms($vars['node']) as $term) {
      $vars['node_terms'] .= ' taxonomy-'.strtolower(eregi_replace('[^a-z0-9]', '-', $term->name));
    }
  }
}

Got from: https://www.drupal.org/node/67587

BTW you should really change the path for the nodes! I know it is still in dev but don't forget it!


Drupal module updates failing through administrative interface after update to 7.50

This is most likely a problem with your file permissions. A quick test on simplytest.me showed that module installation is not broken in 7.50.

I would try to check the file_temporary_path variable under:

"Administrator -> Configuration -> Media -> File System"

And see that the web server can write to the configured directory.

If my assumption is correct, then also all other file uploads will fail, so it might be a good idea to test uploading an image to an article, too.


In the template.php of the theme add the following code.

function phptemplate_preprocess_page(&$vars) {
  $title = $vars['title'];
  $site_name = $vars['site_name'];

  $vars['head_title'] = implode(' - ', array($site_name, $title));
}

Verify the $head_title variable is present in page.tpl.php.


I experienced this under Drupal 6.x - it is possibly a similar experience on Drupal 7.x.

The Apache error log (/var/log/httpd/error_log or similar) may show something similar to the following:

... [error] [client ... ] PHP Warning:  Unknown: Input variables exceeded 1000.
    To increase the limit change max_input_vars in php.ini. in Unknown
    on line 0, referer: https://.../admin/user/permissions

To resolve add the following to php.ini

max_input_vars = 2000

Reload Apache per your operating system and increase setting if pain persists.


Why I'm getting MySQL error that server has gone away?

A couple of things to try:

First, it's potentially one of your contrib modules causing the problem, so option 1 would be to use Drush to disable all non core modules:

drush pml --no-core --type=module --status=enabled --pipe | xargs drush -y dis

After running this, there is a good chance that you can access your modules page again and be able to start enabling modules one by one to pinpoint the culprit.

Option 2 would be to check mysql's MAX_ALLOWED_PACKET.  You can check this by running SHOW VARIABLES LIKE 'max_allowed_packet' in your mysql console.  If it is set at 1MB, you can try raising it to 16M by running SET GLOBAL max_allowed_packet=16777216;. Try loading your page again to see if that was the issue.


I believe that is a memory error. If increasing your memory limit doesn't work, you might get relief from lowering the number of nodes to index per cron run on the search settings page.

It could also be caused by running an out-of-date version of PHP.


Is there a function or a way to invoke the comment object?

The page.tpl.php template file is used for any page output from Drupal; it is not said the page is being output for a node. It would be rather better to use node.tpl.php, which is always used for a node, except when a different template is being suggested and that file exists.

The code I am reporting is valid for page.tpl.php, but with few changes it can be used also for node.tpl.php.
I am taking the assumption you are interested in the comments for the node being shown.

if (!empty($node)) {
  $result = db_query('SELECT * FROM {comments} WHERE nid = %d', $node->nid);
  while ($comment_obj = db_fetch_object($result)) {
    // $comment_obj contains the comment object.
    // ...
  }
}

In the case the code is used in node.tpl.php, it is not necessary to verify if $node is not empty, as the template is surely used to visualize a node.
I called the variable $comment_obj because in node.tpl.php there is already a variable named $comment, but that variable doesn't contain any comment object; it contains the comment settings for the node.

As pointed out from Jeremy French, such code should never go inside a template file, which should just contain presentation code (i.e. code that prints out the content of variables). That code could be the body of a function (contained in template.php of a theme) that builds up the output shown from the template file; alternatively, similar code should be used in a preprocess function.

In this case, the code is similar to the following one.

function mymodule_preprocess_node(&$variables) {
  $variables['comment_output'] = '';

  if (!empty($variables[node])) {
    $result = db_query('SELECT * FROM {comments} WHERE nid = %d', $variables[node]->nid);
    while ($comment_obj = db_fetch_object($result)) {
      // $comment_obj contains the comment object.
      // ...
      $variables['comment_output'] .= // ...
    }
  }
}

page.tpl.php should then print the content of $variables['comment_output'].

print $comment_output;

To notice also that Drupal uses comment.tpl.php, to which is passed a comment object. Depending on what you are trying to do, that could be the template file you are really interested in.


field_type with existing data cannot have its keys changed

Try to delete the specified config file:

drush config-delete <name of the config to delete>

and than import the config again:

drush cim


show amount of results for exposed filter

Here is some sample code to do this:

function hook_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'views_exposed_form':

            $allowed_categories = db_query("SELECT 1 as tid, "Term Name (2)" as `name`")->fetchAllKeyed();
            $allowed_categories = array_reverse($allowed_categories, TRUE);
            $allowed_categories['All'] = '- Any -';
            $allowed_categories = array_reverse($allowed_categories, TRUE);

            $form['field_category_tid']['#options'] = $allowed_categories;

            break;
    }
}

Just change the query to return 2 columns - the tid and the name with a count.


How to add a user/login Link to the Maintenance Mode page?

Yes, you should be able to. You can create a maintenance page template similar to any other in Drupal, "maintenance-page.tpl.php". However, to get that to work you probably have to make some changes to your template.php file.

More info can be found here: http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode although I believe that example is from Drupal 6, but the idea should be fairly similar for Drupal 7 as well.


There may be a more elegant way to do this, but I would use the Switchtheme module, which provides a block that allows users to switch themes.

To make this work, you will have to create three separate themes, one for each option.  However, this is not as complicated as it sounds.  Just make the black-on-white and white-on-black themes subthemes of your main theme (the one with default CSS); then all you will have to do is set up the subthemes one time and add the CSS.


Is it possible to setup reports per individual user when using the Commerce Reporting Module?

This question seems fairly similar to the question "https://drupal.stackexchange.com/questions/141473/how-to-only-include-data-in-a-commerce-reporting-report-about-products-created-b" ... Which has a comment that might be the answer to what you're looking for ... Did "I" hereby answer "this" question?

Aso, while waiting for the Commerce Reporting handbook to get some real content (cfr. your valid comment in the other reply), you may want to look at the Visualization documentation, which includes a link to a video about Commerce Reporting (the Visualization module is the charting API used by the Commerce Reporting module).

Be Aware: I'm a co-maintainer of the Visualization module


Use HTML tags inside rows of a table in a render array

Try creating the links using function Drupal::l,

For example,

$url = Url::fromUri('http://example.com/');
$link1 = \Drupal::l(t('Link1'), $url);
$url = Url::fromUri('http://example.com/');
$link2 = \Drupal::l(t('Link2'), $url);
$url = Url::fromUri('http://example.com/');
$link3 = \Drupal::l(t('Link3'), $url);
$rows = [
  array(
    $link1,
    $link2,
    $link3,
  ),
];
$header = [
    'header 1',
    'header 2',
    'header 3',
];
$render['table'] = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

To add other html tags to table , you can use Drupal markup element and renderer service,

$element['#markup'] = 'Example Span Tag';
$span_tag = \Drupal::service('renderer')->render($element);


Entity reference form in views below node

Ok. After suffering on many different options to get this integrated, I eventually decided to use a workaround. I used the standard node comment form and created a view to display teaser nodes. It works. It's not necessarily the right option but it might help someone looking for something similar.

Thanks for your help guys.


How to manage catalog display of images for Commerce 2 product variation

In future anyone need the answer, The image fields's format to be set to 'Image delta'. If image delta value set to 0 then the first image will be displayed and if it is set to 1 then the second image is displayed and so on.

Delta appears for the fields that has multiple values and delta refers to the order by which it appears.


Try hook_views_pre_render hook to alter view result if only you need to display result. You just need to prepare the webservice result as per hook_views_pre_render result data.


Is this block safe from code injection exploit?

Essentially yes.

You're hardcoding the javascript, so there's no vector by which an attacker can inject code from the client side. This will of course change if you're interpolating variables into the JS code that have come from a potentially insecure source (i.e. the user). Those will need to go through filter_xss().

That's a bit over-simplified, there could of course be other vectors outside of this context which would allow an attacker to manipulate the PHP file itself, which could theoretically be invoked from the client. But in-and-of-itself, the method you've chosen is secure against XSS attempts.


It sounds like you could use something like Field Group and use Horizontal Tabs, seems like it would work the way you want.

Under Manage Display of the content type, add a Horizontal Tabs Group.
Then a Horizontal Tab Item for each field or section you want. The label you put in will be what shows up on the tab.
Nest the tabs underneath, and then put the fields you want underneath each tab.

The result will should look something like this. With a bit of CSS, you can make it look different.

Manage Display

Final Result


The link in the question is not working but after searching in google about the link I come across this page

If your looking for something like this then the best way will be to install view module and views Slideshow module

View Slideshow can be used to create a slideshow of any content that can appear in a view. to create a slideshow with thumbnails please check the video


How to hide empty 'Content Zone' div in Omega?

Probably because you have the debug placeholders blocks activated?
There is a checkbox "Enable the debugging (placeholder) blocks" in Appereance > subtheme > settings > debugging tab.

The zones are rendered even if empty.
I suggest you try with this option turned off.


Run Drupal in localhost then migrate to online once it's finalized

Since this is mostly likely a one time move (because the online version with likely be your master now) I wouldn't worry too much about perfecting the process. Just...

Dump the mySQL DB and place within the root.
Zip/Tar the codebase, including the files directory.
Move it to the server (via SCP or FTP), unzip/untar the whole thing.
Import the DB via: mysql -hHOST -uUSER -pPASS DBNAME < db.mysql
Bam!

For continual workflow I usually use:

Backup & Migrate to create database backups.
Git to move the code around (.gitignore your files directory)


How do I display a view pane with all items of a category?

First you will need to have the views page that displays all the Events for the tag you want, then it should be a matter to rewrite the Link field to output as a link that point to that page you had created.

FOR THE PAGE:

Create the page using views that will filter all Events with category Terror
In the URL make it the exact TERM you will have in the list you need, i.e. www.yourwebsite.com/TERROR
Save

FOR THE LIST:

Create the block/page view you need with the list
You need to add the field TERM again (it should appear twice, one above the other, rearrange if not).
In the first TERM FIELD check the box for Exclude from display
On the second one, go to Rewrite Results > Output this field as a link, check that box
In the text field that appears, enter the replacement pattern for the first TERM FIELD, something like [field_term].

That will render your TERM as a link to the TERM page, that will contain all the events for that term.
If not, place a link so I can help you.


View that shows posts specific to the node

You should begin around Views of course. Just make a taxonomy term per project, and use Views to create a page with all nodes of type "update(post)". Then in tpl.php for a texonomy field of "project info post", build a link based on taxonomy term. That's pretty much all.

Entity reference module is worth to look at, too. Using it you could relate all "update" nodes to "project info" node. Similar effect to taxonomy, has it's pros and cons of course. Read about both, and choose your poison - referencing node directly is cleaner way, but taxonomy seems to be supported better, and is in core so less contrib modules for you.

Last but not least - you could simply make the update posts a comments on project info post.


How to filter the values of an array in drupal

This is an old question, but there didn't seem to be a decent answer yet...

There is no out-of-the-box solution but it's easy to write a function that recursively walks the array and applies a filter function to the keys and values.

<?php
function clean_array($array, $filter = 'check_plain') {
  $clean = array();
  foreach ($array as $key => $val) {
    if (is_array($val)) {
      $clean[$filter($key)] = clean_array($val, $filter);
    }
    else {
      $clean[$filter($key)] = $filter($val);
    }
  }
  return $clean;
}
?>

This also gives you the flexibility to use filter_xss or check_markup instead.

Hope that helps.


Prerit,

I think there is indeed one custom port to BS3 and that can be used in Drupal 6. Follow post #3 to get the idea. However, this is a custom theme made by an Drupal developer and its not in the drupal's project yet.
FYI, it does support jQuery version 1.7.2 by un-setting the default jquery 1.2.6 version which intern may break some functionality in your site.
The link to the Github Repo.

Personally I would suggest to use Zen or Omega for a Drupal 6.x site.


Why should the Hacked! module not be used on a production server?

A quote from the developer of the module, in response to exactly the same question:

  The module is aimed at developers wanting to know what other developers got up to, not to detect if someone broke into your webserver and changed some code.

As such it doesn't really belong on a production server; it doesn't appear to be a security risk (although it does download to your local files folder), it's just not what the module was designed for.

There's also another comment on that post that sums it up nicely:

  It's not that it's fragile, unstable or (very) dangerous.
  It's just that "You're doing it wrong" if a production site is where you actively use the features provided by "hacked".


Where does the variable for the left sidebar get set in Drupal 6?

I ended up changing the menu block settings from having the 'fixed parent item' at the top level with 'starting level' set to 2nd to having the 'fixed parent item' at 'new products set' with 'starting level' to 1st. Now they both work fine.


How to use drush locally with Acquia Dev Desktop2 and upgrade core

in Acquia Dev Desktop application,  when your project is selected there is a small
icon on the right-hand side. If you press it will open CMD and the correct path will be autoselected. Drush up will work there.

Good Luck


Reply form not showing for ajax_comment module installed for Open social distribution

Make Sure that connected user has Post comments Permission Or anonymous has it.


Multilingual site page not found error on default language URL path prefix

On admin/config/regional/language/edit/nl Path prefix language code was set to empty. Setting the code to /nl solved the problem.


Upgrading Drupal 7 version from DEV to PROD

Even thought you said that you are not comfortable with Drush. I would strongly suggest for you to used Drush to update your modules and core. Its just easier and faster. If you decide to give  a try you can update modules and core by running.

drush up -y

If you want to update just the core use drush up drupal -y

You can upload a copy of the latest Drupal version on your production website and then replace sites folder with your dev sites folders. And this would take care of Drupal Core updates.


How to filter view based on a parent node

If you are displaying all similar products on another node page - load the master node by adding an entity reference relationship to your view. I don't think you can  compare values of two different nodes in a view. So, Use the view PHP module to write a filter script that can compare both the fields from the nodes.

Check out this 'Question' on using the view PHP module


Can region be defined outside of the theme's .info file?

Drupal 7 has 5 default regions:

regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right
sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
regions[highlighted] = Highlighted
regions[help] = Help

Regions aren't inherited by parent themes: https://drupal.org/node/225125.

If I'm not mistaken you used to be able to define regions in theme_region(), but I believe that's no longer being used.


Which function should I use to update a node through the comment form?

You could implement the same hook hook_comment_create() but just inverse the assignment you do on the comment as in your code, for example:

function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('node_field') && $comment->hasField('comment_field') && !empty($comment->comment_field->value)) {
      $node->node_field->value = $comment->comment_field->value;
    }
  }
}


How to hide core fields in Content types?

There are two ways you can do this.

You can do this with permissions for some items. 'Menu settings' is controlled by 'administer menu' permission.

If some item is being put onto the page which can't be controlled by permissions then you can use a form alter hook to remove them. I tend to set #access to false rather than completely removing the item from the form.

There is a big explanation of examples of how to alter forms here


How to add extra eventlistener to menu object in attached library

Couple of problems. But the main two are:

In Drupal 8, you need to call $.each() on $.once()
In Drupal you don't need to call $.on() on elements. The combination of Drupal.behaviors and $.once() achieves the same goal.

So your code should be something like:

$(".navbar-collapse", context).once('myMainMenu').each(function () {
  // Do stuff here
});


When using Zen and Zen grids, where do I put SASS variables?

In the Zen theme structure there are several main style files: pages.scss, nodes.scss, blocks.scss, forms.scss. Depend on which part of website that you want to make styles. You have to choose the correct files for changing. In order to use the sample code in the Zen Grids . You can go to pages.scss and make changes here . Make sure that your website will generate the same HTML markup structure like the sample by creating new pages.tpl.php.


how to add custom css as default for the whole site

If you want it on every theme, then you'll want it in a module.

Using this method you won't have to put the CSS in with every theme - just add and enable the module.

Just create a module that uses the following code:

function MYMODULE_preprocess_page($vars) {
  $options = array(
    'group' => CSS_THEME,
    'every_page' => TRUE
  );
  drupal_add_css(drupal_get_path('module', 'MYMODULE') . '/MYGLOBALCSS.css', $options);
  $vars['styles'] = drupal_get_css();
}

drupal_add_css()

drupal_get_css()

You'll need to clear your theme registry to have the changes picked up.


How can I set a certain cck value to selected nodes using View Bulk Operation (VBO)?

Create a view, and add Bulk Operation to the field.
In the configuration field: Bulk Operations: Content
  Bulk Operations -> Selected Operations,  you can choose the operations you would like to perform in bulk.
  Once you done, save the view, and go to the view page.

Select the nodes you would like to edit
Choose an operation, click Execute
Select the field you like to edit
You got the rest.


Search has disappeared on Drupal Commerce Kickstart site

The block that you need is actually called 'Exposed form: display_products-page'. Since it isn't immediately obvious what this is for I must have changed the block position to 'none'. Since it doesn't have search in the block name I didn't realize it was connected to search. Simply looking at the blocks on a new Kickstart Commerce install made it obvious what I was needed. Just change the position of the 'Exposed form: display_products-page' block to 'User Bar First'.


I got the answer. Pretty paths module creates the problem for this. I disables the Pretty Path module and flush the cache.

Now Min/Max slider working fine.


I fixed this by going into structure->views->the-specific-view-causing-the-issue(News)->advanced->theme information, and found a more specific name for "Row style output," in this case views-view-fields--news--block.tpl.php.


The error means exactly what it says:

  Request failed: request timed out

The connection between your Drupal server and Solr server timed out.

If the servers are geographically far from one another, you might consider moving them closer together to reduce latency. Your Solr or Drupal server may also need more resources.

Both are things you'll need to incrementally test (preferably in an identical staging environment) until you've worked out where the bottleneck is and how you can overcome it


How to create a shortcut to IMCE File Browser?

Use me aliases module.

It turns:

http://example.com/user/10/imce

to:

http://example.com/user/me/imce


Views Php how to select actual term name not term ID

You can either create a relationship with taxonomy in order for the term name to be available in views as a field, or use taxonomy_term_load().


How to update disabled modules using Drush?

I use:
    drush pm-updatecode --check-disabled
followed by:
    drush @sites updatedb

The --check-disabled option was added 2014-11-04


Create a node on user account creation. Display link to user on first login

Assuming you are using Drupal 7, I'd advice you not to do this.

Drupal users are now entities and field-able.

In Admin > Configuration > People > Manage Fields tab, you can add new fields to the profile. With Profile2 module, you can have even more control over these fields (this will become a new entity type, with option to have separate tab in user edit page, etc).

If you are using Drupal 6, while being prepared to upgrade your site to Drupal 7 or 8 in near future, you can use Content Profile module to do this.

Also, if you need to automate these data/fields with user registration, give a try to Rules module.

Profile2 and Content Profile, as well as core profiles have Views support so you can show these profile fields in user with a 1:1 relationship (if you create a new node without binding it to the user, how do you find the correct node from pool ?).


Does using Views Aggregation break title field as node link?

I can confirm this was fixed in a recent dev release of the Views module.


Maybe too late you can use the Bundle Copy module:

  Bundle copy is a replacement for the Content copy module which lives in the CCK project for Drupal 6.  Has export/import support for: Node types, Taxonomy, User, Field API fields, Field groups

UPDATE 7.x-2.x-dev notes

The following features have been added:

Export/import of Field Collection
Cloning of Content types
Export/Import of Commerce Entity bundles

Drupal 8: Bundle Copy is in Drupal 8 Core CMI.


how to get the submitted value of tableselect

You can exclude unselected options with array_filter, e.g.

$selected = array_filter($form_state['values']['table']);


Database field of timestamp type cannot be added to the database using hook_schema()

I believe you need to explicitly define the default value for those in the schema:

'created_date' => [
  'mysql_type' => 'timestamp',
  'not null' => FALSE,
  'default' => NULL,
],

For maximum portability, you can also define the types for other databases:

'created_date' => [
  'mysql_type' => 'timestamp',
  'pgsql_type' => 'timestamp',
  'sqlite_type' => 'datetime',
  'not null' => FALSE,
  'default' => NULL,
],

Look at \Drupal\KernelTests\Core\Database\SchemaTest for an example.  FWIW, code doesn't use that for timestamp/created/updated.  Those are field types and handled by the Field API.


Drush not working on a docker based enviroment on ubuntu 16.04

When you run docker run ... or docker-compose run, Drush is running in the context of the container, not your host machine. So when it needs stuff like DB credentials, aliases, ssh keys, it looks for them in the container. If Drush cannot find such things in the container, Drupal cannot fully connect to Drupal and you get an error, usually the bootstrapping one.

I have a feeling your code isn't mounted to the Drush container, based on the fact that the alias scanning isn't picking up anything custom, only the usual alias paths. If the code is mounted, then probably the Drush container does not have the DB credentials. Do a drush status to check if everything is fine.


Statistics module doesn't update when getting a node

The query to update the node_counter table may need tuning.

e.g:

if (variable_get('statistics_count_content_views', 0)) {
  // A node has been served, so update the node counters.
  db_merge('node_counter')
    ->key(array('nid' => $nid))
    ->fields(array(
      'daycount' => 1,
      'totalcount' => 1,
      'timestamp' => REQUEST_TIME,
    ))
    ->expression('daycount', 'daycount + 1')
    ->expression('totalcount', 'totalcount + 1')
    ->execute();
}

The other fields, such as 'yearcount' etc.. aren't in the node_counter, at least not by default which may be causing a PDOException there.


How can I limit an entity reference selection to a specific field value on the reference

You can create an Entity Reference display in a view and use that to generate the available options.

In your view of choice, create a new display of type Entity Reference and configure it so that it only shows the content you want.
Navigate back to your field configuration screen (the one in your screenshot) and change Reference Method from "Default" to "Views: Filter by an entity reference view" and choose the display you created in step 1.


Why is it possible to write any string in the hash salt

You can read about it in the default.settings.php file:

  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.

This value is used by Drupal as salt for some cryptographic operations. It should be a random value. It adds more security to those cryptographic operations (as long as the value is not known by an attacker).

As far as I know Drupal uses a auto-generated salt value based on Database credentials when no salt is set, so Drupal should work without a salt value.


set multiple taxonomy values programmatically

You could also implement the "hook_views_pre_view" function in order to alter the contextual filter arguments of your view and display. In order to add multiple taxonomy values for the same argument, you can change the $args[0] element from the $args variable of the hook.
For example: $args[0] = '22+14+64';
Remember to check the "Allow multiple values" option of the contextual filter.

Take into account that altering contextual filter arguments inside the previous hook may produce troubles when using a views exposed form. Specifically, the form "action" attribute may have a wrong URL. If that issue appears, you can solve it by implementing the "hook_form_views_exposed_form_alter" function and changing the $form['#action'] element with the correct URL.


Use Botcha. This will effectively prevent bot submissions. Don't use short term adjustments for Drupal defaults unless you've used your site for long time.


For Drupal 6 -- page-[content_type_name].tpl.php and clear the cache.

For Drupal 7 -- http://www.digett.com/blog/01/11/2012/overriding-page-templates-content-type-drupal-7


Attach a simple custom handler to a Webform

The above code works. My mistake was in the naming of things. Name all files, classes etc. foo and it will attach.


How do I embed a custom node creation form inside a view

As you're using plain php (not really bestpractice) you can code it out yourself there, having a select changing a query-parameter for your view (self made contextual filter ..).
A more sophisticated approach would be hooking your view, hook_views_pre_render:

This hook is called right before the render process. The query has been executed, and the pre_render() phase has already happened for handlers, so all data should be available.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

Or create a custom page-callback (see hook_menu),
where you embed the view and add the form regarding your query param (or uri param).
You can check permissions with user_access.
You won't need to enable php execution with these approaches !


You're missing page callback from your menu item. From the docs:

  "page callback": The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

Since your menu item is the root item (has no parents) that's probably what's causing the access denied.

Just add a page callback to your menu item, implement the function to return a string or render array to display the page, clear Drupal's caches, and it should work.


Organic groups - The OG groups of the logged in user

You should try to use a contextual filter in views and add a Relation to the OG Roles.

Click on the advanced section in your view.
Add the contextual filter "Content: Groups audience (og_group_ref)"
Then select "Provide default value"
Choose "The OG groups of the logged in user" in the dropdown field
Add a relation "OG Roles from membership"
Add a filter "OG Role name" and choose the role you want to have


Cant create View with Many to Many Relationship

It's quite simple:
Create a view which shows content of type Person (or users, if for Person you mean users).

Now let's say that Transaction has an Entity Reference field named field_person and another one named field_company.

In the view's Advanced section click on Add relationship, search for field_student and check "A bridge to the Content entity that is referencing Content via field_person" if Person as a node type or "A bridge to the Content entity that is referencing User via field_person" if Person is a user. In the configuration window that pop ups check "Require this relationship" and save. You have just configured the first join.

Add another relationship. How that you have configured the first one, you can search for field_company and check "A bridge to the Content entity that is referenced via field_company". In the configuration window click on "Require this relationship" and check that the Relationship combobox has the first relationship selected. Now you have configured also the second join.

Finally create a Contextual filter. Search for "Content: Nid" and check it. In the configuration window, the Relationship combobox must have the second relationship selected. Choose what to do "When the filter value is NOT available" (this depends on what you want to do).

Done!

EDIT: I noticed just now that you search Company by name, not by NID. Just change the field in the contextual filter!


According to the documentation, the function hook_apachesolr_index_document_build(), on line 373 of file apachesolr.api.php, is not a reference value, instead directly a variable. So, the code should be:

function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

Also, from the code you use, I suspect the following possibilities:

You are adding the code to the core node module, which is never recommended, as one should never hack core.
If you are adding this code to a custom module, and name that module node (as you mentioned in the comment of the code), that will conflict with the core node module, and might cause conflicts and break down your code.
If you add this code to a custom module (with a different name), then it is a wrong way to implement a hook in custom module. Follow this guide to get started with module development.
Lets say, if you name your module "custom_search", then you should place this code in the file custom_search.module, and implement it in the following way:

function custom_search_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

Note that, I've replace the hook in the function name with the module name "custom_search"


French accented characters not saving to database

Both suggested solutions above are good things to check when trying to solve this problem.

In my particular case, using the fgetcsv command. It silently chokes on files that are not UTF-8 encoded and contains accented characters. To fix this problem I had to implement the file read function as follows:

while (($line = fgets($file_handle)) !== FALSE) {
  // Ensure the line we read is encoded properly
  $value = mb_check_encoding($line, 'UTF-8') ? $line : utf8_encode($line);
  $data = str_getcsv($value);
  // process the data as normal
}

This fixed my issue.


How to suppress "page not found" messages in watchdog

Yes that option is available as described in the linked issue.

Make sure you have the Redirect 404 module enabled, visit /admin/config/search/redirect/settings, and select the Suppress 'page not found' log messages option.

That will stop 404s being logged.


How do I get block relationships for a content type?

Finally, I got this working by creating a simple view "custom block".
Then, I created 3 relations, one for my node content, one for my content tags and last one for block tags

After that, we just need a contextual filter : Content: Has taxonomy term ID' > 'Display all results for the specified field

And that's all.


My final solution was to create a Page Panel with the following path:

shop/%product/!optionalArgs

% indicates a required argument, ! indicates an optional argument

In order to grab all of the "arguments" or URL path after the product (ex: barn), go to Settings » Arguments, select Settings for optionalArgs, and make sure Get all arguments after this one is checked. Click Finish.

In order to use this with a Clean URL, the panel path needs to be some derivative of the Clean URL because panels does not have access to it. For more details, see merlinofchaos's explanation in the following Panels Issue: Panels, Pathauto and Arguments

  Let's say I have a url. It can be any URL, but for this example it's "node/12".

  Let's say I have an alias and it's generated by pathauto, and it's
  something like video/type/12/this-is-the-title-of-the-video and it's
  aliased to "node/12"

  If I visit
  http://example.com/video/type/12/this-is-the-title-of-the-video then
  what Drupal thinks the URL was was, in fact, 'node/12'. Panels never
  has a chance to do anything with video/type/12/foo because that URL
  doesn't really exist.

  The reason, then, that adding some other piece to the URL makes it
  work is that aliases don't accept arguments. They must be exact. So
  the problem, in that case, is the alias itself is actually taking the
  page away from where you want it to go.


Link to create new node with taxonomy term from url already selected?

Yes, you need to download and enable the Prepopulate module.

The syntax you use to prepopulate taxonomy terms with D7 is (AFAIK) not documented anywhere and the syntax it is also radically different from the syntax used in D6 that is demoed in a number of screencasts of the Preopulate module.  In D7 taxonomy terms are fields.  If you read the source code, you'll find that you prepopulate taxonomy terms as would prepopulate other field.

I.e. if your taxonomy term field is field_tags and you want to prepopulate with the term "myterm", you use the following syntax (with clean URLs):
/node/add/article?edit[field_tags][und]=myterm.


It should help to use the raw filter, like @leymannx commented, but then your template is unsafe, because you should never use the raw filter on template variables containing user input.

So escape the node title first, then add the HTML (which you know is safe because it's hardcoded), before passing it through the raw filter:

{{ node.getTitle()|e|replace({'|': '<br />'})|raw }}


Text (plain, long) automatically has line break converted to

Since you are using a custom template, the quicker way is just to use the replace() filter.

{{ content.field_testing|replace({'
': '', '
': ''}) }}

The field formatter used in the case of a plain text field doesn't have settings, so you cannot decide if the formatter should output the
 tags you want to remove. It would probably make sense in few cases, especially if you need to replace those
 with other text, but somebody could argue that if you don't need them, you could just avoid entering new lines in the field.

The alternative would be implementing a different field formatter, but this is not as quicker as using a filter. If you just need this for this exact purpose, it sounds a bit excessive.


do thumbnail image styles lower the page load

Uploaded images are scaled depending on the preset you choose for display. Thus, a typical high resolution image which might have 8 MB is reduced to maybe 150 kB when using a thumbnail preset. This of course lowers the bandwidth, the original image is not loaded.

So, there is no need to create a second image field. If you haven't seen it yet, you might want to take a look at the Colorbox module. It lets you choose to display an image as a thumbnail and only upon clicking on that preview the full image is loaded (or just another size you defined).

Just a note: Colorbox is not the only module that is providing that feature, there are a lot of similar modules, the original was called Lightbox. On drupal.org, there's a page comparing all available lightbox clones.


Combine two content types in one using search api views

You have to:

1) allow multiselect for the field;
2) implements hook_form_views_exposed_form_alter and edit the filter - replace 2 values on new value and in validate function to replace back.

Example for the simple field:

/**
 * implements hook_form_views_exposed_form_alter
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){

        $form['#validate'][] = 'MYMODULE_form_views_exposed_form_validate';

        $form['field_your_field_value']['#multiple'] = false;
        $form['field_your_field_value']['#size'] = 1;
        $options = $form['field_your_field_value']['#options'];
        unset($options[3]);
        unset($options[4]);
        $options['3+4'] = 'name of combine value';
        array_unshift($options, '- ALL -');
        $form['field_your_field_value']['#options'] = $options;
    }
}

/**
 * our validate for  form views-exposed-form-list-your-views
 */
function MYMODULE_form_views_exposed_form_validate($form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){
        if(in_array('3+4', $form_state['input']['field_your_field_value'])){
            form_set_value($form['field_your_field_value'], array(3,4), $form_state);
        }
    }

}


Choose one:

Use the rules module to test whether the user has authenticated and the field value of the current user is empty. Redirect to user/[uid]/edit if this is the case.
Do the same test in a module during your implementation of hook_init(). Call

drupal_goto('user/[uid]/edit')

to redirect to the user edit page.
Do the same test in a module during your implementation of hook_init(). Call

menu_set_active_item('user/[uid]/edit');

to show the user edit page.

Replace [uid] by the user id of the currently logged in user.

In cases 1 and 2, you also have to make sure that you do not redirect from 'user/[uid]/edit' back to 'user/[uid]/edit'. This would create an infinite  loop of redirections, because the POST data gets lost when redirecting.

Documentation:

drupal_goto()
menu_set_active_item()


How to check if user has access to node creation page from passed parameter?

After some more internet research and experimentation on my side, I solved the problem.

The passed argument as "?parent=" was acquired using $_GET['parent'].
I programmatically checked if the user has access to create a child with the provided parent using the hook_FORM_ID_alter().


Custom story-node-form.tpl.php not working

I have solved this by doing <?php print kpr($form); ?> and put all the hidden input fields in the form like token, form_id etc that worked!


The function views_embed_view is meant to be used to embed the view in a page or a block during the processing of a page. After the page processing is done, the results are passed to the theme engine. It is not meant to be used in the theming stage.

What you can do is create a region in your template where you want the view to appear, then create your view as a block and place it in that region on the Blocks admin page, following the insructions here;


Restrict editor user to only edit contents in one specific language

The answered Specified here would help you give-permission-to-translate-a-specific-language
After installing Translation Management Module,

You can create users with their translation capabilities
You can specify that a user can only translate from English to Spanish and another user can translate from English to French while creating the user

Create a new user with user role: Translator (which is created when tmgt module is installed)

Then Choose his/her Translation skills as shown below :


How to prepare renderable array for images that are not stored in public or private filesystem, but are delivered statically with module?

Simply put...you can't, unfortunately (well not without changing some core stuff at least)

From the comments for theme_image_style()

  This function does not work with images outside the files directory nor with remotely hosted images.


Managed file: the file used in the field may not be referenced

The solution is to add a call to file_usage_add after the file is saved. This call adds a reference to the file in the database. The file_managed_file_validate function will spot the reference and won't trigger the error.

file_usage_add($file, 'foo', 'foo', $foo->id);

This isn't documented in the Form API under the managed_file example.

This issue is being discussed on the Drupal documentation issues: link


If you want to display the cart link in template you better do it with l or url function, example:

in page.tpl.php file:

<?php print l(t('Cart', 'cart')) ?>
 // first way

<a href="<?php print url('cart') ?>">Cart
 // the second way


Content Translation module can help us using Translation Interface (example.com/admin/config/regional/translate/translate) in this regard to search the string and then define a translation against appropriate language.

The strings can only be translated if they are not hard coded and used with t() function.

t() always searches for appropriate translation with respect to currently selected language otherwise it returns the original string.


How to get all linked nodes from all terms in a vocabulary

As "all linked nodes from all terms" are in my case the same as "all nodes of a content type", I solved my problem this way:

<?php
function themename_preprocess_node_news_overview(&$vars) {
  $results = db_query("SELECT nid, type FROM {node} WHERE type = 'news_post';");
  $tmp = array();
  foreach ($results as $result) {
    $tmp[] = $result->nid;
  }
  $vars['content'] = node_view_multiple(node_load_multiple($tmp), 'teaser');
}
?>


Dynamically loading terms in a term reference tree from a huge taxonomy so users may select nodes as options

You can try some contrib modules:
Hierarchical Select

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

Simple hierarchical select

  Defines a new form widget for taxonomy fields to select a term by
  "browsing" through the vocabularies hierarchy.

You can use it with High-performance JavaScript callback handler

Also you can try https://www.drupal.org/project/views_jstree


How to upload multiple images to Ubercart product pages via FTP?

The way I did it in similar, but not exact circumstances, was to use Node export module. It has it's import option. On an import, it expects images to be already uploaded, so the steps are:

Create two products with couple of images manually
See where it's images went
Upload the rest of your images in the same place
Export your products to a file format you are comfortable with, like CSV / DSV
Add the rest of your products to that file, using your manually added ones as examples
Import products from file

My nodes weren't Ubercart products, but above procedure should work none the less.

Remember: Files uploaded will not be managed until and unless you import nodes to use them, so it's a good idea to turn off any "garbage cleaning" modules you may have to avoid their deletion.


Getting Parse Error during installation of Drupal 8

Hopefully you're not installing Drupal 8 in the hope of using it as a stable website...it's nowhere near ready yet :)

That said, the reason you're getting the error is because the PHP const keyword has only been available for use in the global scope since PHP 5.3. Drupal 8 uses const in the global scope in a lot of places (correctly, as Drupal 8 will require at least PHP 5.3).

My guess is you have PHP 5.2 or lower installed on your server.

Some helpful links:

const docs
Drupal change record for using const instead of define()
Migrating from PHP 5.2.x to PHP 5.3.x


Add attributes to options elements in a select box

Unfotunately there is no way to do it using Form API. You need to involve some theming. Please check the following answer:

https://stackoverflow.com/a/9264589/2620782


How to create a rule to assign roles to users based on some checkbox items in their profile?

Part 1 - Make it work for a single selection and related role

Create a rule which looks like so:

Rules Event: After saving user profile.
Rules Conditions (both conditions must be satisfied):

entity has field (with the field corresponding to (eg) "Automotive".
data comparison to check if "Automotive is selected/checked".

Rules Action: : Assign role to user (for the role related to "Automotive").

You could create a similar rule for each possible combination of checkboxes and roles to be assigned. Or continue as detailed in Part 2 to further enhance your rule from Part 1 so that you end up with a single rule for all possible combinations.

Part 2 - Make it work for other possible combinations

To also make it work for other possible combinations, and because of the fact that a Rules action cannot contain "conditions", you basically have 2 possible approaches:

Create a similar rule (as in Part 1) for each possible combination.
Use the Conditional Rules module to enhance the Rules Action in the above rule to alter the flow, using either Conditional (if/else) of Switch logic. Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).


Translating fields in node.tpl.php file with drupal 7

OK, I found out myself how to do this:

Translate field labels and values in "Configuration > Regional and language > Translate > Import". You should import the values as 'User Interface', not as 'Fields'. Do not specify a URL, only msgstr and msgid.
Now, you need to add your t() function in node.tpl.php for the translation to be effective, like so:

In the node.tpl.php file, to translate field label write something like this:
$content['field_my_field']['#title'] = t($content['field_my_field']['#title']);
To translate field's value, use: $content['field_my_field']["#items"][0]['value'] = t($content['field_my_field']["#items"][0]['value']);

You can now render your field:

print render($content['field_my_field']);


One field (entity reference - paragraph) with two display modes

An array with 'type' => 'teaser' is specifying a field formatter, but you probably don't have a field formatter with this name.

You need to add the view mode (display mode) as string argument to view():.

$variables['custom_display_mode'] = $variables['node']->get('field_gallery')
  ->view('teaser');

For more info see How to apply a Field Formatter to a node field programmatically?


How to print the URL path of a referenced node using paragraphs?

Use the Twig path() function and build a node route with the target id of the reference field:

paragraph.html.twig

{% if paragraph.field_example.target_id %}
  {{ 'View node page'|t }}
{% endif %}

See https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates


I thing you need to sort the node using the taxonomy fields. Is it so then use the steps:

Add realtionship in views

Then add 'taxonomy terms on node'

Then go to filter then you can find all the terms there


As per the core documentation we should use the watchdog function without the t() because it is translating when reading and outputing the log message.

Watchdog invokes dblog_watchdog() in "modules/dblog/dblog.module" and dblog_watchdog() is not translating anything before writing into the database BUT it is translating when reading and outputing the log message.

Reference:

https://api.drupal.org/api/drupal/modules!dblog!dblog.module/function/dblog_watchdog/7
https://api.drupal.org/api/drupal/modules!dblog!dblog.admin.inc/function/theme_dblog_message/7
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/watchdog/7


How to get entity type from entity_metadata_wrapper

Hmmm, I seem to have found a way (unsure if this is the 'correct' way...)

$entity = entity_metadata_wrapper('node', 1);
$info = $entity->info();  // entity info as an array
$entity_type = $info['type']; // returns 'node' for node entities


Composer doesn't patch core automatically, but the cweagans/composer-patches plugin allows dependencies to patch other dependencies if:

You have enable-patching set to true in the "extra" section of your root composer.json file, or
You have at least one patch defined in your root composer.json file

In your case, it looks like Lightning is pulling in those other core patches.


Date module: detect if an end date was set

I'm going to take a guess and assume you have the end-date defaulting to the start-date in the Date field, field-settings?

That way if they click the checkbox for Show End Date, they have to provide a value for it. otherwise it will be empty; essentially letting you know if the checkbox was checked or not.


Modifying only node forms, not forms appearing in blocks?

Using hook_form_formID_alter()

You could use hook_form_formID_alter() to target this Webform node specifically.

For example:

function hook_form_webform_client_form_429_alter(&$form, &$form_state, $form_id) {
    // Alterations here.
}

webform_client_form_429 in this example is found using the <form id=''> from the node in the block you want to alter.

Using hook_form_alter for all Webforms rendered in a block

If the Webform block was created using webform_block_view() then $form['#node']->webform_block should be TRUE.  Pages on the other hand should be $form['#node']->webform_block == FALSE

Try using dpm() from the Devel project to poke around the $form variable for webform_block specific items.

My assumption would be that you could use:

hook_form_alter(&$form, &$form_state, $form_id) {
   if ($form['#node']->webform_block == FALSE) {
      // Alterations
   }
}


How to show different view templates for different taxonomy terms?

in child tpl of views taxonomy term check the parent of tid. if parent value is 0 then show data like "Brunei (term name & description)"
And if parent not 0 then show like "Package 1"


You could probably do something like this:

Add hidden form element with product SKU
Read the SKU in a JavaScript Drupal.behavior

The key is making the SKU available in the DOM and using Drupal.behaviors to read it, as they run / are reattached after the AJAX form update.

i.e:

/**
 * Implements hook_form_FORM_ID_alter
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){

  // Add a hidden SKU element to the add to cart form
  if (isset($form_state['default_product']->sku)){
    $form['product_sku'] = array(
      '#type' => 'hidden',
      '#value' => $form_state['default_product']->sku,
    );
  }

}

Then in your JS file

(function ($) {

  Drupal.behaviors.pswtb_loader = {
    attach: function (context, settings) {
     if($('input[name=product_sku]').length > 0){
       pswtb.loader.show({
         widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
         sku: "US_" +  $('input[name=product_sku]').val();
       });
     }
    }
  };

})(jQuery);


To remove duplicates in Views, if the views advanced settings "Distinct" don't operate, have a look at Views Distinct module: https://www.drupal.org/project/views_distinct. Really useful project and sounds better than php in views.


If the CDN caches whole pages you can most likely disable boost.
https://drupal.org/project/advagg - Needed for D6 CSS/JS
https://drupal.org/project/imageinfo_cache - Should help with imagecache generation


Without access to your error logs etc. I'm going to assume the problem is that you are not putting quotes around your title string, so it is trying to use the title as a database column and it fails.

It should be like this:

AND node.title  = '" . $value . "')";

That is not a great solution either though because it opens you up to possible SQL injection attacks so instead, use Drupal's built in sanitisation like this:

$query = "SELECT title, type
            FROM {node}
           WHERE type = 'institution'
             AND title = :title";
$result = db_query($query, array(':title' => $value));

When you do it like that Drupal will sanitize the $value and it will also know that it is a string and wrap it in quotes.
For more information see the documentation for Drupal's database API - Static queries.

In the above example I also changed the type "IN" operator to "=" because you only had one value, removed the redundant brackets around the where clause and removed the table alias to make the query as simple as possible.

On the topic of EntityFieldQuery, there are multiple different ways to run a query in Drupal and the best solution depends on the particular use case.
If you want optimal performance and don't need to restrict results based on node access then db_query() is likely the best method.
Without knowing your requirements I couldn't advise on the best approach for your current query.


How to replace spaces with dashes when redirecting users through Rules?

Sometimes the solution to a problem, is to prevent the problem from happening.

So therefor I suggest you just do not allow spaces in your user names. To do so, use the Rules module (which you already have), and implement a rule that looks something like so:

{ "rules_disallow_spaces_in_user_names" : {
    "LABEL" : "Disallow spaces in user names",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_presave" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "account:name" ],
          "match" : "\\b \\b",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "User names are not allowed to contains spaces, please correct",
          "type" : "error"
        }
      }
    ]
  }
}

Some more details about this rule (which you should be able to import in your own site using the Rules UI):

Rules Event: "Before saving a user account".
Rules Condition: use a regex to check of the user name contains a space (adapt the regex if needed).
Rules Action: set an appropriate error message (adapt if needed).

The additional advantage of this approach is also that you don't need the PHP filter for it to work (as suggested in one of the comments).


How to add paragragh information under hovered menu item?

I think you're going to need to do a little (code) preprocessing of the menu in your theme layer.

To achieve this, I would put my description text in the "Description" part of my links (which is actually the title attribute) and then add a theme_menu_link() function to template.php (https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7).

Most people overload this function to add attributes to the menu links (like classes or ID's) but you could also adjust it to pull out the text you have placed in the title attribute, then mark it up however you want (span, div, etc..) and then return it in the Menu Link Title.

I see that you have also tagged your question with Superfish so you may need to review the theme superfish function as well (http://api.drupalhelp.net/api/superfish/superfish.module/function/theme_superfish/7).


Is it possible to unset private_tempstore values?

delete() is the method to delete a value in the store.
$session = \Drupal::service('user.private_tempstore')->get('achva_sso');
$session->delete('name');

'name' is the value passed as first argument in any call to set().
You don't use PrivateTempStore::delete() since it's not a static method and it would throw errors or warnings, if called as static method.
As side note, user.private_tempstore is a deprecated service. Instead, the tempstore.private service should be used. (See User module's user.private_tempstore and user.shared_tempstore services moved to core for more details.) In the latest Drupal 8.5.x version, the service is marked as deprecated directly in the user.services.yml file.
class: Drupal\user\PrivateTempStoreFactory
arguments:
  - '@keyvalue.expirable'
  - '@lock'
  - '@current_user'
  - '@request_stack'
  - '%tempstore.expire%'
deprecated: 'The "%service_id%" service is deprecated. You should use the ''tempstore.private'' service instead. See https://www.drupal.org/node/2935639.'
tags:
  - { name: backend_overridable }

It should also be better to use dependency injection: A class extending BlockBase, or ControllerBase, can implement the create() method to load new dependencies.


If you prepare a render element of the view

$variables['view_block_1'] = [
  '#type' => 'view',
  '#name' => $name,
  '#display_id' => $display_id,
  '#arguments' => $args,
];

you can then render this view in twig:

{{ view_block_1 }}


"Call to undefined function fivestar_widget_form()" error

There's no function called fivestar_widget_form() in the Drupal 7 version of Fivestar (I've just grepped the module folder).

It's likely that function is a CCK hook remnant, CCK having been incorporated into the core Field module in Drupal 7, and all of it's functions renamed.

As far as I know there's no easy way in Drupal 7 to use a field widget form as a stand-alone form so you might have to look for another way around this problem.


Does the Search API module integrate with the standard search?

Search API and core search do not integrate. Just use Search API and scrap core search (Core Search does not work on Profiles as entities See http://drupal.org/node/1369544). The Search API can search on an entity known to Drupal. Profile2 creates profiles as entities. Therefore Search API can search Profiles. When adding a new index to Search API, just choose "Profile" or "Profile Types" under "Item Type".


Filter the list of entities referenced by "Entity reference revisions" field

I'd recommend doing this by creating a new Field Formatter by extending the default EntityReferenceRevisionsEntityFormatter (or extending whichever formatter you're using to display the paragraphs). If you're not sure how to create a field formatter, review the Create a custom field formatter documentation on d.o.
Specifically, you'll need to override the getEntitiesToView() method, something like this:
protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
  $entities = parent::getEntitiesToView($items, $langcode);
  $allowed_entities = [];

  foreach($entities as $entity) {
    // Check if your show/hide checkbox is checked.
    // Note: I can't remember if this check is sufficient by itself.
    if (!$entity->my_show_hide_field->isEmpty()) {
      $allowed_entities[] = $entity;
    }
  }

  return $allowed_entities;
}

Lastly, you'll need to configure your entity reference revisions field to use this new formatter.


I want to make a news slideshow of nodes

This module is a Views jQFX addon that integrates the Nivo Slider plugin with views.
The Views jQFX module is a dependency.@Anoop Joseph -- Go through modules README.txt, it explains step by step configuration


How to download directly to ~/.drush folder?

There are three requirements:

Your project must have a .info file
Your project must have a project.drush.inc file
Your project must not have a project.module file or any sort of .profile file

If all three of these are true, then Drush will store the project in ~/.drush. If there is a module file or a .profile, then Drush will treat the project like a module or installation profile (usually storing it in sites/all/modules).

Your project was missing a .info file, but unfortunately, the existence of the profile file caused Drush to decide that your project was an installation profile, and Drush thinks that those do not belong in ~/.drush.

The user will have to specify --destination=$HOME/.drush, or move your project to the correct folder manually.


Simpletest fails with "invalid database prefix" - no other information given

For functional (browser) tests you need to provide some environment variables, in this case the SIMPLETEST_DB environment variable.

It can either be supplied in the phpunit.xml.dist file, or in phpunit command, or actually added to the environment before executing the phpunit command.

The format of the variable is seen in the phpunit.xml.dist file provided by Drupal core.

<!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
<env name="SIMPLETEST_DB" value=""/>

From the error it seems that the provided SIMPLETEST_DB is not valid.

Note: the author mentioned that he was using the Admin UI and this answer does not address this problem.


You should be fine.  You will probably need to change the

$base_url = 'http://my-path/subdir';

in your settings.php so that drupal is aware of it.  Also in your .htaccess you will see

RewriteBase /drupal

that is commented out.  Uncomment this and add your path


Download this:

https://dev.acquia.com/downloads

Then install it in one click.

After your site is installed, click on the left on +more.

Once you click on that, console pop ups and Drush is installed and working, turn key


Try $variables[] in your preprocess function!

 function template_preprocess_foo(&$variables) {
  $variables['foo_list'] = array(
    'list item 1',
    'list item 2',
    'list item 3',
  );
}


Get the body of content referenced in an Entity Reference field in node

Found it:

Content Type > Manage Display

Change Format to "Rendered Entity"


Faceted search using fields from a related node, is it possible?

At the bottom of the fields page you can see additional fields. This allows you to join nodes via relationships.

Search API > Default index > Fields > [Scroll to bottom} > Add related fields

Select your field that is an entity reference.
You'll have access to the fields of the reference too.
Then select the fields on the referenced node that you need and save.
And return to facets.

http://example.com/admin/config/search/search_api/index/default_node_index/fields#edit-additional


Cannot assign calculated value to user field in Rules

I could not figure out why the result variable was not available; my solution was to change the order of the actions to:

After the user clicks save button, rule intercepts:

get the value of author's "days left" field and multiply with 86400 (convert days to seconds)
get the duration of content and subtract it from the previous value
divide the result by 86400 (convert it back to days from seconds)
convert the result to integer
subtract one from this result (this turned out to be necessary, perhaps because of the rounding off during the type conversion)
assign the result to content author's "days left" field.

I do not like having to make two type conversions but this is a working solution.


Drupal 7 update field programatically and generate field names

Your problem is that below code does not work as you probably expect.

$node->$fieldname['und'][0]['value'] = $row->$fieldname;

You expect this to work like this:

$fieldname = 'name';
$node->name['und'][0]['value'] = $row->name;

but PHP will probably do something like this:

$fieldname = 'name';
$fieldname['und'][0]['value'] = $row->name;
$node->$row->name;

Instead, try to wrap your variable name in curly brackets to have it replaced first:

$node->{$fieldname}['und'][0]['value'] = $row->$fieldname;


Feeds import from RSS changing dates to current timestamp

Turns out it wasn't Feeds itself but rather the old site's RSS being invalid.
If the simplePie parser used by Feeds can't find a properly formatted <pubDate> value it defaults to a current timestamp.


Setting the mime-type for files stored in the private directory

Editing includes/files.mimetypes.inc is a core hack, which you should strive to avoid.

Instead, use hook_file_mimetype_mapping_alter():

function mymodule_file_mimetype_mapping_alter(&$mapping) {
  // Add new MIME type 'video/webm'.
  $mapping['mimetypes']['webm'] = 'video/webm';
  // Add new extension '.webm' and map it to the 'video/webm' MIME type.
  $mapping['extensions']['webm'] = 'webm';
}


Ask visitor if he want to view page on his language

Just some ideas: I remember a WordPress multilanguage plugin setting that I had the option

  Detect the language of the browser and redirect accordingly.

That must work similar for Drupal. So, I'ld guess you would try that browser language approach. D6 even had an own function for this language_from_browser. I bet there must be something in D7 for that as well.

Once you have the language you might conditionally display the modal window from that. Inside the modal then there'ld be a little form, maybe just two submit buttons "Yes language", "No language", something like that.

Inside your form submit function you may find a way to trigger the redirect to the chosen language. Finally you might want to save the user's answer in a $_SESSION variable and bind that as a condition for the modal display also.

Put all of that in a little custom module and let us know how you've done!


How to customize permissions for a custom module

Add the Field Permissions module, this gives you control over every field in the content type. You edit the permissions on a field by field basis in the content type editing area. This gives you control over editing, and viewing the field.

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


How can I use Metatag Module to set specific tags on specific nodes?

In Drupal 7

When you configure Metatag, you can click on + Add default meta tags and this will allow you to set them up by Content Type.

If you need to alter only specific nodes, edit your node and scroll down to the end and select the Meta tags Tab


Using the Feed Import module, I can not map for “address field”

You may need to set your country.  I've seen feeds import the data into the tables, but nothing displays because there is no country set.


Im not finding a module for that but what I would do is use jQuery to convert all links tags and their content in the "Content area" to [Please login to view this link] this is only loaded if the user is anonymous.

The function .replaceWith() http://api.jquery.com/replaceWith/ can be used


How to display a twig template via a controller's render array

The problem turns out to be a missing ' mark in the twig file itself.

It turns out that the twig was rendering, but since I had

and not

the browser refused to show the badly written HTML.

So this was user error, but a hard user error to debug.  I saw what was going on by looking at the source for the page, which made it obvious.

Hopefully this will save folks some trouble.  But in any event: the technique I use here is valid, and works if you don't do stupid things in your twig :-)


You want to look into Internationalization Views, which allows you to translate labels and such in a view.


You can add a regular select box style date field with the form api like this:

$form['date1'] = array(
  '#type' => 'date',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
);

Drupal core doesn't have a date popup FAPI element, but you can add jQuery UI datepicker to a regular text field as well

$form['date1'] = array(
  '#type' => 'textfield',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
  '#prefix' => '
',
  '#suffix' => '
'
);

// Attach JS datepicker library and init js for textfield
$form['#attached']['library'][] = array('system', 'ui.datepicker');
$form['#attached']['js'] = array(
  drupal_get_path('theme', 'my_theme') . '/js/datepicker-init.js',
);

Then in your theme /js/datepicker-init.js

(function ($) {
  // Add calendar popup to date textfield
  Drupal.behaviors.setDatePicker = {
    attach: function(context, settings) {
      var options = {
        'dateFormat':'yy-mm-dd',
        'changeYear':true,
        'changeMonth':true
       };
      $(".datepicker-wrapper input").once('datepicker').datepicker(options);
    }
  };

})(jQuery);

The result is something like this:


Is there any way to number Paragraphs rendered so as to have a numbered list rendered?

I’d take a look at overriding the paragraph template file in your theme and doing the work there. Paragraph’s uses the following template names:

paragraphs-item--[VIEW-MODE].tpl.php
paragraphs-item--[BUNDLE-NAME].tpl.php
paragraphs-item--[BUNDLE-NAME]--[VIEW-MODE].tpl.php

The source code of the paragraphs-items.tpl.php is as follows:

<?php

/**
 * @file
 * Default theme implementation for a single paragraph item.
 *
 * Available variables:
 * - $content: An array of content items. Use render($content) to print them
 *   all, or print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity
 *   - entity-paragraphs-item
 *   - paragraphs-item-{bundle}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened   into
 *   a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php print render($content); ?>

You could use a preprocess hook to set an $attribute or other variable that would provide the Step identifier for the paragraph being rendered, although, I’d be suprised if you couldn’t figure that logic out at this level with data available on either $content or $attributes.


Views view unformatted and outputting taxonomy custom field

Finally got it to work!  Here is how you do it.  Assuming your field is called field_category.  My template is called views-view-unformatted--my_view_id_name.html.twig.

{% set my_category_id = row.content['#row']._entity.field_category.0.target_id %}

It does seem pretty silly to me that it has to be that long.  It would be very cool if it was something more like this and that all values associated to a post (since that is what is being output) are available and exposed to the view.

row.content.field_category.id

And if all taxonomies that are added would follow the same path.  Seems unneccesary to have it in #row, then in _entity, then needing to add a 0 and use some oddly named thing called target_id.

I'm new to Drupal coming from Wordpress.  There are nice clean functions in wordpress for getting taxonomy ID and names.  Not too many hoops you need to jump through.


Omega theme responsive grid two break point

Omega 3 uses the 960 grid, but you can alter it adding a custom 960.

Go to http://grids.herokuapp.com/ and design your grid and override the default one (on a sub-theme).

But I strongly recommend going with Omega 4. Is far more powerful and it is designed to give you the freedom to use any grid or presentation framework you like! If you don't like sass (bad for you) you can just alter the css directly.

Edit: As @Clive mention it, the Omega 5 alpha is out there! It's fantastic and follows all the html/css best practices + complies with D8 standard. Go test it, it's almost stable and your themes will be ready for D8.

Disclaimer: It has been ages since I use the Omega 3.


@see Issue #3076750: Add Webform Options Limit


Feeds: use custom field as unique field for mapping

This tutorial works for me:

How to configure unique fields in Drupal feeds importer ?

See also the official documentation, which states that you can either use the Field Validation module, or write a custom solution implementing hook_feeds_processor_targets_alter().


How do I show the image in a node enlarged?

This can be accomplished using Image Resize Filter

Here is a nice tutorial by Lullabot: Effortless Inline Thumbnails: Image Resize Filter


Building custom entities, but using existing modules?

Especially in Drupal core, Nodes are still something like a Super-Entity with a number of features only supported by them, like revisions and the whole node_access thing. The entity.module tries to implement these features generically for all entities, I'm not sure if everything is covered yet.

Many modules only support nodes both due to these missing features (You can't configure ACL's or workflows if there is no way to limit access in the API, diffing is pointless without revisions) and historical reasons (all of your listed modules are ports initially Drupal 6 versions or even older and have been ported to Drupal 7). The whole concept of entities represents a major shift in Drupal and not all modules have made that step (yet).

I guess that's one of the reasons why e.g. Commerce uses Nodes as the default way to display products.

Work is ongoing in Drupal 8 to unify these features and provide them for all kinds of entities.

This is not really an answer to your question, more an explanation of the status quo. As Alex already mentioned, many of those modules are working on supporting entities or an entity-aware successor is being worked on, like http://drupal.org/project/state_machine.


How do I debug my Feeds import not importing a field

As a first step, you could check whether the field has been parsed properly:

In sites/all/modules/feeds/plugins/FeedsProcessor.inc:

Add debug($item) after line 180:

  public function process(FeedsSource $source, FeedsParserResult $parser_result) {
    $state = $source->state(FEEDS_PROCESS);

    while ($item = $parser_result->shiftItem()) {
       debug($item); // debug entry

      // Check if this item already exists.
      $entity_id = $this->existingEntityId($source, $parser_result);
     ...

debug() is a core function that lets you print out debugging information:

https://api.drupal.org/api/drupal/includes!common.inc/function/debug/7 and/or

http://blog.boombatower.com/drupal-7-debug-and-simpletest-verbose?utm_source=buffer&utm_campaign=Buffer&utm_content=buffer5ee6f&utm_medium=twitter

The result will be processed using drupal_set_message(), and will appear in http://example.com/admin/reports/dblog (probably, depending on your configuration).

You'll get one notice for each imported line, like:

User notice:

array (
  'title' => 'This is a test title',
  'body' => 'And a test body',
  'tax' => 'And a taxonomy term',
  '' => '',
)

Alternative: download (from http://drupal.org/project/devel, or drush dl devel) and enable the Development module (Devel in admin/modules), or drush en devel and use drupal_debug() or another tool from the devel module.


How to add image field to paragraph programmatically?

You can treat the field like a PHP array to add (and not replace) an image:

use Drupal\paragraphs\Entity\Paragraph;

  $paragraph = Paragraph::load($paragraph_id);
  $paragraph->field_image[] = [
    'target_id' => $fid,
    'alt' => $alt,
    'title' => $title,
  ];
  $paragraph->save();


How to store a list of bundles in a select field (programmatically)?

I've found that there is an "allowed values function" setting for list fields. Perfect! :)

http://www.phase2technology.com/blog/setting-the-allowed-values-function-property-on-text-fields/


How to theme a radio button field on node edit form?

I think what you need to do is just altering the form array. You can accomplish this in your own hook_form_alter implementation.

For example:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'YOUR_CONTENT_TYPE_node_form') {
        $form['YOUR_ELEMENT_NAME']['#attributes']['class'][] = 'your-custom-class';
    }
}


I am guessing that you need to set your heritage_ui/heritage_ui_library library to have a dependency on core/drupalSettings.

Note that looking at your code, you should also add a dependency upon core/jquery.once, and spend a bit of time learning how to use $.once(). This is because Drupal.behaviors is called often, so your code will be run multiple times unnecessarily (and potentially with problems). You can read more here: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How can I filter content with a date that is somewhere this week by using Views?

You simply add the filter criteria to view.

operator type: is greater than
value type: -7 days


How do I retrieve the field data  associated with an entity, using EntityFieldQuery?

When EntityFieldQuery::count() is not invoked, what returned from EntityFieldQuery::execute() is an array having the following structure:

[entity type] => array([entities])

[entity] => array([relevant ID] => [entity object])

The relevant ID is normally the entity ID, as in the query you reported. See entity_create_stub_entity(), and entity_get_info() to understand what information the entity object contains.

To get all the fields associated with the entity you are querying, you just need to execute the following code.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'audio')
  ->propertyCondition('status', 1);
$result = $query->execute();

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']);
}


field_attach_form not working as expected

Turns out that the bundle name must be same as entity type.

<?php
...
        'bundles' => array(
            'fy_teacher' => array(
                'label' => t('teacher'),
                'admin' => array(
                    'path' => 'admin/structure/teachers',
                    'access arguments' => array('administer teachers')
                ),
            )
        )
...
?>

For anyone who has this issue,

In your hook_entity_info, under entity keys, simply add the bundle property.
to get the above example to work, simply change the entity keys array to :

<?php
'entity keys' => array(
            'label' => 'name',
            'id' => 'tid',
            'bundle' => 'property_name' //The name of the property that contains the bundle name for the entity.
        ),
?>

for hook entity info reference, see https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_entity_info/7


What's the difference between landing pages and panel pages?

I do not see much difference between both, in fact landing page itself a panel page.The only difference I can say is there might be predefined pages like user profile, node template that we can override using panels and thus making them a panel page while landing page is pretty much same as a node with a url to navigate and contents with various ways might be static text, embedded blocks and much more.

Panels should be never be considered as a tool to build static pages as they are resource intensive,instead use nodes for that purpose.There are many reasons why node is preferred instead of panels like node being entity has attached attributes like author, created time, revisions, also there is long list of node api which allows you to hook into node edit/insert/view processes.


How to display data without html on ajax call?

I have done this in a custom controller before. You don't want to return a render array, because Drupal will take the default action.

Instead, you want to render it to HTML (string) and return that back. Something like this:

$rendered = $this->renderer->renderRoot($build_array);
$response = new Response();
$response->setContent($rendered);
return $response;

As far as the Javascript, here is a generic example using fetch (in a twig file):

You also likely don't want to cache the render array either. You can also greatly simplify the API fetch code by using Guzzle (Client) instead of curl.


How to get Views caching working with contextual filters?

This is a Views bug actually and it is not solved yet, but you can work around it by using this patch if you are using contextual filter Taxonomy with depth as I guess, and if it didn't work you can turn off the "Field Language" for the view if you have neutral language content, but this patch is not complete as there is some issues not solve, you can see the full discussion of this issue here issue here