Unable to set date field programmatically

It is a format issue that you are choosing to save.

    $newNode->field_datum['und'][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
//Here in place $node->language pass 'und' and then try.
//Just save a node directly from backend, let say it is saved with node id 10.

$nid = 10;
echo "<pre>";
print_r(node_load($nid)) ;
echo "</pre>";

Now check which format it is using to save. Pass same format once statically and then make it dynamic. Hopefully it will resolve your issue.


Cart page content in simple block in ubercart 3

There is a module Ubercart pictured cart block which will display the content of the cart page into a block. It will provide all functionality which are cart page. You can set the block in a region from block administration page in admin.


I found a solution for this I have two exposed filters for my begin_date (begin_filter_1 and begin_filter_2) and two exposed filters for my end_date (end_filter_1 and end_filter_2).

When the begin_filter_1 is entered, this input will be copied to end_filter_2.
When the end_filter_1 is entered, this input will be copied to begin_filter_2.

No the filter looks like this

Published Yes

AND

Category - Exposed (Taxonomy Term) = Design
Begin Filter 1 - Exposed >= Begin_Date
End Filter 1 - Exposed <= End_Date

AND

Has Taxonomy Term - Exposed = Design
Begin Filter 2 - Exposed(but hidden via css) <= Begin_Date
End Filter 2 - Exposed(but hidden via css) >= End_Date

As you can see in the second Group I use a different filter to filter on the category. This is because of a bug in Drupal Core:
Complex Filter Criteria no Results


How to use multiple values for an exposed filter via url

If using ?author_nid[]=38&author_nid[]=32 as suggested by milkovsky doesn't work you may need to look at using contextual filters. Or, as I think might be your only option, use hook_views_query_alter where you can build your own views query WHERE clause based on $_GET parameters.


Available options to implement a knowledge base or FAQ repository?

Ticketing system

Implement a ticketing system, using the Support module. Popular/great module, to the extend that you can live/agree with the design / assumptions / etc of this module. Definitely worth considering to "get started". Here is a list of features (from its project page):

  Ticketing activity is illustrated with colorful charts (depends on the Chart API module).
  Tickets can be assigned to users (and users can view all tickets assigned to them).
  Tickets support states (new, active, pending, closed, etc) and priorities (low, normal, high, critical, etc).
  Configurable email notifications for new and updated tickets.
  Email integration allows tickets to be created and updated via email, with support for attachments. New users can be automatically created. Ticket properties can be updated via email (using included support_mailcmd module).
  Highly configurable client and user ticket overviews, highlighting tickets that haven't been updated for a long time.
  Fully integrated with Drupal's search functionality, users can only search for tickets they have access to.
  Supports an unlimited number of clients, each with their own configuration and access permissions.
  Tickets are nodes, ticket updates are comments.

Wiki system

Implement a wiki system, using modules such as these ones (excerpts are from their project pages):

Wikitools:

  ... provides some settings to get a more wiki-like behavior. It aims to be lightweight; all features are optional, and it provides no database tables of its own.

  Some of the features of this module are:

  Node Creation: Let users create new nodes when they type in a node name which does not exist.
  Node Search: Let users search for nodes when they type in a node name which does not exist.
  Automatic Redirect: If a title of a moved page is entered, redirect automatically.
  Unique Titles: Enforce that titles are unique over all wiki node types.
  Move Protection: Disallow change of node titles for users without administer nodes permission.
  Underscore as Space: Treat underscores as spaces when doing a node-lookup by title.
  Dash as Space: Treat dashes as spaces when doing a node-lookup by title.
  Custom wiki 404 pages: pick and choose from links to create, links to search, and an inline node add form.

  The module can be used in conjunction with the flexifilter module (of course), the freelinking module by hijacking freelinking links, or together with the pearwiki filter module for various wiki formats.

Freelinking:

  ... implements a filter framework for easier creation of HTML links to other pages on the site or to external sites.

  The framework uses a wiki style format such as [[indicator:target]] as markup to identify links.

The video about Setting Up a Wiki in Drupal 7 contains an interesting introduction to the modules mentioned above (and some other modules you might also want to consider for this purpose).

There is also the Wiki installation profile (either just use that profile, are review it to get inspiration about possibilities). Excerpt from its project page:

  ... will set up Drupal with the following settings:

  Moderator role which can revert / delete pages.
  Revisions for pages.
  Freelinking - easier creation of HTML links to new or existing pages.
  Edit a section of a page (based on header).
  Mediawiki input format.
  Categorization via free tagging vocabulary.
  Views: All pages / All categories / All Images.
  Recent changes.

Questions & Answer site

Implement a questions & answers site (similar to "Drupal Answers" here ...), using the Answers module (Disclosure: I'm a co-maintainer of it), for which a Demo site is available.

To experience it yourself, here are the steps to try it out:

Head over to this sandbox site.
Just accept the defaults to create a sandbox demo site (hit the create sandbox button, and wait for the process to complete).
Login to the site (using the suggested defaults).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Note: you may also want to enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x). After you do, return to the question you created before, and see how the look-and-feel of both the question and related answer(s) below it changed ... Here is a sample screenprint of it:

Groups of users

If your target audience consists of multiple groups of users, then you might want to use the Organic Groups module also.

A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.

As an alternative you may want to consider the Group module, which only exists as of D7, but already has a pretty stable D8 version also.

Roll your own cookies

After you become more familiar/experienced with Drupal, you could just build your own custom solution. With only site building techniques (using contributed modules), you could probably get pretty far. E.g. using modules such as the Frequently Asked Questions module.

However, I you want more flexibility and (way) more facilities that can be perfectly tuned to your specific needs, then you should consider using modules such as:

Views (Video tutorials: Learn Views).
Rules (Video tutorials: Learn Rules).
Flag (Video tutorials: Learn Flag).
Message (More docu in its Community Documentation).


Can Drupal site logout user when he change IP Address?

I'm not aware of any contrib module providing all these features out-of-the-box.

If you are on Drupal 7, you might want to give the IP Address Manager module a try, which provides user-based IP address logging and can be extended programmatically with your own module.

For Drupal 8 you may have to create it from the scratch. Which shouldn't be too hard, if you have appropriate knowledge of Drupal 8 programming.

Btw., I also strongly suggest adding another feature to your requirements: Save the previous IP into the active session (cookie) and check, whether the user just switched the IP during the session (e.g. by means of VPNs), but is still using the same device/browser. - I always find it quite annoying and a bad user experience getting captchas/password dialogs when trying to access sites securely with switching IP addresses. (Which I need to when working from within China. ;)


Drupal7 Get results from a form in a table

The return value from a form submit function isn't used. What you need to to is rebuild the form, and alter the original form function to display the table if it's available. For example:

function find_tryk_filter_test_form_page($form, &$form_state) {
  if (isset($form_state['render_table'])) {
    $form['table'] = array('#markup' => find_tryk_filter_test_page());
  }

  $form['submit'] = array(
   '#type' => 'submit',
    '#value' => t('Find trykluft element'),
    '#ajax' => array(
        'callback' => 'find_tryk_filter_test_ajax_result_callback',
        'wrapper' => 'result-wrapper',
        'method' => 'click'
    )
  );

  return $form;
}

function find_tryk_filter_test_page_submit($form, &$form_state) {
   $form_state['render_table'] = TRUE;
   $form_state['rebuild'] = TRUE;
}

Or you might redirect to a page that has your table on it, if that makes sense:

function find_tryk_filter_test_page_submit($form, &$form_state) {
   $form_state['redirect'] = 'foo/bar/path';
}


Replace a specific integer value with a string?

This seems like the simplest method:

print $content['field_price'][LANGUAGE_NONE][0]['value'] == 0 ? 'Price on demand' : render($content['field_price']);


Load and render all pages from main menu

you cannot render menu entries, but render arrays. you need to get the node from the menu item's path (see here) and then you can use node_view to get its render array.

a way better solution would be to make a views page, with a menu_node relationship.


You might take a look at the module, Protected Pages.  https://www.drupal.org/project/protected_pagesIt seems your tab would direct users to a particular page with sensitive or unique information pertaining to only those users.  In that case a simple module protecting those pages might do the trick.


How can I get documentation on a variable listed in the Features UI provided by Strongarm?

Unfortunately, this is a shortcoming of the Variables system in Drupal: there is no centralized place documenting what they do. This is one reason why it is recommended that modules implementing their own advanced configuration (more than a few key-value pairs) do so using their own tables in hook_schema(), where everything can be documented. That having been said, you can grep around for where they're set/read from your Drupal root:

grep -rn 'variable_[gs]et(' . | grep 'foo_variable'

By checking the documentation for the functions in which they're set, you can typically glean their purpose.


Custom content type displayed without theme

I gave up in the end, deleted the content type, recreated it, and it worked. So something must've gone wrong when I first created it, but I never saw an error indication.


Link one title to a different page other than its content of a view page

I could achieve this by using jquery. I attached a jquery in global library (To add jquery and css to drupal 8 refer this page)

I needed a url redirection while clicking on the link /node/7 from the views field to /another-page. The jquery for which is as follows

$('.view-class a[href$="node/7"]').attr('href', '/another-page');

This selects the anchor tag with the 'view-class' and href attribute value ends with 'node/7' and redirects to '/another-page'


Biblio module: importing ris files, titles not importing even though mapped correctly

after finding this comment, I changed two lines in biblio_ris.module:

339 from

$node->biblio_pages .= ($tag == "SP") ? $data : " - " . $data;

to

$node->biblio_pages = ($tag == "SP") ? $data : " - " . $data;

and 357, from:

$node->$field .= $data;

to

$node->$field = $data;

It works.


User activity not showing in the personal log but is in the public log using Heartbeat module

Finally sussed it. I needed to go into the Triggered Rules page and change the "do" behaviour for the "Heartbeat: When a user adds a comment" rule.

Setting "User Id" to "[comment_author:uid]" links the activity log to the author, and "Node context Id" to "[node:nid]" links to the node being commented on. After changing these the activity showed up in both personal and public Heartbeat activity streams.

Hope this helps somebody else who may be struggling with this.


We had a similar setup. But the only difference is we create a new tag for every update in the theme repository. So we just reference the new tag in  website composer.I would suggest you to try that instead of referencing branch so you get updated code on every compiser update.
If you are not interested in doing in that manner I would suggest you to clear composer cache and execute composer update you will probably get the updated code.


How to programmatically clear library info definition?

Okay, searching thru core services found this. We can clear all the library definitions like this.
\Drupal::service('library.discovery')->clearCachedDefinitions();

See Drupal Reference of this method: Reference
Calling this function Clears static and persistent library definition caches.


Home page only page accessible, no login with clean urls

If the Acquia Dev Desktop configured Apache correctly, then you're most likely missing your .htaccess file in the root of your Drupal install.

I know sometimes on Windows machines .htaccess is hidden within FTP clients, and you need to change a setting so that  you can see the file in directory listings.

The content of your .htaccess file you posted is from the Drupal files directory, which is usually located within /sites/default/files

Double check that you .htaccess exists in the route, and that it has the correct contents. I'd recommend grabbing an original copy from Drupal core.


Search with Views not Saving Selected Filters when user tries to go BACK

Ok, I solved my own question. To get Views search results to 'stick' you just have to select an option for each filter you want to save and the role that this works for.

In Views > Filters > check the box next to 'remember the last selection' and select which roles this applies to.

Easy. Now when a user clicks the 'back' button I've added to the tpl file it takes them back to their selections.


How to make an entity reference field required using states

There isn't a specific form element with the moderation state, since they are added as action submit buttons, but you could add one like this:

  if (!empty($form['moderation_state']['widget'])) {
    $form['moderation_state_hidden'] = [
      '#type' => 'hidden',
      '#title' => 'moderation_state_hidden',
      '#value' => $form['moderation']['widget'][0]['#default_value'],
    ];
  }

Then you could refer to it in your states array like this:

$form['schedule_publish_date'] ['#states'] =  array(
 'required' => array(
  ':input[name="moderation_state_hidden"]' => array('value' =>"published"),
 ),
);

But using states doesn't really make sense because you can't change the moderation status of a hidden field or a non-ajax submit button.

So in that case, you could just update the form element to be required

  if (!empty($form['moderation_state']['widget']) && $form['moderation_state']['widget'][0]['#default_value'] == 'published') {
    $form['schedule_publish_date']['widget'][0]['target_id']['#required'] = TRUE;
  }


Multiple owners for commerce order [or] Allow non-owner to pay for an commerce order

You may want to look at https://www.drupal.org/project/masquerade module for some ideas to see how it does the switching since it allows:

  "...(anyone with enough permissions) to switch users and surf the
  site as that user (no password required). That person can switch back
  to their own user account at any time."

You can then write a custom module.


hook_form_alter not running if cache enabled

Messages set by drupal_set_message() goes thorough message router and may end up displayed on another page than the one you set them. If you want to add informative element to your form, use markup Form API element instead.

if($form_id == "user_profile_form" && $user->uid == 1) {
  $userid = arg(1);
  if(is_numeric($userid)) {
    $form['info'] = array(
      '#markup' => t("Current User Id on site: !uid", array('!uid' => $userid)),
      '#weight' => -9999,
    );
  }
}


How to show the product "add to cart" button on a product kit?

Drupal has a number of modules that make "add to cart" and other similar features of Drupal commerce work, by simply enabling those modules.Check out the following links:

Commerce Line Item Cart Form
This link may also help- Cart Modules


why do I receive wrong Notice: Undefined index?

I think that the name views-view-fields--activities--block.tpl.php is a suggestion for all blocks of the view activities - to get better specified template name check template information in that view. ('Information' link under Other -> Theme in the view builder) I think that the template name should be something like views-view-fields--activities--[block_id].tpl.php.

Change the block machine name if necessary.

Also, its a good practice to utilise this in templates to prevent such warnings:

<?php if (!empty($fields['field_activities_image'])):?>

<?php print $fields['field_activities_image']->content;?>

<?php endif; ?>


Create Node contains Field collection with restws + services

This sandbox will implement a field_collection service for services 3.x: https://www.drupal.org/sandbox/graber/2141747


You must have Features, UUID and UUID Features modules enabled. In the uuid_features configuration, admin/structure/features/uuid_features, select " Auto detect uuid terms. When exporting a vocabulary, include its terms."


How to create a View displaying the list of files attached to a page?

If this is for Drupal 7, a solution I found was using Rewrite Results. Create a view showing Content of type Page which displays an unformatted list of fields. Within the View, under fields add your File Field. In the settings for the field set the Formatter to URL to file, remove the label and then under Rewrite Results tick "Rewrite the output of this field". Within this section you have access to the files description field so you can enter something like

[field_files-description]

Which will output the description as a link to your file.


theming a rendered entity in a view header

When an entity is rendered an entity view mode is picked. Each entity view mode can have different dispaly configuration. So, you may add a new View mode to your entity  and set up the appropiate display config in the entity display page.

Then, in your view, seleect this view mode when configuring the rendered entity.

If you need further output customization you can define your own template for your View mode.

To add anew view mode you can check this question: How to add additional display(view mode) for node?

To set up a template file for your custom VIewmod you can check this question: How to provide template for particular view mode?

You can also use the full view mode, but this affect all rendered entities of this type.


using hook_node_submit to create an alternate upload method

Please use the copy function to store the files to different location other than drupal root or files folder.

Alter hook_node_submit function using copy instead of file_save_upload.

Try referring Drupal S3 module code, which copies the files to AWS S3 storage.


How to select Views as a Context reaction block?

To achieve you requirement please follow the steps below.

In view configuration, under advance settings select Exposed form in block as a Yes.

Now you can see your view listed at right side.

  Please remember, only blocks can be place into region, thats why you
  have to first expose your view as block.


Hook path in main menu not hold active trail

I am not sure what you are doing in a lot more areas of your system than described above, but doing the following on a d7 testbed here:

function MYMODULE_menu() {

  array $items;

  $items['about'] = array(
    'title' => 'About',
    'page callback' => 'MYMODULE_about_page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  $items['supply-area'] = array(
    'title' => 'Supply area',
    'page callback' => 'MYMODULE_supply_area_page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  return $items;

}

function MYMODULE_about_page() {
  return 'What\'s it all about, Alfie?';
}

function MYMODULE_supply_area_page() {
  return 'Making Supplies';
}

...followed by clearing caches and then setting it up via the Menu UI:

...provides the following:

so I would check how you might be doing it slightly differently on your system.


Given a node object how can I detect if it's first term (or term in a chosen vocabulary) contains a taxonomy image?

taxonomy_image_display returns an empty string iff the term has no image.

Given a node $node, the terms are stored in $node->taxonomy as an array indexed by term ID (see taxonomy_nodeapi($node, $op = 'load')).


They way you specify your callback means that it is a function. You define it in your class, which means, it is not.

Prefix it with ::, that's a shortcut that tells Drupal that it's a method on the form class. You should also use camel case for the method's names. So, something like ::ajaxExampleDependentDropdownCallback (to be clear, you also have to rename your method, not just the callback string).

I also don't understand what you're trying to do with include 'dependent_selects.config';?


How to remove 'By term' and 'View' tab being displayed at top of pages?

'By term' seems to be generated by one of the views in Organic groups: posts_by_term. You should be able to disable it at admin/build/views. Here's the issue https://drupal.org/node/1635082.

The View tab should not be displayed if it's the only tab, for example for authenticated users who don't have permission to edit the node.

Removing the View and Edit tabs, should you want that, is a bit complicated because you still might need them in some situations. Here's a pretty thorough conversation about that: https://stackoverflow.com/questions/3530756/how-to-hide-edit-view-tabs.


Check the permissions and owners of the date module folder inside your sites/all/modules it should be same as others...

Check drupal watchdog logs for more information on errors....


How do I inspect mail messages in Behat tests?

Ensure you don't have anti-spam modules installed and doing their job!

The @BeforeScenario and @AfterScenario code in the original question is correct except in the case where you have an anti-spam module that is interfering with a Scenario.

For example, if  you've got honeypot installed, ensure that you disable the time_limit setting. time_limit is there to protect the Drupal site against spambots .... and test programs! ... on the assumption that humans can't enter stuff in less than a few seconds whereas bots and test programs do so almost instantaneously.

So, if you, as I did, have honeypot installed, then you will need to temporarily disable time_limit for the duration of the test. For example my @BeforeScenario and @AfterScenario code is now as follows:

/**
   *  @BeforeScenario @email
   */
  public function beforeEmailScenario(BeforeScenarioScope $scope)
  {
    $this->m_config = \Drupal::configFactory()->getEditable('mailsystem.settings');
    $this->saved_mailsystem_defaults = $this->m_config->get('defaults');
    $this->m_config
      ->set('defaults.sender', 'test_mail_collector')
      ->set('defaults.formatter', 'test_mail_collector')
      ->save();
    // Reset the state variable that holds sent messages.
    \Drupal::state()->set('system.test_mail_collector', array());

    // If we have honeypot installed then ensure that we disable time_limit
    // So that automated tests / bots can run
    $this->h_config = \Drupal::configFactory()->getEditable('honeypot.settings');
    $this->saved_honeypot_time_limit = $this->h_config->get('time_limit');
    if ($this->saved_honeypot_time_limit) {
      $this->h_config
        ->set('time_limit', '0')
        ->save();
    }
  }

  /**
   *  @AfterScenario @email
   */
  public function afterEmailScenario(AfterScenarioScope $scope)
  {
    // revert mail system after scenarios agged with @email
    $this->m_config
      ->set('defaults.sender', $this->saved_mailsystem_defaults['sender'])
      ->set('defaults.formatter', $this->saved_mailsystem_defaults['formatter'])
      ->save();

    // Ensure we protect against spambots again if honeypot is installed
    if ($this->saved_honeypot_time_limit) {
      $this->h_config
        ->set('time_limit', $this->saved_honeypot_time_limit)
        ->save();
    }
  }


Try using the Views PHP module. First, make the field with the javascript be excluded from the display (check the box for this, don't delete the field). Then add a php field to the view, and then have it print the field with the javascript via the replacement pattern. You can also use PHP to manipulate it, write more javacript, etc. This is the only way I have found to add javascript to view rows.


Hide zip in addressfield form on commerce checkout pane?

Clive is correct. The module already adjusts the form as appropriate. If you aren't seeing this, you must have something interfering with the Ajax based update of the form element.


How to get the current user id in the path

I found the answer for this myself. Used the me aliases module. And used the path 'SITENAME/me'. Works perfectly

Provides shortcut paths to current user's pages, eg user/me, blog/me, user/me/edit, tracker/me etc.
This means logged in users no longer have to know/remember their uid, and it makes it easier to link to user-specific pages from a site help page (without resorting to using php to put $user->uid in the link).


Toggling not working properly in node--contenttype.tpl.php file

Try writing it when document get ready like this:

jQuery(document).ready(function ($) {
        $('#block1 a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  });


Did you try in your .profile:

export DRUSH_PHP='usr/bin/php56'

I think you are mixing up alias with setting an environment variable.


How do I remove required fields (or a required attribute) from customer profile in Drupal Commerce?

The only data required for the commerce profile is defined by the fields you attach to it. By default that is the addressfield. You make the field required or not required, which will result in some fields being required or not required.

You have two ways of solving this. You can either change the behavior of the address field by creating a plugin (code).

Or you can choose to only store the address in the address field and make it options and create a separate field for name that you can make required.


If you're using D7, you'll need two dashes between page-user, not one.

Some examples


The reason your getting html in your output is because your using render(), which is just a wrapper for drupal_render. Per that function's documentation, it "Renders HTML given a structured array tree."

If you want just something like:
Cats, Dogs, Otters

it would probably be better to just pull out those values, ether by looping through the field_tags array and pulling out the value into an array and then imploding your array, or simply looping through and creating a string. So instead of render(), use something like:

$tags = array();
foreach($node->field_tags['und'] as $tag){
  $tags[] = $tag['value'];
}
$variables['field_tags'] = implode(',', $tags);


Users that exist only on slave cannot login

Bakery doesn't pre-sync accounts, so any accounts that exist only on slave sites (sub-sites) won't be synchronized to the master site. This is because of the nature of needing an authoritative account master, the Bakery master site. During authentication (on a slave site) Bakery sends the user to the master to validate so if the account does not exist there the user cannot be authenticated.

To note, accounts that exist on the master that do not exist on the slave will be synchronized when the user authenticates and visits the slave site (administrators also have the option to "pull" accounts from the master).


How to put conditional multiple recipients in drupal 7 default contact us form

With this module https://www.drupal.org/project/tcontact you can create different contact categories for each language so you can specific different recipients.


How to remove content from view once user clicks on it (or reads it) in drupal 7?

You can use rules and flag module.

Create a view that list related content that the user hasn't flagged.

Create a rule that flags the content when is viewed by the user.

Setup the flag so the it doesn't show up on the node view.


Changing number of values on a field in installation profile

It's a field setting (cardinality), so assuming you're using field_create_field() to create it...

$field = array(
  'entity_types' => array('node'),
  'cardinality' => 2,
  'translatable' => FALSE,
  'locked' => FALSE,
  // etc...
);
field_create_field($field);

For unlimited values you can use the FIELD_CARDINALITY_UNLIMITED constant.


Various View-panes with arguments from url in the same panel-page. It is possible?

This discussion has gotten long in the issue queue already, so instead of repeating what's been said there, I'm try to explain from scratch how you can have two Views in the same Page, with the same arguments.

Create two Views. In both Views, add only a single "Content pane" display. No page displays.
Configure your contextual filters on both content panes, make sure they expect the same type of argument.
In the pane-specific settings, set both panes to get their arguments from context, pick appropriate context objects.
Create a new custom page, or use an existing one. Add both content panes.
Done.

Additional comments: I guess the settings of both Views have more similarites than their arguments, so I would put both of the content panes into one View.


Is it possible to add a second `drupal.behaviors` to your module?

Turns out this does work I just needed to clear cache...

If you have this issue:
go to admin/config/development/performance and press the clear cache button.

.js files are cached even though if you have set caching to disabled on the page I just mentioned.


How to manually create links to change focus on horizontal tab items?

There is a css trick that can achieve this.

Firstly, reset the default positioning on the a element:

.horizontal-tabs > ul.horizontal-tabs-list li a {
  position: static;
}

Secondly, apply an ::after pseudo-element to the link for the horizontal tab AFTER the selected/active one:

.horizontal-tabs > ul.horizontal-tabs-list li.horizontal-tab-button.selected + li a::after {
  content: "next";
  display: block;
}

Given we reset the positioning on the parent li (and the ul is relatively positioned by default) we can now position our pseudo-element relative to the ul, which spans the whole content block. So if you wanted to put your "next" link top right, do something like this.

.horizontal-tabs > ul.horizontal-tabs-list li.horizontal-tab-button.selected + li a::after {
  content: "next";
  display: block;
  position: absolute;
  right: 0;
  top: 30px;
}

This example assumes that our ul has a height of 30px. Given that the last li element (ie the final tab) does not have an immediate sibling, the "+" selector does not match on the last li, which automatically excludes the "next" link on the final tab.


Add language filter at admin/structure/block/block-content

That page is a view.

That means, you can simply edit the view and add fields, filters and so on in the UI. You can get there by finding the contextual links icon and clicking "edit view" or by going to "/admin/structure/views/view/block_content/edit/page_1".


How to add another html tag (i.e. span) before the field value renders using hook_preprocess()?

Not sure how it would be done with a preprocess hook, but an alternative would be to instead copy field.tpl.php into your theme, rename it according to the convention of field-name-[field_name], and simply add the  and  elements at the appropriate points in the template, like so:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>

        <?php if (!$label_hidden): ?>
        <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

        <?php endif; ?>
        <div class="field-items"<?php print $content_attributes; ?>>
            <?php foreach ($items as $delta => $item): ?>
            <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

            <?php endforeach; ?>


How to add destination parameter in hook url_inbound_alter

For your particular problem (redirect an anonymous user to user/login), it can be better to redirect on form submit. So, on hook form_submit() you check whether user_is_logged_in(), if not drupal_goto('user/login').


Is there a simple way to notify users about new posts on the site?

You may consider the Notify module, which is a lightweight framework for sending out periodic notifications about new site content to users and admins.

From the project page:

  The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.


limiting shipping method if a specific product is selected

You are looking for how to add a condition to each of your shipping services for a specific product or two? Here's a quick animated gif that shows you the gist of what you want:

Locate your shipping services
Click "edit component" to control which service needs to be hidden based on a particular product
Add a condition called "Order contains a particular product"
You would need to check the "Negate" checkbox before saving to "show all the things unless this product is on the order." Which sounds like what you are attempting.

Good luck!


It's not clear exactly what you are doing (eg are each of your chapters a node?) however you may be able to use the core book module for this. However it sounds like you are going to need something like Views PDF to get the formatting you need.


How to add reCaptcha while doing comments on my drupal website

Thank you all, Its done. Procedure as follows :

I have downloaded 2 modules CAPTCHA & reCaptcha.

Then extract them into /var/www/site/modules/ .

Then I have restart my web server. Then goto browser.

Next I have found CAPTCHA and reCaptcha options on modules section.

Then I configured CAPTCHA settings in configuration section according to my requirement.

Thats it !!  When I try to do comment on my website it was given me captcha challenge This is what all i need.

Thanks!! :)


If you are also using the global $user object in your code, doing something like $user=user_load($node->uid) can 'log you in'.  This is a security issue and should be corrected.


Load Hierarchical list automatically from Hierarchical select option

Instead use Simple hierarchical select module, It actually load child terms without button.

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.


How do I find the user whose field is equal to the email address?

Your first mistake is in your fetch by property action. The property must be set to email for the users to be found.

After that, the fetch by property action will always return a list even if it's only one result. So you just need fetched-user:0:name. No loop required.

In php, 0 is the first item in a list.


How do I programmatically set cache age?

This is all done from the render array itself.  The nitty gritty details are documented in Cacheability of render arrays.

In your case, you need to do something like

return [
  '#markup' => $this->t($pageContent),
  '#cache' => [
    'max-age' => 86400, // one day in seconds
  ],
];

This uses the #cache entry for the render array, and sets the max-age to be one day.  This is where you would also add in your cache contexts.

As a side note, try to avoid using '#markup'.  Use themeable elements, either though code or Twig.


Empty value "- Select -" does not appear for select fields with states requirement

To force the "empty option", assign it with something like:

"#empty_option"=>t('- Select -'),


It turns that I already posted the answer in the question, but somehow missed it during testing!

Removing , $node->book from $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book); does print the entire expanded tree.

If someone has time to add a user form option to the module it could eventually benefit many and get on the drupal.org repo.


Hook_node_grants: how do I access a user account field?

As per your error statement, field_group does not exist in $user object. The global $user object does not load the fields which are attached to user profile. if you want to load the complete user profile with attached fields, you need to use function "user_load" in your code.

global $user;

$account = user_load($user->uid);
if ($account->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $op == 'view') {
  //Do the needful
}


How can I compare data comparison with values submitted in a webform?

At a minimum, make sure you have the Webform Rules module enabled. Some details about it (from its project page):

  This module adds rules integration on webforms.

  Did you ever want to react on webform submission using rules but couldn't find the proper event?

  Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

You may also want to have a look at feature request "Expose submission data to rules". Here is a summary of it:

  Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

Issue status is "Needs work" ... not an "easy" issue.

Time for a work around ...

The very same issue contains a comment with a workaround (it's genious I think, because it's so simple), here is a relevant quote from it:

  You can initialize a rules string variable with the tokens. If you need integers or booleans you can subsequently convert it to whatever and then use it to load nodes or whatever.

A picture is worth more then 1000 words, checkout the screenprint included in that comment.

... and a demo

Consider this rule (in Rules export format):

{ "rules_validate_a_component_of_a_submitted_webform" : {
    "LABEL" : "Validate a component of a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022 and another field \u0022[data:contact_us_message-title]\u0022 which has value \u0022[data:contact_us_message-value-raw]\u0022." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:contact_us_message-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "text_matches" : { "text" : [ "submitted-form-component-value" ], "match" : "mail.ru" } },
            "DO" : [
              { "drupal_message" : {
                  "message" : "Stop and listen! ... One of the form components of the form you just submitted (= \u0022[submitted-form-component-value:value]\u0022), contains some value that is not allowed around here ...",
                  "type" : "error"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Some details about the above rule:

Rules Event: After a webform has been submitted
Rules Conditions: User does NOT have role "authenticated" (i.e: an anonymous user submitted the form).
Rules Actions:

Show an informal message on the site (this is just for QA-purposes, omit this action after you're convinced it works).
Add a variable (this is the clue of it all ...), named submitted_form_component_value and with label "Submitted form component value", and with value [data:contact_us_message-value-raw] (the form component we want to validate in subsequent Rules Actions).
Use the Conditional Rules module to perform some text comparison. In this case it checks if it contains mail.ru. If so, then perform another Rules Action like "Show an error message on the site". Obviously, at this point you could make any Rules magic happen ("block IP address" seems appropriate).

Be aware: as per the Rules Event we used here, the Webform has been submitted (and so far I've not found a more appropriate event like "Before submitting a Webform").

Showtime

With the above rule enabled, I submitted a webform. This is the message I got (as per the first Rules Action):

  The webform component submitted by Pierre (= First name:) Vriens (= Last name:) contains a field labeled "Subject:" which has value " This is a demo of a validation of a webform component using Rules ... " and another field "Message:" which has value "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ...".

And sure enough, this is the error message that follows it right away (as per the last Rules Action):

  Stop and listen! ... One of the form components of the form you just submitted (= "Bonjour! Guess what happens AFTER I submit a webform with a form component containing a string like mail.ru ? The bets are open ..."), contains some value that is not allowed around here ...

PS: In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


The weight column in the taxonomy_term_data table contains the information you need.

You can join it in to your current query via taxonomy_term_data.tid.


Should I make a SOAP or a REST service to receive files from a .Net WCF Service?

I have implemented SOAP based web service. And for file transfer I have sent the file contents as an array of bytes and it was successfully received in PHP.


pass variable from custom module file to twig template in d8

First create a function that returns the variable, something like this:

function my_function() {
return $var_name;
}

Then you must create a preprocess function, for the template, like this:

function MY_MODULE_preprocess_TEMPLATE(&$variables) {
  $V_NAME = my_function();
  $variables['v-name'] = $V_NAME;
}

Remember to clear the cache.


How to track what has (or hasn't) been "featurized" in the UI?

Try using the configuration module along with Drush. It writes the configurations into files which you can manage using GIT.

You run drush config-export –all on your dev and push your code with the config using GIT. Then you pull the changes on your prod server and run drush config-sync. It takes the config from the text files and puts them into the database making the changes live on the site.

Here is a nice article which explains this - https://shanetully.com/2014/04/drupal-and-the-holy-grail-of-workflows/


Add css to nodes of certain content type

The generic answer:

if (some condition) {
  $something['#attached']['library'][] = 'yourmodule/yourlibrary';
}

If you're in a module, do it in hook_node_view() and add it to $build. If you're in a theme, do it in hook_preprocess_node() and add it to $variables.

some_condition for your case would be $node->getType() == 'your_type', in case of preprocess, the node object is in $variables['node']

You can even do it directly within a template with attach_library(), see https://www.drupal.org/node/2456753.


This is hard for me to believe, but the results are telling.  The source fields were never loaded, so they weren't available to the destination handler.  I added the following prepare() function to my Migration class so that the values would be available.  I don't see any examples that look like this, so I'm almost certain there's a better way.

function prepareRow($current_row) {
  if (parent::prepareRow($current_row) === FALSE) {
    return FALSE;
  }

  $phone = db_select("field_data_field_phone", "p")
    ->fields("p", array("field_phone_value"))
    ->condition("p.entity_type", "user")
    ->condition("p.entity_id", $current_row->uid)
    ->execute()
    ->fetchField();
  $current_row->field_phone = $phone;
}


Would like to remove welcome message from frontpage

If you add a node, publish and check "promote to front page" the "No front page content" message will disappear, even if the node isn't shown at all.

See node_page_default for the logic there.

Alternatively, you could look into use hook_page_alter to remove the $build['default_message']


How to change image style using hook_views_pre_render()

I gave up on hook_views_pre_render and wound up meeting my requirements with template_preprocess_image_formatter as follows:

function <TEMPLATE_NAME>_preprocess_image_formatter(&$variables) {
  $styles = array('thumbnail', 'medium', 'large');
  if ($variables['image']['#style_name'] === 'medium') {
    $variables['image']['#style_name'] = $styles[array_rand($styles)];
  }
}


Migrated a drupal database from a preview site to a live site and am now getting an error

Figured it out. As admin:

admin > settings > file system

The Temporary directory was set to a different path that didn't exist in the preview site.


Your error says your application has been deleted. Go to https://developers.facebook.com and check your application under the "Apps" tab. If the app exists, check that your oauth details (on the drupal site) match. If the app doesn't exist, create an app (also under the "Apps" tab) and validate against that in your Drupal site's oauth settings.


why doesnt Drupal recognize my route name?

That code snippet looks very strange, is it really like that in your yml file or is it just wrong in the question here?

There is no route_name key inside the definition, and everything needs to be inside the first key, which is the route name. There are plenty of examples in system.routing.yml. Always try to find actual examples in Drupal core and not some online tutorials when you're not sure, as they might be outdated.

Make sure that you always use two spaces for indentation.

Your example should look like this:

mymodule.admin:
  path: '/admin/structure/mymodule'
  defaults:
    _controller: '\Drupal\mymodule\Controller\QuicktabsController::adminOverview'
    _title: 'mymodule'
  requirements:
    _permission: 'administer mymodule'


How to set Form API date_select option values

This is how I get when I copied your code without any change. Option values are correct, but somehow the order got reversed.

<select class="date-year form-select" id="edit-birth-date-year" name="birth_date[year]">
    <option value="" selected="selected">-Year</option>
    <option value="1910">1910</option>
    <option value="1911">1911</option>
    <option value="1912">1912</option>
    .
    .
    .
    <option value="2017">2017</option>
</select>

Check your Date / Date API module versions. I'm using 7.x-2.8


Remove the "upload" button from the image field form element in drupal 7

Put this code in template.php of your theme, and rename the function.

/**
 * Implementation theme_image_widget($variables)
 */
function THEMENAME_image_widget($vars){
  unset($vars['element']['upload_button'], $vars['element']['remove_button']);
  return theme_image_widget($vars);
}


ftp uploaded files are not in the library of Media module

The media module, like pretty much all of the file related modules on Drupal, relies on the managed files system which involves adding data to the db for files that are uploaded, simply using ftp to place them in the appropriate directory bypasses the "drupal way" and doesn't create these database rows, so the media module doesn't know about the files. I have used this method with other modules but not media:

::I do not claim that this is the best way to handle it, but it has worked for my use cases::

The following are the contents of a custom module I through together and assume a few things, first that your node type is "picture", second that you are just using the default "file" field that comes with drupal, and lastly that only files you are aware of exist in the directory "/sites/default/files/importer":

function MYMODULE_menu(){
    $info['db_pics']=array(
        'title' => 'NCD Callbacks',
        'page callback' => 'db_pics_callback',
        'access callback' => 'pics_is_admin',
    );
    return $info;
}
function pics_is_admin(){
    global $user;
    return ($user->uid==1);
}
function db_pics_callback(){
    $url='./sites/default/files/importer';
    $files=traverse($url);
    foreach($files as $source){
        $node=new stdClass();
        $node->type='picture';
        $node->uid=1;
        $node->status=1;

        //This part is optional and just allowed me to create a node using metadata from the image file
        //Get file info
        $fn=exif_read_data($source);
        if(!isset($fn['DateTime'])){
            $fn['DateTime']=$last_dt;
        }else{
            $last_dt=$fn['DateTime'];
        }

        $node->title=$fn['FileName'];
        $names[]=$node->title;
        $node->created=strtotime($fn['DateTime']);

        //Fetch the actual data from the image file
        $image = file_get_contents($source);

        // Returns the new file object after saving the image to the appropriate Drupal File schema
        $file = file_save_data($image, 'public://'.$fn['FileName'], FILE_EXISTS_RENAME);
        $node->field_image['und'][0]=(array) $file;
        node_save($node);
    }
    return '

'.implode('

',$names).'

';
}

//quick and dirty utility function assumes only files you want are in the specified directories
function traverse($url){
    $entries=array();
    $dir=scandir($url);
    foreach($dir as $entry){
        if(in_array($entry,array('.','..'))) continue;
        elseif(is_dir($url.'/'.$entry)){
            $entries=$entries+traverse($url.'/'.$entry);
        }else{
            $entries[]=$url.'/'.$entry;
        }
    }
    return $entries;
}

This is a little different than what you asked for, but I see people asking for this functionality frequently so I wanted to give a complete answer about importing files as nodes, for your specific use case the callback function can be significantly shortened to:

function db_pics_callback(){
    $url='./sites/default/files/importer';
    $files=traverse($url);
    $saved_files=db_query('SELECT filename FROM file_managed')->fetchAll(PDO::FETCH_COLUMN);
    foreach($files as $source){
        $image = file_get_contents($source);
        $fn=substr($source,strrpos($source,'/')+1);
        if(!in_array($fn,$saved_files)){
            file_save_data($image, 'public://'.$fn, FILE_EXISTS_RENAME);
        }
    }
    return 'Finished';
}

That should add all of your files to the managed files database table and allow you to view them in the "Library" tab. Good luck!


Get content of selected option after user select any option from select field

I have done same with User Roles and Users. Check below code if you can find it helpful.

function custom_menu(){
    $items = array();
    $items['custom'] = array(
        'title' => 'custom',
        'description' => 'Custom',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('custom_form'),
        'access callback' => TRUE,
    );

    // " % " is the RID coming from '#autocomplete_path'.
    $items['autocomplete/%'] = array(
        'page callback' => 'autocomplete_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

function custom_form($form, &$form_state){
    $options = array();
    $roles = user_roles($membersonly = TRUE); // Getting list of Roles.

    // Removed "Authenticated" role from the list.
    // That is not listed in "users_roles" Table.
    array_shift($roles);

    foreach ($roles as $key => $value) {
        $rid = user_role_load_by_name($value);
        // Give RID to each role as their key in array.
        $options[$rid->rid] = $value;
    }

    // Defining $role as selected value of Select list.
    $role = !empty($form_state['values']['roles']) ? $form_state['values']['roles'] : '';

    $form['roles'] = array(
        '#type' => 'select',
        '#title' => 'Role',
        '#options' => $options,
        '#ajax' => array(
            'wrapper' => 'auto-wrapper',
            'callback' => 'select_callback',
        ),
    );

    $form['auto'] = array(
        '#type' => 'textfield',
        '#title' => 'Users',
        '#autocomplete_path' => 'autocomplete/' . $role, // Pass RID to path.
        '#prefix' => '
',
        '#suffix' => '
',
    );

    return $form;
}

function select_callback($form, &$form_state){
    return $form['auto'];
}

function autocomplete_callback($role, $string = "") {
  $matches = array();
  if ($string) {
    $query = db_select('users', 'u');

    if(is_numeric($role) && $role != ''){
        $query->join('users_roles', 'ur', 'ur.uid = u.uid');
    }

    $query->fields('u', array('name', 'uid'));

    if(is_numeric($role) && $role != ''){
        $query->condition('ur.rid', $role)
            ->fields('ur', array('rid'));
    }

    $query->condition('name', db_like($string) . '%', 'LIKE')
      ->range(0, 10);

    $result = $query->execute();

    foreach ($result as $user) {
      $matches[$user->name] = check_plain($user->name);
    }
  }

  drupal_json_output($matches);
}


Can Views theme/rendering be disabled programmatically?

Yes under Advanced there is a Theme Information link that will show you template file(s) that you can override to meet your needs depending on the display format selected (fields, rendered entity, etc).

If you need to change how the page itself renders for example, you can also affect the sitewide theme function used to create the url by changing theme function in hook_menu.


Migrate site from dev environment to production server - 404 errors

It sounds like your .htaccess file is missing, or AllowOverride is disabled.  Clean URLs not working? Check your .htaccess file!


Adding the is_front variable to a Paragraphs template

You should be able to add this with a preprocess function in mytheme.theme of your theme.

/**
 * Implements hook_preprocess_paragraph().
 * @param $variables
 */
function mytheme_preprocess_paragraph(&$variables) {
  $variables['is_front'] = Drupal::service('path.matcher')->isFrontPage();

  // Ensure the cache varies correctly.
  // Drupal 8.2.x or lower
  $variables['#cache']['contexts'][] = 'url.path';

  // Ensure the cache varies correctly.
  // Drupal 8.3.x+
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

This should add is_front as a variable to any paragraph twig template. Clear cache after adding this code.

Per 4k4's comment, if this is Drupal 8.3 you will also need to add a cache context.


How do I create a php page that has access to the Drupal API?

The correct way to "create a PHP page that executes Drupal API functions" is to create a module.

In that module, you implement hook_menu() which allows you to tell Drupal that it should call a given php function for a specific path, for example 'yourmodule/somepath'. Inside that, you can then execute whatever PHP and Drupal API functions which you want.

See http://drupal.org/node/1074360 for more information.


If you're looking for a good core alternative to select entities, using custom queries, make sure you familiarize yourself with Entity Field Query (EFQ)

e.g, fetch 10 published article nodes with field_my_field value 'foo':

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_my_field', 'value', 'foo')
      ->range(0, 10)

$result = $query->execute();

if (isset($result['node'])) {
  // nids are here
  $nids = array_keys($result['node']);
  // nodes can be loaded as such
  $nodes = entity_load('node', $nids);
}

More EFQ info here


How to group node comments using parent comment in views

Hmmm, maybe this way:

Create Views that view only comments. and filter from all comments only those, that was made by the users with role "student".
With Display Suite module mark-up displaying of your content type - "screw" this view to your content type.
Edit what view that is checked id of this node and show comments only for this node


Drupal - Update Statistics label from "read" to "view" and "reads" to "views"

It's because you aren't accepting $variables by reference, so you're just changing a local variable. This will probably do what you want:

function mytheme_preprocess_node(&$variables) {
  $content = &$variables['content'];

  // Check the node  type to make sure
  // we have the one we want

  $content['links']['statistics']['#links']['statistics_counter']['title'] = str_replace('reads', 'views', $content['links']['statistics']['#links']['statistics_counter']['title']);
}


How do you customize the title of an RSS feed created by Views RSS?

Not sure how much this will help as its not exactly what you're asking (i think):

I was using views_rss to show comment threads to a question_answer module question. But I wanted the question to show up as the 1st time in the RSS feed (as RSS feeds) may only show 1 piece of data by their nature (eg, comments or new posts or blog posts) ...

I didn't muck with the title of the Feed because I saw issues with Firefox Sage vs. Google Reader as what the "title" of the RSS feed is -- so I stuffed the "FAQ question" to the comment thread at the top of the RSS feed ....

/**
 * Implementation of hook_views_pre_render().
 *
 * For the comment rss feed we want the description to contain something such
 * as "topic #N: topic text". These values are excluded in the view already.
 * The RSS feed supports a description field but cannot have PHP code in it,
 * it's just static text.
 *
 * This is a means to theme the RSS description field for valid RSS feeds. The
 * view enforces that the parent node is published, and that comments are
 * published as well.
 *
 * http://stackoverflow.com/questions/4011505/how-can-i-add-a-summary-row-to-a-drupal-view
 */
function MYMODULE_discussion_views_pre_render(&$view) {

  if ($view->name == 'MYVIEW_discussion_comment_rss' &&
        $view->current_display == 'feed_1') {
    # Insert the question as a leading comment for this feed.
    $question = node_load(array('nid' => ARG(3)));
    $qrow = new stdClass();
    $qrow->comments_subject = htmlentities('Question Was:');
    $qrow->comments_comment = htmlentities($question->field_topic_text[0]['value']);
    array_unshift($view->result, $qrow);
  }
}

EDIT: My answer was coded for a D6 site, but the exact same principal applies to D7 (and I think the code as well).


I think Domain Path module can solve your issues.

  The Domain Path module allows the creation of separate path aliases
  per domain for nodes created using the Domain Access module.


It's displayed using the Context module.  I found it like this:

Go to admin/build/context and select the global context

Click the Blocks reaction
Under the Space tools region, Atrium: Search form block is being shown

I then searched for the name Atrium: Search form, and found that the block is defined in the atrium_features module, in functions atrium_block and atrium_search_form of file atrium/atrium.module.

You could modify the search form using a hook_form_FORM_ID_alter hook, such as hook_form_atrium_search_form_alter.


The field group module is designed to solve this exact problem The Drupal 8 version is reasonably up-to-date.

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

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


The CSS solution might not be the best for SEO purposes...
Another better alternative is to write in the page title field :

<No Title>
or : to leave it blank

And the title wont be displayed


How can I use 'xx time ago' as date format?

There are two ways to tackle this.
One is to just use the field formatters.  If you have a DateTime field, just goto Manage Display, and change the Format to Time ago.  Then click the gear, and pick some options.  These are cache aware that will bubble up through the page, but you may end up with short cache lifetimes in some situations.
The other is to use a template_preprocess_node().  This is preferable when you have a timestamp that isn't a field.  Then you use the date formatter service to render out the timestamp in timeago format.  It is preferable to use the formatDiff() versions rather than formatInterval() (while not formally deprecated, it is discouraged).
function MYTHEME_preprocess_node(&$variables) {
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
  $date_formatter = \Drupal::service('date.formatter');
  $request_time = \Drupal::time()->getRequestTime();
  $variables['foo'] = $date_formatter->formatDiff($request_time - 12345, $request_time, [
    'granularity' => 3,
    'return_as_object' => TRUE,
  ])->toRenderable();
}

When you specify 'return_as_object' => TRUE with the formatDiff() functions, a FormattedDateDiff object gets returned, which contains the formatted string as well as a mostly accurate [#cache]['max-age'] entry in a render array to make this work with Drupal 8's new caching system.  Then you can just use {{ foo }} in your Twig template; the render engine will do the right thing with the render array instead of a plain string.
Also read the docs on DateFormatterInterface for the formatTimeDiffSince() and formatTimeDiffUntil() variants, and for the $options you can pass in.


Is it possible to disable CSS and Javascript aggregation by role?

To do exactly what you want; using hook_css_alter & hook_js_alter is how to do it. Set the preprocess key to FALSE for everything.

For an out of the box solution that is fairly close to what you want https://www.drupal.org/project/advagg/ can do it. Give that role the "bypass advanced aggregation" permission and then they can add ?advagg=-1 to the end of the URL to see the change.

Will also mention that using a dev environment when altering css/js is ideal.


How do I programmatically close a simple_dialog window

try this code using jquery,

jQuery('#simple-dialog-container').trigger('click');

change id/class to anchor.


How to get by insufficient memory impass - can't access site?

There is 3 method to increase your PHP memory limit.  They are all outline in http://drupal.org/node/207036

The best way to check your current situation is to create a file in the root directory call phpinfo.php, with these lines of code

<?php
  print phpinfo();
?>

Then check the settings by going to http://www.example.com/phpinfo.php


Yes that would be relatively easy. How I would do that:

Edit the main menu: yoursite.com/admin/structure/menu/manage/main-menu and add menu item named My Articles (linking to a view is what I would do but you can choose to link it to anything you want - or nothing)

Edit the article content type: yoursite.com/admin/structure/types/manage/article

in Publishing Options deselect Promoted to Front Page
in Menu Settings:

check Main Menu under Available Menus
select My Articles (or whatever name you chose) in Default parent item

Then every time you create an article select provide a menu link. This will obviously work best for new sites where you don't have to go through and edit old articles to be in the menu.


Print admin toolbar icon in custom module

If you want to add svg icon for your menu link item in admin toolbar, you have to alter toolbart.

In your mymodule.libraries.yml file

toolbar:
  version: VERSION
  css:
   theme:
    css/styles.css: {}

And you need to implement hook_toolbar_alter() in your mymodul.module

function mymodule_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'mymodule/toolbar';
}


Passing node parameters into views block

I can't give you the complete Views-based solution off the top of my head (although I think it must be possible) but the key to the solution is using 'Contextual filters' (they used to be called 'Arguments' in D6/Views2) and relationships.

Contextual filters are filters that take their value from the url, so you can narrow down the results to the current node currently. By adding a relationship for the node reference field, you can retrieve information from the nodes referenced by that field.

If I'm not mistaken, you can add a second contextual filter that makes use of the relationship, to exclude the current node from the related nodes.

Sorry this is not a complete how-to, but I hope it gets you started.


Programatically adding Taxonomy text field

The only way to achieve adding a text field to a Taxonomy Vocabulary is to place it in the hook_enable() function of your module.

If it's outside of that the "Text" module won't be loaded and you'll receive the error above.

If anyone has a way around that please let me know.


How do I perform a redirect to the cart?

If you use the Devel module, you could also find the right routes on "/devel/routes".

An then do something like:

  $url = Url::fromRoute('commerce_cart.page');

  //$url->toString();
  $form_state->setRedirectUrl($url);


This can be achieved with Entity reference and relationship

Create a views of studio.
Make a relationship of Entity reference with user and hardware information
Now when you select fields all the fields from user, studio and hardware will be available in the list.
Select those fields which you need. and that's it.


What can cause form API to ignore the weight of an element that is a collection of buttons?

I've discovered this is expected behavior. The solution is to copy the buttons into new form elements, position them where desired, and remove the default buttons. Here are step by step instructions on how to do this.


Are use Drupal\Core\Form\FormStateInterface statements for a Drupal 8 hook required?

It is recommended to use the use + short reference. Technically, it makes no difference, but it results in shorter lines and is easier to read.

The reason the hook documentation always uses full namespace is to make it easier to copy it into a module file, as you'd otherwise also have to look up the use statement.


If you don't need to save the data returned by the external source in your drupal database, then you can go through below mentioned points,

In hook_form_form_id_alter declare a custom submit function

$form['#submit'][] = "my_module_form_submit_handler";
in the custom submit function redirect after submission.(are you using cURL to send and receive data to and from external api.)

$value1 = 'value returned from external api';
$value2 = 'value returned from external api';
$form_state['redirect'] = 'myurl/' . $value1.'/'.$value2 ;

Create a menu item with hook_menu and pass the values as argument

$menu['myurl/%/%'] = array
(
  'title' => 'some title',
  'page callback' => 'my_page_callback',
  'page arguments' => array(1, 2), // 1 and 2 are the first and second indexes of the URL - the location of the wildcards
  'access callback' => TRUE,
);
in page callback function pass the variables

function my_page_callback($val1,$val2)
{
return theme('custom_data_page', array('val1' => $val1,'val2' => $val2));

}
implement hook_theme

function mymodule_theme($existing, $type, $theme, $path) {
    return array(
        'custom_data_page' => array(
            'variables' => array(
                'val1' => val1,
                'val2' => val2
            ),
            'template' => 'your_template_filename', // do not include .tpl.php
            'path' => 'path-to-your-template-file'
        )
    );
}

Create the template file in templates folder
Clear cache.
Let me know if you face any issues


“admin/people” filters not available anymore

I would check:

Is the views module still enabled?
Is this specific view enabled?
Did the configuration get changed for the view that exists at admin/people?

For #1, go to the modules page and scroll down to views and confirm it is enabled.

For #2, I noticed that I was able to "Disable" the user_admin_people view and then I get a screen at admin/people that looks exactly like yours. The resolution to that problem is to go to /admin/structure/views/ and "Enable" the user_admin_people view.

For #3, you could install a fresh version of Drupal 8.7.3 and compare the configurations of the view to find if it's wrong.


Form Alter Foreach Loop changes not sticking

I've finally managed to resolve my issue, but I'm not sure why. I decided to change what array I was using to iterate through the filter fields on my form. By switching to iterating through the form array instead of form_state, any changes I make to it now are sticking.

foreach($form['#info'] as $delta => $input) {
    $filtername = $input['value'];
    $collapsed = (empty($form_state['input'][$filtername]) ? TRUE : FALSE);

    $form[$filtername . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $filtername]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$filtername . '_fieldset']['' . $filtername] = $form[$filtername];
    unset($form[$filtername]);
    unset($form['#info']['filter-' . $filtername]);

}


Allow user A to grant view permission of their node to user B

Perhaps consider using Organic Groups which allow users to create and control groups of users and curate content for them.

There is also Node Access User Reference which is slightly more specific.

Both should work together but I think you will only need one of them for your stated needs.


For most part, you can achieve this using contrib modules. Here are some of them:

Views will allow you to fetch most of the information in your database and create pages, blocks and subpages.
Administration Views will override default admin pages (e.g. /admin/content/node and /admin/people) and even more importantly, allow you to change the output of those pages.
Views Data Export allows you to export information from Views to a variety of formats, from txt to csv.
Google Analytics with custom
Messages module. I've used Messages module many times when I needed to track an action of a user somewhere. It integrates with Views and Rules, and in combination with the two you can log most actions on the site.
Total Control gives you a central administrative page from where you can manage different sections. It's also coming with certain panes that you might find useful.
Panels will allow you to create more complex pages that contain blocks and information in a different layout than what is provided by default in your admin theme (e.g. 3 columns and multiple different rows).
Forena reports module allows you to create custom reports from the database.

For additional information, see this response by Pierre Vriens.

Lastly, I just realized that this question might not be really suited for this website as it's opinion based and asks for module suggestions. If that's the case, I guess mods will remove both the question and answer.


How do I change template file for the user registration form?

I found the solution here: http://www.foreach.be/blog/how-manipulate-forms-drupal-8
and the file name for overriding the user register form is:
form--user-register-form.html.twig


Turns out there was yet another .tpl file, just for this element, I could copy from the moduel and place in my themes directory - component.tpl.php


how to hook checkout pane defined in another module?

commerce_checkout_form_PAGE is a form ID. Use it inside of HOOK_form_FORM_ID_alter to edit a particular page of the checkout process. Like so:

function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
    $form['#prefix'] = '

You have coupon? Add it here.
' + $form['#prefix'];
    $form['#suffix'] = $form['#suffix'] + '
';
}

Alternatively, you can also do a generic alter and check the build info in $form_state:

function MYMODULE_form_alter(&$form, &$form_state) {
  if ($form_state['build_info']['base_form_id'] == 'commerce_checkout_form') {
    // We're in checkout.
    $form[PANE_ID] ...
  }
}


When using Views Bulk Operations, the options for Rule Components are not shown in the VBO drop down for all users

If you are adding operations using Rules Component then you have to set the permission.

Edit your rule component and under the settings there will be Configure access for using this component with a permission, set your permission here.


Unpublish article based on non date type field

If you don't want to write custom code you can use the https://www.drupal.org/project/scheduler module.

Quoting the description: "This module gives content editors the ability to schedule nodes to be published and unpublished at specified dates and times in the future "


AFAICT the code you've posted will populate the entity with the values from the CSV file - but nothing's set up to persist those values. The Field API itself can persist values it knows about. Look at file_field_schema()

/**
 * Implements hook_field_schema().
 */
function file_field_schema($field) {
  return array(
    'columns' => array(
      'fid' => array(
        'description' => 'The {file_managed}.fid being referenced in this field.',
        ...
      ),
      'display' => array(
        'description' => 'Flag to control whether this file should be displayed when viewing content.',
        ...
      ),
      'description' => array(
        'description' => 'A description of the file.',
        ...
      ),
    ),
    ...
  );
}

Through this, the Field API knows to store the file ID, whether or not to show the file when viewing content, and a description of the file. Image field is very close to file field, and shares mostly the same code. And looking at image_field_schema() you can see where the title and alt fields come from.

/**
 * Implements hook_field_schema().
 */
function image_field_schema($field) {
  return array(
    'columns' => array(
      'fid' => array(
        'description' => 'The {file_managed}.fid being referenced in this field.',
        ...
      ),
      'alt' => array(
        'description' => "Alternative image text, for the image's 'alt' attribute.",
        ...
      ),
      'title' => array(
        'description' => "Image title text, for the image's 'title' attribute.",
        ...
      ),
      'width' => array(
        'description' => 'The width of the image in pixels.',
        ...
      ),
      'height' => array(
        'description' => 'The height of the image in pixels.',
        ...
      ),
    ),
    ...
  );
}

I think the right way forwards depends on your data model. In the example below there are two nodes with file fields, each referring to the same file. Note that they can have different alt and title fields even though they're referring to the same file.

Node 1:
  file_field:
    fid: 1
    alt: A beautiful beach
    title: Wish you were here?

Node 2:
  file_field:
    fid: 1
    alt: Great swimming
    title: Fun for all the family

The alternative I suggested in a comment was to add the fields to the entity itself.

File 1:
  alt: A beautiful beach
  title: Wish you were here?

Node 1:
  file_field:
    fid: 1

Node 2:
  file_field:
    fid: 1

This means the alt and title will always be the same for a given file. It's obviously for you to decide which model meets your needs more appropriately. If you want to store the data per-field (the first example) you have two choices:

Use an existing field and alter its schema with hook_schema_alter() - a bit painful as there's no hook_field_schema_alter(). Only do this if conceptually every instance of this field should have that extra data.
(I'd prefer this personally) Create a new field that stores the extra columns you're interested in. Image field is the perfect place to look for inspiration, because its functionality's based on file field and it has extra columns.

If you want to store the data per file entity, then you can use fieldable files and I'm fairly sure you should be able to set everything up through the feeds UI. (IE no need for the feeds code above.)


How to import nodes with custom fields using Feeds module and Feeds JSONPath Parser

There are 3 places where the problem could lie:

Data not being correctly parsed by feeds
Data not being correctly saved by feeds
Problem with the field definition itself

Number 3 is ruled out since fields save correctly via the UI.

Troubleshooting Number 1.

Add a hook_feeds_after_parse to your module and either step through with a debugger or dump the $items array to the dblog:

function mymodule_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  if($source->id == 'ENTER YOUR SOURCE ID HERE') {
    watchdog('My Module', '<pre>' . print_r($result->items, TRUE) . '</pre>');
  }
}

Question: is there a value in the items array for your engine field?

If no: there is a problem in the JSON parser definitions and feeds is not extracting the data correctly.

If yes: if the information exists that you require, i.e. every sub field value exists then the problem is not with the feeds parsing.

Troubleshooting Number 2

This points to an issue with your implementation of hook_feeds_processor_targets_alter.  Most likely, the data is not in the correct format for saving.  Add some watchdog statements in this function to determine:

Is the callback being fired?
If the callback is being fired then there is an issue with your hook_feeds_set_target implementation.  It isn't providing the correct data format to allow the field to be saved.  You could add a dpm() statement to hook_node_update and then save a node via the UI. This will show the correct format.


Inline entity form complex and cardinatlity

Try changing the type to inline_entity_form_complex so that you have the following;

$form['inline_entity_form'] = [
    '#type' => 'inline_entity_form_complex',
    '#op' => 'add',
    '#entity_type' => 'my_ent_type',
    '#bundle' => 'my_bundle',
];

Got the pointer from the following answer. https://drupal.stackexchange.com/a/207582/9906


I'd highly recommend using Search API with which you can create an index and custom search from any entity including Taxonomy terms. You can then customize your search page using Views.


Displaying content from an entity reference in a view

Remove current contextual filter and relationship
In contextual filter add nid.
In its configuration select raw value from URL, then select argument number which is your nid form url
Now you can also set default value in this configuration
In block display setting show your block on your content type.


How do you create a custom permission to administer a custom module?

Permissions can be added in the mymodule.permissions.yml file of the custom module.
You can also define permissions with a callback, if they depend on other items in the application.
See: https://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8


How to clone an existing View and change the format from table to CSV?

Here are the steps to get you going (referring to the screenprint you added):

Click the drop-down list in the upper-right that says view Working Papers Other, where you should then see another list item with label clone Working Papers Other.
Select (click) on that list item with label clone Working Papers Other.
Note that you'll then have an extra (and same named!) button to the right (or below) the 8 buttons you already have, with the very same label Working Papers Other, and the newly added one will be highlighted (grey / black), and selected.
To improve readability, hurry to go change the line (upper-left) that says "Display name: Working Papers Other" (by clicking on that Working Papers Other link). I suggest you change the Display name to (eg) Working Papers Other (CSV).
Change the line (upper-left) that says "Format: Table | Settings" (by clicking on that Table link). At this point you should be able to change the style of the view from Table to the Views display offered by the Views data export module, with label "Data export".
Tune (refine) the "Settings" of the Data export views display to fit your needs, whereas you can see how the result will look like in the preview near the bottom of your page.
Change the line (upper-middle) that says "Path: /publications/working-pa..." (by clicking on thatPathlink). I suggest you change the path by only adding some suffix such as-csv`.
Don't forget to use the Save button (upper-left) to permanently store the updated configuration of your view.
Click the button (upper-right) that says view Working Papers Other (CSV) (if you used my suggestiuon in item "4.") to actually view (browse) the Views result produced by the various changes described above ... Is it a CSV file that fits your requirements? If not: must be that you did something wrong in the steps described above ...

Note: If you want to become more familiar with Views, checkout the (free) set of 30 video tutorials about the Views module.


Expiration of cached pages stuck at 6 hours

The settings.php file contained the following line, which caused the behavior I was observing.

$conf['page_cache_maximum_age'] = 21600;


I have the same issue.
the problem was in the module:

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:
  You have requested a non-existent service "colorbox.attachment";.

The module mantainer do not add colorbox to dependencies.

So you just to need to install and enable Colorbox module.


I'm guessing you mean the Redirect module, not the Global Redirect module.

One thing to clarify: Are you trying to change the actual destination of the redirect (by initially having example.com/newsletter redirect to sites/files/upload/newsletter.pdf one day, then the next day having it redirect to sites/files/upload/newsletter-2.pdf)?  Or (as I think you're saying) are you actually overwriting newsletter.pdf on the server so that it's a different file?

I'll assume you're doing the latter.  If so, then the type of redirect doesn't matter.  You're facing caching on the browser side and you need to change your mod_expires settings.  Assuming you're allowing htaccess files to influence your apache configuration, you can put the following in the mod_expires section of your .htaccess file in the root of your site:

ExpiresByType application/pdf A86400

That would make browsers cache PDF files for a day (86,400 seconds).  An alternative, equivalent syntax is:

ExpiresByType application/pdf "access plus 1 day"

You can adjust that parameter however you like.  See documentation here.


FacebookforDrupal Publish to stream isnt working?

Sorry, there is no hook_nodeapi() for D7. In D7, there are seperate hooks for create, update, view and delete operations. You could use this Link as a reference.
You could insert your dpm("test"); inside hook_view() to test it.


How to add an attribute in an input date field

Try with

$form['field_periodo_prenotazione_to']['widget'][0]['value']['#attributes'] = array('autocomplete' => 'Off');


Can`t access config panel after the installation of Ubercart and e-commerce modules

You are using dpm function to print variable. To fix this issue you just need to enable the devel module or comment the dpm function.


How can I change a field's widget type on its node edit page?

Login in as super admin:

content management ->content types -> edit [your content type]->managefields

click on configure of that field and there you will see second button which named "Change basic Information"

Click on this button and will get the way to edit widget type.


Getting the auto summary from a node body

node_view() is appropriate when you need to render whole node or many of it's fields.
But sometimes you have to render the only field you need. It can be done with field_view_field() or field_view_value():
$node = node_load($nid);
// Render array of body field.
$build_body = field_view_field('node', $node, 'body', 'teaser');
// Render it in common way.
echo render($build_body);

The interesting thing is that you can pass your own field formatter settings instead of view mode with the fourth parameter.
Please, read API docs for more info.


How do I force unique values within a multi-value set?

It might be easier to filter the autocomplete results using JS. You could either extend the prototype being used by Drupal or use some sort of trigger for when the results are being displayed.

I don't think that server-side solutions such as session variables and so on are practical as there's no guarantee that the results of previous calls were actually used by the user. Similarly, hacking the autocomplete feature to perhaps send existing values along with current user input is inherently impractical.


How to render a node with absolute URL to use in a mail?

Two possible approaches:

Find the URLs in preprocess targeting this specific view mode and apply setAbsolute(), see for example How do I render the absolute URL of a referenced entity in a simplenews newsletter?
Apply a regex on the rendered output $html or use Html::transformRootRelativeUrlsToAbsolute() like added recently to the core MailManager:

$html = Markup::create(Html::transformRootRelativeUrlsToAbsolute((string) $html, \Drupal::request()->getSchemeAndHttpHost()));

Source: https://git.drupalcode.org/project/drupal/commit/530f7ac

By the way, use instead of render() the method renderPlain(), see How to deal with Bubbleable Metadata when there's no rendering context and no render array


Guidelines For Features as building blocks

Some of my thoughts coming from my experience:

Features should be logical and separated functionality blocks - each feature should be standalone as much as possible and there should be no overlaps to prevent one feature overriding other.
You can safely put your custom code in features - if you write something into your .module file (or any other that is not filled with features exports), next time you recreate the feature it will be respected and it will stay there - this fact is not so often used but it can be very helpful to achieve the first point.
More smaller features are easier to manage than few big ones - this is just because bigger features are more error prone when creating (e.g. you add something without noticing) and you need to inspect more code when searching for stuff.
It's good practice to put features in separate folder (e.g. sites/all/modules/features)
You can use Features Extra (https://drupal.org/project/features_extra) to export some additional entities, especially blocks.
Use Context (http://drupal.org/project/context) or Panels (https://drupal.org/project/panels) for powerful exportable layouts.
Everything can be exported only once, features UI will not even allow to export duplicities.
Use drush to make your life easier (see drush help, section features)
Use Advanced Options to replace your existing features when recreating (instead of downloading it and copying it manually)
Keep everything clean 1 - install Diff (https://drupal.org/project/diff) to see overrides of your features code and revert when necessary.
Keep everything clean 2 - recreate you features often, to keep your code updated and to avoid unclear situations when you are not sure what should be in code, what actually is in code and what is overriden in database.

I will update my answer when I come up with additional stuff


Well if you have tons of time you could implement a component type... but because that is unlikely you should just add a validation hook and a textfield to the webform. You could do a valid_url($form_state['values'][[your_field_name']); in your validation hook.

Someone asked this question on d.o previously here. You can find all sorts of examples on "things you may need to do special with a webform" here.

Another possible solution would be to install the Webform Validation module, add a regex validation to your field, and steal a known usable url validation regex like drupal has.


At this point assuming your site doesnt make use of extra modules, you can likely assume 7.x php works fine. I have found in numerous sites in the last few months that moving to php7 went fine and most php 7 were squashed in popular D7 modules in the last year or two.

If you have alot of custom modules you could try running a php 7 linter from github to check modules for php7 related issues, rather than trying to live-test drupal itself.

Something such as this github repo:
https://github.com/wimg/PHPCompatibility


Getting child term's Tid not the parent's

For the further references: I changed my code to this:

$option = [];
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('collections', $parent = 0, $max_depth = 3, $load_entities = FALSE);

foreach ($terms as $term) {
$key = $term->id;

if($term->depth == 0){
  $term = $term->name;
}
elseif ($term->depth == 1) {
  $term = '-'.$term->name;
}
elseif ($term->depth == 2){
 $term = '--'.$term->name;
}
elseif ($term->depth == 3){
  $term = '---'.$term->name;
}
elseif ($term->depth == 4){
  $term = '----'.$term->name;
}
 $option[$key] = $term;
}

$form['collection'] = array(
  '#type' => 'select',
  '#title' => t('In Collection:'),
  '#empty_option' => t(' '),
  '#options' => $option,
);

Sorry if I wasted your time.


How can I use Typekit fonts with Drupal 6? Preferably without an extra module

If you want the typekit code on every page of your site and you don't want a complicated solution just put the code in the page.tpl.php file. They are external scripts I assume so drupal_add_js won't help you in D6.

You can add things to the scripts variable in template_preprocess_page(), but if you are going to do that on every page then you may as well just put it next to where the scripts are printed in page.tpl.php


Log where permissions are being refused?

No. Permissions usually are checked by a function call to user_access and for performance reasons there is no way to override that (not that D6 was so big on overrides like D7 is -- still that function can't be overridden in D7). You can set use devel to see the query if one is run or Views can display the query. As a last resort, you can add error_log(4, $string); into user_access itself to send the permissions into Apache error log or similar.

Note that it can be a node access issue, in this case the query log will help you.


From your question, by hook_cron() this can be done. You can use a watchdog() function to make sure that the cron was run. The computed field has a table entry in the database, so you just need to find out that one and check each user's birthday from a DOB field stored in another table based on UID. Then if the user has updated the DOB then check for their ages and insert/update the value in the "field_age" computed field. All of the operation can take place in hook_cron() which will be invoked by cron.php each time the page is fired in crontab.


If I may, you're not doing this in the most optimal way.

The best solution would be to implement hook_views_data(), and describe your custom entity's base table to Views. Then you can use Views to build your page through the UI, and all of your entity's properties and fields will be available to output as fields, filter by (exposed or not), and sort by.

You get all of the flexibility you're used to with Views for nodes, and it's easy to write custom field/filter/sort handlers for your custom properties if they need a bit more functionality than the default.

To answer your original questions (in case you don't want to go down the Views path):

Remove the required attribute after the call to field_attach_form(), e.g. unset($form['field_foo'][LANGUAGE_NONE]['value']['#required']);
The order isn't broken, it's exactly what you've asked for. If you want the fields to appear before the search, but field_attach_form() before the definition of $form['search'].


How to display tags of content filtered by a different tag

You will need to use three views.

The first view can be either a view of taxonomy terms (easy enough), or a view of your content type with a relationship, taxonomy terms on node. Use this path: work

If you select the second option you will get duplicate rows, and you will have to use aggregation. You will need three fields: tid (hidden), type (hidden and aggregation set to count), and term name (rewrite it to a link with this: work/[tid]).

The second view will have a path: work/% and will be a view of your content type. Add two relationships, one to taxonomy terms on node and select year, and another to taxonomy terms on node, and select project. Give them each a descriptive identifier. Now add a contextual filter: The tid of a taxonomy term, and select the relationship of the year taxonomy vocabulary. Now you will get a lot of duplicates. Again set aggregation on and this time you might have to add fields content type (hidden and aggregation count) as well as tid (hidden, relationship to year vocab, aggregation count). Add two hidden tid fields (for the link construction), one with year relationship, other with project.
Add your link field and rewrite as link like this: work/[tid]/[tid_1]

The third view is more of the same. It will have path of word/%/%. You will add one more relationship and contextual filter than you did for view 2.

In view 1 if you do it based on your content type then only years that are being used by your content will show. If you do it as a taxonomy view then all year terms will show, and depending on your content some of these term links will then navigate to empty views.

And when you build your views start off without any sorting on them as this will give initial issues with aggregation. You can add sorting back after you have a working solution.


What is difference between #value and #markup?

#markup is

  Used to set HTML that will be output on the form.

#value is

  Used to set values that cannot be edited by the user. Should NOT be confused with #default_value, which is for form inputs where users can override the default value.

For #value this might include submit buttons, hidden elements, etc. - basically anything that needs a value for the form submission, but where that value should not come from the user.

The only change you need to make in your sample code is to allow for the fact that classes in the attributes array must now be in an array themselves:

$form['in_title'] = array(
  '#type' => 'button',
  '#value' => t('ort'),
  '#executes_submit_callback' => false,
  '#attributes' => array('class' => array('hide-submit-exclude')),
);


Hi you could use event_calendar module.. The calendar module only display calendars value. It is not display any event on it... So we are going for event calendar module. It gives various option for display the events and also provide the event content type..


Copy core template to your theme template folder (yourtheme/templates) core/themes/stable/templates/form/container.html.twig and clear caches.


Unable to access Admin panel of Drupal site at Localhost, migrated from server

This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that browser you are able to login, then it's probably a cookie problem (in your original browser).

If http redirects to https you might have a module that does this or it might be a rule in .htaccess see if you can comment out the rule in htaccess or disable any relevant module with drush dis MODULENAME.

If none of these suggestions help, then re-edit your question by adding more details about which modifications to your '.htaccess file, httpd.conf, etc' you already tried (and didn't work).