Narrow down which module is causing a PHP warning

FIELD_BEHAVIOR_DEFAULT is defined in the core field.module file, which will always be loaded into the page build if you have the core field module enabled.

If you're getting an error that it's not defined then either the field module isn't being loaded for whatever context you're receiving the error in, or the field.module file has been corrupted/changed.

Try getting the field.module file from a fresh copy of Drupal and replacing it on your site, that might fix the problem. If not, grep your sites/all/modules folder for the string FIELD_BEHAVIOR_DEFAULT. That should help you narrow down the modules that use it, and which ones you should try to disable.


What is the difference between base tables and data tables for content entities?

My guess is that you didn't actually set the translatable flag to TRUE. The data_table is only used then, but I guess views gets confused if you have it set but the entity type is not translatable, sounds like a bug in views but it also doesn't make sense to define the table and not have your entity type translatable.

The difference of those two tables is that it contains a row for each translation of your entity type. For example, {ńode} has just the nid, vid (which is the current revision), type and uuid. All the other fields are in the data table, like the node title, status, changed date, and so on.


First, I would say dont put this logic in a .tpl if you can put it somewhere else, for maintainability.

Second, as with many drupal solutions, there is more than one way and they differ in some aspects.  Let me try a few for you:

Solution A: https://www.drupal.org/project/colorbox  This adds a checkbox to the views field controls that says "Open link in Colorbox", and you use the Output as a Link controls to make this link point to /node/add.  Verify necessary permissions are set.

Solution B: Ctools modal link conversion.  In your calendar view add a nid field and use the 'Rewrite Field' options to replace it's value with your Create anchor tag.  Make sure this tag has the class "ctools-use-modal".  The reason for doing this so early is that links tagged with that class, when passed through the render process, get converted into a modal link.  Since this is on a calendar display, I am guessing that you are wanting people to make events for the calendar, and it would be really cool to have the event creation form pre-populate with the day they clicked?  Look at https://www.drupal.org/project/prepopulate and alter your anchor path to include the token from the date field that is already in your view.  Now the hard part, you will need to write a hook, so you will need a custom module.  I havent tried https://www.drupal.org/node/1312770 but it looks like it can make a skeleton for you.

You will need to implement this:

function hook_views_pre_build(&$view) {
  if ($view->name == [your_view_here]) {
    $current = $view->current_display;
    // Include the CTools tools that we need.
    ctools_include('ajax');
    ctools_include('modal');
    // Add CTools' javascript to the page.
    ctools_modal_add_js();
  }
}

That will make sure the view is processed by ctools looking for modal pop-ups.  I just used this the other month in a slightly more complicated use case, where path in the view is a custom registered callback and anonymous user gets a sign-up form in modal, and logged in user gets the requested resource.  Using what I have explained above, you should have a site where everybody gets the modal.  Make sure you have the appropriate Node Create permissions checked.

Solution C: There is an Overlay module that ships with Drupal 7, has been in there from the begining.  This is less popular than colorbox and ctools, and bit more limited.  Enable the module, give anon user permission to use it, and add "#overlay=" to the beginning of your link path in the view.  I dont recall at the moment if they solved some security issue involved with anonymous access to this module, so I caution against using it.  I am really only including it here as an example of how many solutions are available in drupal.

Good luck, and please do say how this worked for you.


You can only use hook_view() when you are implementing the code for the module that defines a content type.

  Display a node.

  This is a hook used by node modules. It allows a module to define a custom method of displaying its nodes, usually by displaying extra information particular to that node type.

The documentation of hook_view() for Drupal 7 is clearer:

  Display a node.

  This hook is invoked only on the module that defines the node's content type (use hook_node_view() to act on all node views).

If you are writing code in Drupal 6 to alter the content of a content type implemented by another module, you can only use hook_nodeapi('alter'), for which the documentation reports:

  "alter": the $node->content array has been rendered, so the node body or teaser is filtered and now contains HTML. This op should only be used when text substitution, filtering, or other raw text operations are necessary.

As what you are trying to achieve is text substitution, this is the hook you should use.

The equivalent for Drupal 7 is hook_node_view_alter().

  Alter the results of node_view().

  This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

  If the module wishes to act on the rendered HTML of the node rather than the structured content array, it may use this hook to add a #post_render callback. Alternatively, it could also implement hook_preprocess_node(). See drupal_render() and theme() documentation respectively for details.


Drag and drop content on user side in drupal 6

Save the arrangement of blocks using some client side storage (e.g. cookies) when it is changed. After the page is loaded, use JavaScript to recreate the arrangement from the stored information.


You have to install and enable the File Entity (fieldable files) module:

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

7.x-2.12 works flawlessly.


This code should do it:

    <?php foreach ((array)$node->field_image as $item_id => $item) { ?>
      <div id="<?php print $item_id+1?>" class="gallery"><?php print $item['view'] ?>

    <?php } ?>


Why is my theme library load on every page?

In my theme.info.yml i add under libraries "theme/hover3d".

That's why it's loaded on every page. libraries in the theme info file is:

  A list of libraries (which can contain both CSS and JavaScript assets) to add to all pages where the theme is active.

To add it contextually, attach it to a relevant render array. For example:

function MYTHEME_preprocess_node(&$variables) {
  // Library will only be loaded when a node is rendered on the page.
  $variables['#attached']['library'][] = 'theme/hover3d';
}

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme for more information.


I had forgotten about the table-cell and table-row diplay properties. Despite the fact that CSS is off topic, the way to do it given Drupal's  form class structure is:

.form-no-label {
    display: table-cell;
}
label {
    display: table-cell;
}
.container-inline {
    display: table-cell;
}
.label {
    display: table-cell;
}
.form-item {
    display: table-row;
}


How to programmatically reset user password

Just use the setPassword() method to update the user's password:

// Get user storage object.
$user_storage = \Drupal::entityManager()->getStorage('user');

// Load user by their user ID
$user = $user_storage->load($id);

// Set the new password
$user->setPassword('User123@');

// Save the user
$user->save();

This will take care of all the hashing for you and will trigger all the appropriate hooks for saving a user.


How to switch existing file field from public to private?

I know this was asked a while ago, but posting this in case anyone else needs it:

https://gist.github.com/thsutton/6878688

This gist takes the steps from this comment on d.o. and makes it into a simple script: https://drupal.org/node/1806220#comment-6960906

Here's the steps from the linked comment:

backup your site and db
copy the table for your field (and the revisions table for the field) to make a backup (in my case i copied: field_data_field_attachments to field_data_field_attachments_bk)
empty table field_data_field_attachments
go to drupal and the option to change the file system should be available, so change it
copy all data from field_data_field_attachments_bk back to field_data_field_attachments
go to drupal, select your content type, select your file field, in file path settings select retroactive update
click save and it will move all your files to the right place in file system and update your db to the new path

I ran through the script and field updates on several fields myself recently and it just works.


How can I save parts of the URL to the database when a certain page is viewed?

Marketing creates the page with a URL that contains a variable
representing the user. User gets an email and clicks on button that
goes to page. When they get to the page the module is triggered to
collect the variable data from the URL. The module will then save that
value to a DB.

Use template_preprocess_node
Have the URL in the e-mail formatted like this:
example.com/node/1?param1=value1?param2=value2

If it's required that the user must be logged in
example.com/user/login?destination=node/1?param1=value1?param2=value2

I used /node/1 as an example, but you can use its url alias instead if it has one.
Then in your mymodule.module file
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
   if ($node->type == 'article') { // checks its Article Content Type
     $params = drupal_get_query_parameters();
     if (!empty($params)) {
       // do more magic to get each param value on its own
       // save to the DB
     }
   }
}


Wysiwyg with ckeditor and custom configuration

Take a look at this Denver DrupalCon2012 Talk: What-you-see-not-always-what-you-get-it-can-be

Google Docs here


add billing information in Drupal Commerce Programatically

To add billing information in checkout process first we have to create a profile object and assign it to the order. This code works for me

For adding new profile for billing information

function commerce_services_bill_ship_create($data, $flatten_fields) {
$status; $message;
$orderId; $uid;

$orderId =$data["orderId"];
$fullname = $data['fullname'];
$city = $data["city"];
$address = $data["address"];

//load order that you want to add billing information
$order = commerce_cart_order_load($uid);

// We'll assume that the current user will be the customer of our order
global $user;

$profile = commerce_customer_profile_new('billing', $user->uid);
$profile->commerce_customer_address = array(LANGUAGE_NONE => array(0 => addressfield_default_values()));

//for updating existing profile, uncomment the line below and comment commerce_customer_profile_new()
//$profile = commerce_customer_profile_load($profile_id); //

//add fullname
$profile -> commerce_customer_address['und'][0]['name_line'] = $fullname;

//add address
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;

//add city
$profile->commerce_customer_address['und'][0]['locality'] = $city;

// You sould pass the entire $profile object as parameter.
commerce_customer_profile_save($profile);

//assign profile_id to the order
$order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile->profile_id;

try{
    // Now you can save the order.
    commerce_order_save($order);
    $status = 1;
    $message = "order update successfully.";
}catch(Exception $ex){
    $status = 0;
    $message = "order can't update successfully.";
}

$reply= (array('status' => $status,'message' => $message));

return $reply;
}

Reference site - Programatically Create Order with Customer Profile
, Creating Customer Profiles Programmatically


How to query the last 5 nodes of multiple content types?

I think the only thing you need is alter the second line of your EntityFieldQuery to this:

->entityCondition('bundle', array('typeA', 'typeB', 'typeC', 'typeD'), 'IN')

Haven't tested this particular though, but you can query multiple content types this way.

Cheers

EDIT: Maybe this can help you more: https://www.drupal.org/node/2048345


Dropdown menu of node titles that are made by a view

I don't know if or how the Superfish module integrates with Menu Views. Off the top of my head I kind of suspect it doesn't...

The simplest solution is to use CSS to hide the view except during the parent's :hover state. You can pick up a simple js to make that function in IE7 and below. There are of course plenty of other, mostly javascript or jQuery-based, solutions.


Next/Previous button for nodes within a book

ok, this can be achieved by overriding of modules\books\book-navigation.tpl file. Copy this file to your Theme and change following:

 <?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?>
      <?php endif; ?>

    <?php endif; ?>

to:

<?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('Back') ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print t('Next'); ?>
      <?php endif; ?>

    <?php endif; ?>


Issues removing text decoration from links in a custom block

For the text-decoration, try to use !important attribute.

For that "doubled text", you need to use text-shadow: none.

If text-decoration still doesn't work, you can try border-bottom: none for that line, too.


how to add form action twig template form

I am assuming you are building this form with Form API and not plain HTML (don't do that). You need to add the attributes to ensure you get everything you need.

<form{{ attributes }}>

See the main form.html.twig template: https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21form.html.twig/8.4.x

In general, I advise you to theme the form elements themselves instead of stitch the form together like this, because you will likely be missing the things in the form Drupal adds behind the scenes to a rendered form.


After further inspection, I found in the view that "Rewrite the output of this field" was on to include the sku.


How to get the parent entity title inside image.html.twig

The cleanest solution that I could find is to get node object in image-formatter.html.twig which is a wrapper to image.html.twig.

Add THEMENAME_preprocess_image_formatter to your THEMENAME.theme

function THEMENAME_preprocess_image_formatter(&$variables) {
  $variables["node"] = $variables['item']->getEntity();
}

Copy core/themes/classy/templates/field/image-formatter.html.twig into your THEMENAME/templates directory.

Now you can get the node title in this twig file using {{node.getTitle()}} or {{node.label()}}

The twig file might look like this

Node title: {{node.getTitle()}}

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

Don't forget to rebuild cache (clear cache) for the changed hooks/twig files to be seen by your Drupal installation.

Alternatively if you want to just change the alt and title attributes of your image based on the node title here is one way to do it (covers question in the comments)

function THEMENAME_preprocess_image_formatter(&$variables) {
  $node = $variables['item']->getEntity();
  $variables["image"]["#alt"] = $node->label();
  $variables["image"]["#title"] = $node->label();
}


Can I change the location of the cached Twig templates?

Yes you can, put this in settings.php or any file loaded by it like settings.local.php:

  $settings['php_storage']['twig']['directory'] = '/path/to/tmp/folder';
  $settings['php_storage']['twig']['secret'] = $settings['hash_salt'];

Note that the directoy must exist already.


How do you render a set of checkboxes without using drupal_get_form()?

...I just need a few <input type="checkbox"> elements.

Just render it as plain html, and if you absolutely want a render array, then create your own theme function for it.

$variables['content']['checkboxes'] = array(
    '#markup' => '
 Please select every sport that you play.
 Soccer: <input type="checkbox" name="sports" value="soccer">
 Football: <input type="checkbox" name="sports" value="football">
 Baseball: <input type="checkbox" name="sports" value="baseball">
 Basketball: <input type="checkbox" name="sports" value="basketball">

'
);


You can use module Commerce Currency Settings for formatting of currency.


how do i set the first page of my site in drupal 6?

Have you been to /admin/settings/site-information and set the homepage from there? At the bottom put the node address into Default Front Page field, something like node/1 (or whatever node number you want the front page to be)


My guess is that you are running into EOL marker differences. That boils down to editor settings, and NetBeans copnfiguration help would be best at a sister side,  If the code works, then don't worry about it.

As a side note, I don't recall running into any situations that prevented me from using the normal Google Analytics module.  Recent versions let you adjust the code, so you should be able to match up with any tracking code you have.  In addition, you can configure it to ignore admins, track downloads, and do a lot more.


How to add rows to a form table with AJAX Callback in Drupal 8

Details and Warnings

  Changes to the form must only be made in the form builder function
  (ajax_example_autocheckboxes() in the example here), or validation
  will fail. The callback function must not alter the form or any other
  state.

Reference: https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7

It's for D7, but the concept how Ajax works has not changed:

  The Big Idea

  The big idea here is that:

  Your form gets rebuilt when you manipulate a form element (e.g. select, submit etc.)
  Your form builder function builds it a different way based on that input ($form_state)
  Your #ajax settings and your callback function arrange to deliver all or a part of the newly rebuilt form to replace or otherwise
  enhance some part of the page.


Force redirect back to password form until password got set after one-time-login

You should be able to use hook_init to check for your custom $_SESSION variable (along with other conditions), and then leverage drupal_goto() to send the user back to the password change page.

Rough example:

function MODULE_NAME_init() {
  // Check that the session key exists.
  if (!empty($_SESSION['my_special_session_key'])) {
    // Check to verify the path the user is currently visiting is not the
    // password change form, or related path.
    // This needs to be customized according to your needs.
    if (arg(0) != 'user' || arg(1) != $GLOBALS['user']->uid || arg(2) != 'edit') {
      drupal_goto("user/{$GLOBALS['user']->uid}/edit");
    }
  }
}

You'll also need to unset that $_SESSION key after the user successfully changes their password. You'll likely want to do this using another hook related to the password change form.

Usinghook_form_FORM_ID_alter to add a custom submit callback to the form is a reasonable choice.

Here is an example that adds the submit callback to the user's edit form if the $_SESSION key exists.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state) {
  if (!empty($_SESSION['my_special_session_key'])) {
    $form['#submit'][] = '_MODULE_NAME_unset_session_key';
  }
}

/**
 * Custom callback for removing the special session key.
 */
function _MODULE_NAME_unset_session_key() {
  unset($_SESSION['my_special_session_key']);
}

Hope this helps.


Why isn't my managed file getting saved?

The managed_file element handles moving the file into place and adding a file record, you don't need to save it yourself. The file module does all this in a validation function which makes the fid available in the submit handler.

So, for example, if your file element is defined with $form['file_id'] = ..., you can change your code to something like the following

$fid = $form_state['values']['file_id'];
$file = file_load($fid);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'my_module', 'node', $some_nid);


Display summary of entered field values and permit user to cancel submission

There is a feature request for a "summary" component for Webform in the Webform module issue queue here: http://drupal.org/node/435232, but there isn't any movement yet on actually making a built-in summary component in the core project.

In that issue, dealancer notes that he has already added his code to the http://drupal.org/project/webform_bonus project, which allows you to add a summary component directly to your form in the same way you would add a textfield or any other component type. Install that module and add a summary field to your form, selecting which fields you would like to include in the summary. If you would like it on its own page, make sure to add a pagebreak component first.


How do I limit taxonomy by content type?

You would also join in the node table (on term_node.nid = node.nid) and add node.type to the WHERE clause.

Do note there are several problems with your above code. First and foremost, as mariomc asks, any special reason why you're doing this manually instead of through Views?

Second, if you do have a good reason to do the querying yourself, do look into using placeholders with db_query. Its primary purpose is preventing SQL injection problems (strictly speaking, if the variables really are hard coded like this, there is really no danger, but consider what happens when you decide to feed them in from somewhere else at a later date).

All in all, code that would both answer your question and is more "correct" would be (untested):

<?php

$vid = 15; //vocabulary id
$num_term = 20; //limit maximum terms
$type = 'story'; // Your type

$query = "SELECT td.tid AS tid, name, COUNT( nid ) AS count
  FROM {term_data} AS td
  LEFT JOIN {term_node} AS tn ON td.tid = tn.tid
  LEFT JOIN {node} AS n ON tn.nid = n.nid
  WHERE td.vid=%d AND n.type = '%s'
  GROUP BY tn.tid ORDER BY name ASC LIMIT %d";

$result = db_query($query, $vid, $type, $num_term);

// ...
?>


How do I allow iframe embeds to a particular domain?

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

you can set security level and also set exceptions


Migrate doesn't update destination files if source files have changed content

It turns out that files are actually updated. So there's nothing to edit in my migration code.

Problem is that a flush on image styles is required.

I was triggering flush manually, but I could not see updated images in webpages.

Flushing was not working due to file permissions on resized images, so I still see the old "styled" images.


In a custom module how do I get all the nodes of a certain type?

You use db_query() to get the node IDs for all the nodes of a content type, and then node_load() to load the single nodes one by one.

$query = db_query("SELECT nid FROM {node} WHERE type = '%s'", $type);

while ($result = db_fetch_object($query)) {
  $node = node_load($result->nid);
  // Use $node or store it in an array;
}

As the query is fetching a single field, db_fetch_object() could probably be replaced with db_result(); I have never checked if it works for all the database engines, and I didn't find a Drupal core module that uses db_result() in a loop (e.g., while ($nid = db_result($query))).

The reason you should use node_load() is that:

It allows the module that define the content type for the loaded node, and third-party modules to add extra fields in the node object. This is because the function uses the following code:

// Call the node specific callback (if any) and piggy-back the
// results to the node or overwrite some values.
if ($extra = node_invoke($node, 'load')) {
  foreach ($extra as $key => $value) {
    $node->$key = $value;
  }
}

if ($extra = node_invoke_nodeapi($node, 'load')) {
  foreach ($extra as $key => $value) {
    $node->$key = $value;
  }
}

It loads the correct node revision, when revisions are enabled for the content type.
It caches the result; if two calls to the functions are requiring the same node, the function simply return the previous result. This happens if the call to the function doesn't require a specific revision of the module, and if the last parameter passed to the function ($reset) is not equal to TRUE.

If you are interested to get only the node ID, then the call to db_query() is sufficient.

In Drupal 7, there is a class that allows to load multiple entities (Drupal 7 nodes are entities) that match some criteria in once: EntityFieldQuery.


Yes, you need to update MariaDB. Just "cd" to your ddev project directory in the terminal and issue the following commands:

ddev config --mariadb-version=10.4

and then

ddev restart

That's it! Good luck:)


The purpose of the clean_id filter isn't providing a unique ID, but removing from the string used as HTML ID the characters that aren't allowed. Basing on 6.2 SGML basic types HTML IDs can only contain letters, digits, hyphens, underscores, and colons.
Html::getUniqueId() itself uses Html::getId().
// If this is an Ajax request, then content returned by this page request
// will be merged with content already on the base page. The HTML IDs must
// be unique for the fully merged content. Therefore use unique IDs.
if (static::$isAjax) {
  return static::getId($id) . '--' . Crypt::randomBytesBase64(8);
}

// @todo Remove all that code once we switch over to random IDs only,
// see https://www.drupal.org/node/1090592.
if (!isset(static::$seenIdsInit)) {
  static::$seenIdsInit = [];
}
if (!isset(static::$seenIds)) {
  static::$seenIds = static::$seenIdsInit;
}
$id = static::getId($id);

The documentation page for Html::getId() says it should be used only when the ID doesn't need to be unique.
For the cases where the ID needs to be unique, Drupal core modules set a variable passed to the template file, which is what's done in template_preprocess_pager(), template_preprocess_block(), or template_preprocess_views_view_table(), for example.
variables['heading_id'] = Html::getUniqueId('pagination-heading');

// Create a valid HTML ID and make sure it is unique.
if (!empty($variables['elements']['#id'])) {
  $variables['attributes']['id'] = Html::getUniqueId('block-' . $variables['elements']['#id']);
}

// Improves accessibility of complex tables.
$variables['header'][$field]['attributes']['id'] = Html::getUniqueId('view-' . $field . '-table-column');

Since Drupal core doesn't have a Twig filter that returns a unique ID, that is the only way to obtain one: Set a variable in a preprocess function used for the template file with the value returned from Html::getUniqueId(), and use that variable where the template file needs a unique ID.


How can pass a data of a node's field to entityform field

You can use hook_form_alter in a custom module and pass the node field value to the value of the form item eg :

<?php
  function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id){
    // dpm($form);
    $node = node_load(arg(1));
    $form['field_code']['#value'] = $node->my_field[LANGUAGE_NONE][0]['value'];
  }
?>

Things you need to know are:

The ID of the entity form for FORM_ID, you can get this using Get form ID module.

What the field you are populating is ? you can install Devel module then uncomment the line in the above code to inspect the form.

Where within the node object the field with the data is ? If Devel is installed you can navigate to the node and click on the Devel tab and explore the node there.

If you are using hidden fields then ['#value'] is ok but if it is a textfield then you should use ['#default_value'].

Also, this is presuming that the form is in a block on the node page, other wise node_load(arg(1)); will node work.


You can do a little tweak.

After you get the only date in YYYY-MM-DD string format, concate 00:00:00 as time to the string. then you can get unix time format by using function strtotime() that takes a string date format and returns an integer of time format (unix).

Hopefully this helps you getting the correct duration.


Setting automatically created taxonomy terms using rules module

Simply add a autocomplete taxonomy field to the content type and when node saves, rule to set data into this field. Taxonomy module will then create the new term if it does not exist.


Get proper block title from block object

If you were using hook_preprocess_block() it would be much easier to get the title, you would simply load the block by its id and get the label from the returned block object like this:

function hook_preprocess_block(&$variables) {
  $variables['new_title'] = \Drupal\block\Entity\Block::load($variables['elements']['#id'])->label();
}


Tracking number of attempts via Form API

Just use a variable insider $form_state.

In validate function

if ($validation_failed) {
  $form_state['error_count']++
  $form_state['cache'] = TRUE;
}

Then, in your form function just check $form_state['error_count'].

$form_state will be persistent between page petitions while validation fails thanks to $form_state['cache'].

You can also check for errors using form_get_errors().


Ajax callback of select form field not triggered when changed by javascript, only when changed manually

try to specify the event, like

$form['children']['number_children'] = array(
  '#title' => t('Počet detí'),
  '#type' => 'select',
  '#options' => range(0, 15),
  '#default_value' => $number_children,
  '#ajax' => array(
    'callback' => 'ajax_callback_registration_children',
    'wrapper' => 'children-div',
    'method' => 'replace',
    'effect' => 'fade',
    'event' => 'change',
  ),
);

this should be sufficent .. (but select uses change already as default event ..)

other things to try could be

add a custom event, like:

'event' => 'custom_change',

jQuery('select').trigger('custom_change');

See How to trigger Ajax forms machinery

or invoke the callback yourself:

Drupal.ajax['#ID'].eventResponse('#ID');


The reason for your problem is that page manager has already defined a menu entry for that path. Just as well, because the menu item you have created would cause an infinite chain of redirection. You would need to change the path for your panels page to be something different in order for the redirection to work.

But you can simply remove your menu entry altogether and use page manager to define the menu item for the page as a tab under Settings -> Menu. You shouldn't need any extra code to do that.


Fatal error: Class 'RulesI18nStringController' not found in entity.i18n.inc on line 31

You have $update_free_access variable in your settings.php file. Set it to:

$update_free_access = TRUE;

You will be able to run update.php without login. Don't forget to turn it back to FALSE when done - if left TRUE, it can open your site to DoS attacks.


view's query "was not run" while getting results

If your views having contextual filter using relationship, then you should check if correct relationship set in contextual filter.


Custom Twig Template for Custom Content Type

If you want to load the template from the module folder you are in the right hook, but you need to use the correct base hook. This means you have to start the template name with the base hook and a double underscore node__ and declare the base hook in theme_hook(), see Store template in module.

hook_theme():

function myModule_theme($existing, $type, $theme, $path) {

return [
    'node__faculty_bio' => [
      'base hook' => 'node',
    ]
  ];
}

The Twig template path and name would then be mymodule/templates/node--faculty-bio.html.twig.


Redirect example.com to example.com/node

Do you have any redirect module enabled? Might be because of that maybe Global redirect or something.

Otherwise you can redirect your homepage to pick up example.com/node by adding the path here: Default front page: URL(admin/config/system/site-information).


You can follow these steps to achieve what you want.

Add a field in your views Content:Nid.
Rearrange the field & place above added field at the top of yours (Products referenced by field_product) Field: Images.
Edit (Products referenced by field_product) Field: Images & set Link image to Nothing.
Click on Rewrite results & check Output this field as a link.
Paste node/[nid] token in Link path.
Save it & you are done :)


Reference three types of entities and render them in one list

If I understand your question correctly, you currently have three different reference fields (one for each entity type to reference to) that each can have multiple values. And you want to combine the value of these three fields in groups, so the first values are displayed as a set, the second values are displayed as a set, etc.

I think the Paragraphs module is what you are looking for. You can create a paragraph that contains the three reference fields, in your case allowing only one value per field. And on your node (type) you add a multi-value paragraphs field, allowing your editor to provide groups of references which are rendered together.


removing the 'title' field from custom content types

You are looking for Exclude Node Title module

  This module handles a very simple functionality, decide whatever to
  exclude a node title from full node page or node teasers. It provides
  a checkbox on node-edit pages for easier exclusion, or you can use the
  admin page to manually enter a list of node id's to exclude title.

Also provides the option to hide all titles of a certain Content type.


This is a possible solution using javascript that shows how to select the child checkboxes with JQuery.


Any modules for editing files in the browser?

Well, elFinder, and this page may help you. At least elFinder supports inline file diting. Good luck!


logo_path seems to only be set if you override the theme's default logo via its theme settings. To get the default logo, use theme_get_setting('logo').


Cancelling user account set draft pages to published

Just did a test with the steps you provided.  I tried with just 1 node unpublished and cancelled the user and the node was assigned to the anonymous user BUT the node stayed unpublished.  I don't see any reason why the result would be any different if I tried with 10 nodes.

I believe a contrib/custom module is at fault.  See if you have any modules that deal with publishing/unpublishing content you have to disable them and test if the problem is gone.

If the above does not help I would try to disable all modules one by one and testing to see if the problem is gone on each step.  Once you find the problematic module you can post the results in the issue queue and you might also discover a patch resolving the issue.

You can also post a list of your enabled modules and someone might be able to spot a module that could be a potential candidate to be causing this behaviour.


"Locking" a node after a certain period of time

You could do something like this:

/**
 * Implements hook_menu_alter
 */
function MY_MODULE_menu_alter(&$items){
  $items['node/%node/edit']['access callback'] = 'MY_MODULE_check_node_access';
}

/**
 * Custom menu access callback for node/%node/edit
 */
function MY_MODULE_check_node_access($op, $node){
  global $user;
  // Note $op and $node are passed in default node_menu access arguments
  // Allow bypass by users with administer nodes permission
  if (($op == 'update') && (!user_access('administer nodes'))) {
    // Allow edit access to node author if within time limit
    if ($user->uid == $node->uid) {
      $limit = variable_get('node_edit_limit', (15 * 60));
      if ((REQUEST_TIME - $node->created) > $limit) {
        drupal_set_message(t('Edit time limit exceeded'));
        return FALSE;
      } else {
        return TRUE;
      }
    }
  }
  // Fallback to regular node_access checks
  return node_access($op, $node);
}


For future reference, I think this recipe is pretty awsome: http://www.drupalgardens.com/documentation/taxonomy/views


you could print the login block programmatically in (the top of ..) your page.tpl.php like

<?php
 $block = module_invoke('user', 'block_view', 'login');
 print render($block['content']);
?>

clear caches through drush if possible

drush cc all


Entity reference, display custom field, not the title

Create a view and set the filter "Content: Type", to "one of"- Event and Organization. Pull all the fields you want to be displayed and publish the view in a page or as a block on any page. You can further customize the html of said created view per the instructions here :)


You can make use of the arrange fields module.

  This module lets you drag-and-drop the fields of any CCK content type,
  Webform, or almost any other form in Drupal into the positions you
  would like for editing. This makes it super simple to have forms with
  inline fields, which you can change at any point. Tab indexing is also
  updated, so no matter how you arrange the fields, the users can still
  tab through them easily. And, you can now add arbitrary bits of HTML
  markup-- labels, images, HR's, etc.


After much frustration I have resolved the issue and will post the answer in case it is of use.

Cron seems to not always have access to the same PATH information as when a normal user - or even root - runs a drush command in a command line.

The solution came from comment #7 in this drush thread.

You need the path to drush. You can find this with the command:

which drush

In my case it was /usr/local/bin/drush

Then add the path info to the top of the shell script.

export PATH=$PATH:/usr/local/bin

And then it worked perfectly.

Additionally, it appears if your local mail is not set up correctly cron discards output from scripts which is why the drush: command not found error was not turning up in logs. To make sure you get logs from cron configure it for local mail. See this post.


Get node fields in Rules action programatically

Just in case someone had the same approach as mine. Here is the solution from Drupal.org community.


For home page:

Clone your page.tpl.php as page-front.tpl.php in order to customized work for your home page.

Listing nodes in accordion:
* Use views to build a list for you
* User Views Accordion to format them in accordion

jqDock menu:
jqDock menu can be build using your content templates. But it should be clear what type of data coming from your database.

For custom data you will have to build your own module to fetch data.


Code in URLs despite clean URLs turned on

According to this posting on StackOwerflow and this one on Drupal Answers, these appear if there is Javascript in place to add "AddThis" tracking to the website.  They do no harm, and if it's not your site, you should leave them alone.

(Note that this has nothing to do with clean URLs in Drupal.  Drupal's clean URLs changes things like example.com/?q=node/123 into  example.com/node/123.  It does nothing with hashmarks added to URLs.)


How can I assign a database for each user?

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

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.
Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.

Resources

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


can you put views field values into a global token?

I do not believe this is possible if paragraphs module does not provide this token itself. The way to do it would be to create your own token. Even with this it may be tricky to figure out that information.

To create your own token you will need to look into the hook_token_* items such as hook_token_info.

It sounds like to me your best bet would be attempting to hook into the views pre processing and change the value that way.


URL aliases problem when assigning aliases for custom pages

You are doing it in reverse order. This order is generally followed.
Create a page.
Note down the node number (ex : 7)
Then create a file corresponding to that like page-node-7.tpl.php
You should not assign node/11 as alias as these are considered as internal paths.
You can give anyother name which mostly suits the page contents.


How to import custom content type in XML?

In my case an error "There are no new nodes" was caused by a wrong xml context in the xpath parser setting.

In your case should be: //article and not only: article.

This is because //article in xpath is equivalent to say "all the article tags".
If you put only article in the xpath, context feeds does not import anything.


You can use either of these ecommerce solutions:

Drupal Commerce

  Drupal Commerce is used to build eCommerce websites and applications
  of all sizes. At its core it is lean and mean, enforcing strict
  development standards and leveraging the greatest features of Drupal 7
  and major modules like Views and Rules for maximum flexibility.

or Ubercart.

  Ubercart is the most popular Drupal E-Commerce platform for your
  website. It implements everything you need to start selling products
  online. Web Developers from all skill ranges can use it to support a
  variety of E-Commerce industries-- including physical goods, digital
  downloads, or even subscription based billing services. Ubercart can
  do it all!


check like this

{% if view_mode == "teaser" %}

{% elseif view_mode == "full" %}
  //something else
{% endif %}


Apply formatting to tables generated by tablefield module

I haven't installed the module, but from the code it looks like there's an option in the field settings called "Table cell processing" in which you can allow the user to select what Input Format they want. This makes use of Drupal's text formats (Admin > Configuration > Content Authoring > Text formats). You could allow them to use HTML within the cell, or install some alternate Text Format module such as BBCode.


How do I add custom validations to Webform?

Make use of the validate function in hook_form_alter:

 if ($form_id == 'webform_client_form_14') {
    $form['#validate'][] = 'cork_creation_validate_custom';
 }

function cork_creation_validate_custom($form, &$form_state) {
  if (!preg_match('/^[A-Za-z]+$/', $form_state['values']['submitted']['name'])) {
            // $form['submitted'][$key]['#attributes']['class'] = 'error';
            form_set_error('name', t('Please enter alphabets only for Name.'));
 }

  }


Why is my custom module not being recognised?

Take a look at Creating Drupal 7.x modules

Writing module .info files (Drupal 7.x)

Example
The following is a sample .info file:

name = Really Neat Widget
description = Provides a really neat widget for your site's sidebar.
core = 7.x
package = Views
dependencies[] = views
dependencies[] = panels
files[] = example.test
configure = admin/config/content/example


How can I track statistics on how often a hook/error message is triggered?

I don't think you'll get 'statistics' as such without some coding yourself, I've never seen a module that does that sort of thing (but hey it's Drupal so there probably is one somewhere).

Failing that I think your best bet would be to use the the watchdog() function, combined with enabling the dblog module on your site. You can use it like so:

if (empty($message->thread_id) && strlen($message->body) < 200 ) {
  form_set_error('[body][value]', t('My custom message.'));

  global $user;
  watchdog('mymodule', 'My custom message for user @username', array('@username' => $user->name));
}

Every time that if statement is entered you'll get a message on the 'Recent log messages' page, where you can even filter by entries for your own module, giving you a basic idea of what's happening, when, and for whom.


Additional form validation only after passing default validation

I'm pretty sure you have to re-arrange the order of the validators, and inject yours basically in the middle instead of just adding it at the end.

From user.module, $form['#validate'] = user_login_default_validators(); or:

/**
 * Set up a series for validators which check for blocked/denied users,
 * then authenticate against local database, then return an error if
 * authentication fails. Distributed authentication modules are welcome
 * to use hook_form_alter() to change this series in order to
 * authenticate against their user database instead of the local users
 * table.
 *
 * We use three validators instead of one since external authentication
 * modules usually only need to alter the second validator.
 *
 * @see user_login_name_validate()
 * @see user_login_authenticate_validate()
 * @see user_login_final_validate()
 * @return array
 *   A simple list of validate functions.
 */
function user_login_default_validators() {
  return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
}

and

/**
 * A validate handler on the login form. Check supplied username/password
 * against local users table. If successful, sets the global $user object.
 */
function user_login_authenticate_validate($form, &$form_state) {
  user_authenticate($form_state['values']);
}

so I'd do something like:

$form['#validate'] = array('user_login_name_validate', 'mbrusers_infusionConnect_validate', 'user_login_authenticate_validate', 'user_login_final_validate');

instead of if <Default form validation passed> so that your validation function is called before the normal/usual second validator.


Caching Drupal 7 using boost module and Varnish, yet still getting a "MISS"(

Pay attention to the Cache-Control header returned from Drupal:

Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0

If Cache-Control is set to no-cache, Varnish will respect it by default. Either you must force caching from within Varnish in vcl_fetch or (much better), make Drupal deliver the proper header (Cache-Control: public, max-age=X). The simplest way to achieve the latter is to enable "Cache pages for anonymous users" in Administration » Configuration » Development and also set "Expiration of cached pages". You can hard-code those settings using:

$conf['cache'] = 1;
$conf['page_cache_maximum_age'] = 3600; // 1h

You also may force the Cache-Control header by adding it explicitely using a custom module by implementing hook_exit. A reasonable save implementation looks something like this:

/**
 * Implements hook_exit().
 *
 * @see drupal_serve_page_from_cache()
 */
function MYMODULE_exit($destination = NULL) {
  // If the client sent a session cookie, a cached copy will only be served
  // to that one particular client due to Vary: Cookie. Thus, do not set
  // max-age > 0, allowing the page to be cached by external proxies, when a
  // session cookie is present unless the Vary header has been replaced or
  // unset in hook_boot().
  $vary_header = drupal_get_http_header('vary');
  $max_age = !isset($_COOKIE[session_name()]) || isset($vary_header) ? variable_get('page_cache_maximum_age', 0) : 0;

  if (drupal_page_is_cacheable() && $max_age && $destination == NULL && !headers_sent()) {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . $max_age);
  }
}

Also note that due to the fact that boost will also add a Cache-Control header, you still need to introduce some VCL logic in vcl_fetch. The following fragment will force Varnish to still store pages in the cache, even when they were delivered using boost with Cache-Control no-cache:

sub vcl_fetch {
  if (beresp.http.X-Cached-By ~ "Boost") {
    set beresp.ttl = 1 h;
  }
}


On the page level forms are rendered and so you cannot get its elements. You will need to implement a hook_theme function in template.php file where you define the path of the template file and also implement preprocess function if required.

You can see a detailed explaination here .. Theming Forms with Template file


Update drupal modules without updating core in one drush command

You can use the --no-core flag.

drush upc --no-core

https://drushcommands.com/drush-8x/pm/pm-updatecode/


This is not good approach for Drupal.
Try to make the query in VIEWS UI, after that you have 2 options:

In the view add this option Show:Content | Teaser.
Create tpl file for that specific node (node--news.tpl.php), add if statement for the DISPLAY(view) MODE of the content type (full or teaser).
In the correct display mode you have all node fields that are enabled in the content "Manage display" tab (as admin structure->content type->news->manage display)
and use " print render($content['field_news_link']) ".
In the view add this option Show:Fields. Rewrite the option of the field "Rewrite results"->"Rewrite the output of this field" in the view and add there html + token of the field.


How can I assign a View Page on a Domain?

Domain Views

This module should provide that integration. It is supposed to link the domain access module and views together.


How to show language switcher only on home page

Set block visibility to only show on <front>


How to return a View's content in search results?

There is the Search by Page module that allows this (and much more). Some details from its project page:

This module is an enhancement to the core Drupal search module, which adds a new tab to the core Search page or can also be used in stand-alone mode. The differences between Search by Page and the existing tabs in the core Search module lie in what is indexed for searching and how it is indexed:

Search by Page indexes the content of your pages as rendered by your theme (Search indexes the default rendering you would have from an unmodified theme)
Search by Page allows you to omit content from indexing (such as "database table" node types that should never be viewed as stand-alone content)
Search by Page allows you to index non-Node pages, including user profiles, file attachments, and Views
Search by Page is language-aware, so it only shows you results in the current language.
Search by Page has multiple search "environments", so you can have different search pages/blocks to search different things.

Maybe you can use that or look how they index the views pages.


Alter validation when using inline entity form

At last I got it to work. Here is the final code where the error was that I did not fully understand how to use form_set_error to point at the field I wanted to validate.

function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)
{
  $entity_form['#element_validate'] = array('mymodule_inline_entity_form_entity_form_validate');
}

function mymodule_inline_entity_form_entity_form_validate(&$entity_form, &$form_state)
{
  form_set_error('field_bucket_list][und][form][field_price', '!Validate');
  inline_entity_form_entity_form_validate($entity_form, $form_state);
}

The field I wanted to validate is field_price and is located as values->field_bucket_list->und->form->field_price in $form_state, which I got from using Devel.


Could be a caching issue within the browser, Drupal or both. For the browser set cache headers in the response, see https://drupal.stackexchange.com/a/278703/47547.

For Drupal caching add a cache context user.roles:

$response->getCacheableMetadata()->addCacheContexts(['user.roles']);

Furthermore it is recommended to execute a redirect event subscriber only on a master request, this helps to prevent redirect loops:

public function checkFrontRedirection(GetResponseEvent $event) {
  if (!$event->isMasterRequest()) {
    return;
  }
  ...
}


If you want to pass variables to a form you can. See this similar post.

Just add $vars as second argument.

drupal_get_form('new_form', $vars);

and...

function new_form($form, &$form_state, $vars) {

If you are trying to pass the user object to user_profile_form you can do it like so:

global $user;
$form_state = array();
$form_id = 'user_profile_form';
$args = array($user);
$form_state['build_info']['args'] = $args;
form_load_include($form_state, 'inc', 'user', 'user.pages');
print render(drupal_build_form($form_id, $form_state));

If you really want to load the user_profile_form inside another form (?) as suggested in your comment, you can do the snippet above but not render the form, just load it into an a variable and extract vars from it.

$loaded_profile_form_with_user = drupal_build_form($form_id, $form_state);


Creat new menu items link in menu like create new Content Type does

You do not need to use php code just to create a menu with menu links. You can do it with Drupal Core itself.

See below detailed tutorials that may help you.

How to create a menu and add links to it in Drupal 7

Advanced Drupal 7 menu settings, how to create parent child menu links

Create Drop Down Menus in Drupal 7 Using Nice Menus module

If you want to do it specifically using Custom Code then your callback function should call drupal_goto with link as an argument.


I feel like there is a better way but I just quickly created a custom token.

<?php

/**
 * @file
 * Node custom functionality.
 */

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_token_info().
 */
function my_custom_module_token_info() {
  $type = [
    'name' => t('My Custom'),
    'description' => t('My Custom Tokens.'),
    'needs-data' => 'node',
  ];

  $node['body_first_media_image_url'] = [
    'name' => t("Body First Media Image Url"),
    'description' => t("Body's first media image url."),
  ];

  return [
    'types' => ['node' => $type],
    'tokens' => ['node' => $node],
  ];
}

/**
 * Implements hook_tokens().
 */
function my_custom_module_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'node' && !empty($data['node'])) {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        // The first media item embedded in body.
        case 'body_first_media_image_url':
          $dom = new DOMDocument();
          @$dom->loadHTML($node->body->value);
          $embedEntities = $dom->getElementsByTagName('drupal-entity');
          if ($embedEntities->length > 0) {
            $uuid = $embedEntities->item(0)->getAttribute('data-entity-uuid');
            $media = \Drupal::entityManager()->loadEntityByUuid('media', $uuid);
            $url = ImageStyle::load('extra_large')->buildUrl($media->image[0]->entity->uri->value);
            $replacements[$original] = $url;
          }
          break;
      }
    }

  }

  return $replacements;
}


Using attachFileToField in a Functional test doesn't allow entering the alt text for an image

Ah, it looks like this might do it:
    $page->fillField('field_image[0][alt]', 'Image alt text EN');
    $page->pressButton('Upload');
    // This reloads the page and the alt text field is now present.


Using "Security Review" gives file permission errors, how to fix them?

If your webserver user is the same as your account user that you use to login and update the files, then the files should be 440 and folders 550. However, this will make it hard to edit or update the code of the site as you will have to change the permissions back to 755/644 before doing the update.

Note, also, that using anything other than 0 as the final digit in the three is likely the wrong value on a shared server where you do not know/trust every user of the server.

The security review test is about "defense in depth" that prevents a poorly coded file-upload tool from becoming a way to overwrite executable files in Drupal's installation. Sometimes it's OK to ignore some of the reviews from security_review module.


how to unset admin menu links programmatically?

hook_menu_alter is want you are looking for. The usage is exactly the same as your example, just don't forget to clear the caches afterwards.

Cheers!


How to let users register with their Facebook accounts?

Drupal for FaceBook is the one you need.

You can configure application settings and which information you want to get from users, such as email address.

Unlike other suggestions, this module does not rely on third party providers and registrations other than Facebook.


"public" not supported or disabled in libcurl error

public:// is the sites public file system path. You can change it by navigation to admin/config/media/file-system.
    There you can set the public file system path, the default path is sites/default/files.


Is there any way to see the content of the theme registry?

If you want to see the content of the theme registry, you can use _theme_load_registry(). The first argument could be the global $theme for the currently used theme, or one of the objects returned by list_themes().
As the function name is prefixed by an underscore, I would suggest to use it only for debugging purposes. (Theoretically, future Drupal versions could drop those private functions, and that would not probably be taken as API change.)

If you have installed Devel, you can use the following code:

global $theme;

$registry = _theme_load_registry($theme);
dsm($registry);

You can also simply visit the devel/theme/registry page which shows you the theme registry content.


I know, this question is pretty old, but I was looking for a solution by myself.

Maybe someone is looking as well: http://drupal.org/project/vppr
This module provides some new permission settings just for viewing terms which is exactly what I was looking for.


To completely remove the tab from all pages you can use hook_local_tasks_alter().

function mymodule_local_tasks_alter(&$local_tasks) {
  unset($local_tasks['local_task_to_remove']);
}

Where local_task_to_remove is the tab you want to remove.

To have it removed from some pages you could use hook_menu_local_tasks_alter() instead. Something like:

function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  $routes = ['entity.entity_view_display.node.default', ...]; // put other routes in place of '...'
  if (in_array($route_name, $routes)) {
    unset($data['tabs'][0]['local_task_to_remove']);
  }
}


Simply add a Rule upon the event Calculating sell price of Product.  Multiply price by an amount is probably the Rules event you want to be using.


How to reload a node page after Comment submit

You can achieve this using below code:

 Drupal.ajax.prototype.commands.ajaxCommentsAfter = function(ajax, response, status) {
 try {
     location.reload();
 } catch (e) {
     console.log('ajaxComments-After: ' + e.name)
 }

};


In my opinion Features isn't really useful for just one site. It is useful for extracting and packaging functionality to use on multiple sites. Using both at the same time is probably counter productive and prone to errors, as they both try to enforce features via configuration and manage them as well.

If you had a site and wanted to copy/clone the article functionality or product catalog functionality from it to another (different) site, then, yes. You would need Features to do this, because core CMI does not work when you want to take pieces and import to a totally different site.

On the other end of the spectrum, you could ignore the core config management and use Features to do this for your entire site, but it is more for you to manage, and as stated, if you are not extracting it out for use in other sites, it is just busy work.


drupal stores in UTC have to convert this to current time zone

$dt=new \DateTime($changed_date, new \DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('America/New_York'));
$correct_date =  $dt->format('Y-m-d H:i:s');


You don't need to redirect to any page; you can produce the access denied page by calling drupal_access_denied().


How to restrict number of nodes per content type?

Have you tried the Node Limit module?

  The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

You could create a role just for node limit and assign ALL users (including the admin) to that role.


I suppose you use D7?
Do you use the Inline Entity Form module to add a new referenced node of type B? (https://www.drupal.org/project/inline_entity_form). I just tested the following workflow with the Inline Entity Form and Pathauto, and path aliases were successfully created for both nodes (type A and referenced type B):

enable inline_entity_form and pathauto modules
create the Entity Reference field on content type A that references content type B; select 'Inline entity form - Single value' as a widget type
create patterns for both content types in admin/config/search/path/patterns (ex: for A - 'news/[node:title]'; for B - 'people/[node:title]')
create a new node of type A, within it create a node of type B
both nodes should have the correct aliases


Programmatically adding and removing users to a user reference field?

It should be pretty simple:

Load the node you are trying to modify using node_load().
Look for the user referencing field.
Modify the user referencing field.
Save the node using node_save().

I wrote those steps before looking at the example you linked, but after looking at it, it pretty much follows those steps. To answer your question regarding the language: The reason for that is that you are not supposed to hardcode the language key directly. If I am not mistaken, in Drupal 7 this key is something like 'und', but when you use a language on a node this key changes dynamically to something like 'es' or 'en'. If you hardcode the language key, then your code will be translation incompatible. Even if you don't use translation, it is still consider a good Drupal programming practice not to hardcode that language key ;)

If you follow the code that it is given in your link you will be fine.


To create a new subtheme, briefly:

Create a new sub-directory in sites/all/themes with the machine name of the new theme.
Create a new file in the new subdirectory with the machine name and extention .info:

  name = The human name of the new subtheme

  description = ...

  core = 7.x

  base theme = the-machine-name-of-base-theme

  stylesheets[all][] = css/subtheme-new-file-name.css

Regions are not inherited and should explicitly declared again, so copy over from base file theme info file.
Color module file colors.css needs to be copied and added too, if the base theme supports it, otherwise a nasty error occurs.
Favicon is not inherited
Settings are not inherited

All the rest stay at base theme.

More about sub-theming: Creating a sub-theme


How to add a cache context from an existing menu?

Apparently it's:

$breadcrumb->addCacheContexts(['route.menu_active_trails:main']);

and

$breadcrumb->addCacheTags(['config:system.menu.main']);


How can I remove some content types of the admin menu?

While you can add/remove items from the admin menu from this menu
/admin/build/menu-customize/admin
you really shouldn't, that would be customizing what that module does and anytime they release a new version you would have to make your customization again.

The purpose of that module to to simplify, or make shortcuts to, all of the aspects of administering a Drupal site. If there are certain portions of the admin you don't want users to see, use roles to control which of the links are viewable.

Hope this helps!


Adding new rows on a draggable table via jquery

As I can not reproduce your case, this answer just is a suggestion:

look at misc/tabledrag.js:

Drupal.tableDrag.prototype.makeDraggable = function (item) {

So you need re-running necessary javascript after adding new row.

Drupal.attachBehaviors($('#guide-pages-table > tbody:last'));


Is it safe to delete 'sites/modules.sav'?

Yes, as far as Drupal is concerned, it's safe to delete that folder. Whether it's needed for something outside of Drupal I obviously couldn't say.

Drupal didn't put it there, and unless you've got a very abnormal setup (which you'd undoubtedly know about already), it's not going to be looking in that folder for any files.

It's probably a remnant of whatever automated method you used to update Drupal; if you'd done the upgrade manually that folder wouldn't have appeared.

To be sure, take a full backup, remove the folder on a dev version of the site, and run the usual tests you would after a normal upgrade. If those all pass, you'll know 100%.


Mod Rewrite for Subdomain to point to TLD

This should work:

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


Second product attribute resets if first product attribute is changed

This is addressed in a pending feature request that probably just needs a little more patch review before being committed to Drupal Commerce: https://www.drupal.org/node/1286244


How do I get rid of the "Review payment" form after PayPal Express checkout?

I got the answer and the solution on Ubercart's forum.

Quoting the user longwave:

  "In Drupal 6/Ubercart 2 go to
  /admin/store/settings/payment/edit/gateways and expand PayPal Website
  Payments Pro then Express Checkout.
  In Drupal 7/Ubercart 3 go to
  /admin/store/settings/payment/method/paypal_ec and look towards the
  bottom of the page."

I'm using D6.
Then I mentioned that I see the following message on that page:

  "You must enable the Credit Card module to use PayPal Website Payments
  Pro."

... and that I didn't want to enable Credit card module while I don't need it. He said I have to, if I would like to reach "Review payment" settings:

  "The settings are hidden here, this is a known bug. Enable the credit
  card module; you don't have to use it - or you should be able to
  disable it again after changing the Express Checkout settings."

That's true, everything related to "Review payment" form could be set there!
I made a screenshot for others who are also struggling with this problem:

Problem solved. No more unnecessary questions before purchasing. :)


Setting date-based filter criteria in Views

Hope this will help,Create a view, Add a FILTER CRITERIA on content date field
select the following option

It will return all content which is lies on current month for the respective date field. Good luck


Migrate sub_process plugin is not working

OK - I spent far more time than I care admit debugging this one. (doesn't help that PHPStorm is very unfriendly when it comes to stepping through a migration (e.g. I have not found a way to do it). Hope this saves someone from the frustration I had.

Problem one: Source was not formatted correctly. It MUST follow the following structure:

$source = [
  'countries' => [
    0 => [
      'country' => 'US',
    ],
    1 => [
      'country' => 'CA',
    ],
  ],
];

The YAML for that is:

  constants:
    countries:
      - country: 'US'
      - country: 'CA'

Problem two: The implementation of sub_process was a little off. And a little off is like being on the wrong planet. It should like this

  field_locations:
    plugin: sub_process
    source: constants/countries
    process:
      country_code: country

One thing that is not obvious (and would never be if you were actually "migrating" from D7 to D8 for example, is the source.

Here, I am not actually migrating. It is an import from JSON. And, as it turns out, importing JSON can be a little unpredictable.
The final "gotcha" was that the key "country" had to relate to the source (which it usually does).  I had tried to slap in a different constant. (bad idea - though it could be done if that is really what is wanted.


How do I add a link to the #title property of a checkbox?

The code is not calling $this->t() passing the correct arguments. The correct code would be the following one.

$pane_form['cgv'] = [
  '#type' => 'checkbox',
  '#default_value' => FALSE,
  '#title' => $this->t('I have read and accept the general terms and conditions of business', [':general-terms' => Url::fromRoute('entity.node.canonical', ['node' => 1], ['attributes' => ['target' => '_blank']])->toString()]),
  '#required' => TRUE,
  '#weight' => $this->getWeight(),
];


How to display the summary (teaser) over the body in a full content view

You can do this with Views.  Create a view that overrides the paths for your content type.  Set the display to Fields and then add the body field twice; set the first instance to display the teaser and the second instance to display the body.  You can add the images in between.  Views will also allow you to customize the CSS of the teaser/body fields easily (by default, Views provides a number of classes, and you can add additional classes if necessary).

For reference:
Node One series of video screencasts on using Views


This should just work. Make sure to follow http://twig.sensiolabs.org/doc/installation.html#installing-the-c-extension and run the commands from within /path/to/docroot/vendor/twig/twig. Next, you should check again that extension=twig.so exists in your php.ini file and that Apache has been restarted/reloaded.

To confirm that the extension is being loaded, you can run php -c /path/to/php.ini -i | grep twig


How to insert html tag "id" in an image field in a view

Searching for typeof="foaf:image" I found that was set by rdf module preprocess_image, not in views. Therefore I added a preprocess function

function MYTHEME_preprocess_image(&variables){
  // compute first MY_UNIQUE_ID
  $variables['attributes']['id'] = array('MY_UNIQUE_ID');
}

now it works.


Per instance settings on blocks with context?

If you use Context module for block positioning - you don't need to make any changes at /admin/structure/block page.

All configuration are done in context /admin/structure/context

If you need to display the same block on different places/pages/regions - just create different context for each condition.


Render entity from entity reference field

You can enable Twig Debugging in sites/default/services.yml. If services.yml does not yet exist; copy default.services.yml and rename it to services.yml.

Set the debug variable to true:

parameters:
  twig.config:
    debug: true

Now clear cache and refresh your page. Look in the html source and you should see some template suggestions.


update hook to delete and bulk update pathauto aliases

I do it with the following method:

function MYMODULE_update_7100(&$sandbox) {
  module_load_include('inc', 'pathauto');
  module_load_include('inc', 'pathauto.pathauto');

  // Delete the existing node aliases.
  db_delete('url_alias')
    ->condition('source', 'node/%', 'LIKE')
    ->execute();

  // Regenerate the node aliases.
  $nids = db_query("SELECT nid FROM {node}")->fetchCol();
  pathauto_node_update_alias_multiple($nids, 'bulkupdate');

  // Delete the topics taxonomy aliases.
  db_delete('url_alias')
    ->condition('source', 'taxonomy/term/%', 'LIKE')
    ->execute();

  // Regenerate the taxonomy aliases.
  $tids = db_query("SELECT tid FROM {taxonomy_term_data}")->fetchCol();
  pathauto_taxonomy_term_update_alias_multiple($tids, 'bulkupdate');
}


Why Content Path cannot be used to sort a view?

Node path is not a field from DB table. It is calculated dynamically.

In views you can only sort if a sorting can be applied to the underlying SQL query.


Retain revision author when editing revision

You definitely don't need to copy, replace, override, etc.

Node revision information is handled here.  As you can see, the revision author is maintained, but most use-cases will call to show the original author.

Depending on your situation, there's many ways to show the revision author instead.  For example, I see that the revisioning module you're using provides a revision-author token in revisioning_tokens.inc.

Other possibilities: hook_node_view in a module, template_preprocess_node in a theme's template.php, node--NODE-TYPE.tpl.php, etc.

Edit: BTW, if you went about updating the author ID like you mentioned, you would effectively change the ownership of the node to another user, which probably isn't a good idea!


Remove drupal parameters from form submitted via GET

I ended up doing this:

$form = drupal_get_form('my_form_id');
unset($form['form_build_id']);
unset($form['form_id']);
unset($form['form_token']);


How to have a popup calendar in a date view exposed filter?

This can be done with the Better Exposed Filters module.

Enable the module, set it as the exposed form handler under Advanced -> Exposed form style, on the BEF settings page dialog set the filter display option to "jQuery UI Datepicker". Save everything and you should be good to go.

Note that changing from the default date format may require you to implement hook_better_exposed_filters_display_options_alter.


View of taxonomy terms - add preprocess class

You should try hook_views_pre_render(&$view);
http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

Also you can write a template file to write extra css class with condtion. For this go to advance section and go for theming section and choose a template name.


Having a view spitting out a form - the UI way

You can try using the editablefields module.

I personally find it better to write a custom views handler implementing the Views Form API, but you can try to see how far this takes you.


Filter View based on current user profile info (from Content Profile Module)

See this post for a solution in Drupal 7, but the same principle applies here.

Create an argument for the related loc of todays_spot.
Choose the the right relationship (node, I think), and select 'provide default argument'
Use 'PHP Code' as your default argument

You'll need to modify the code below to match your system, but it should resemble the following:

global $user;
// the code below loads via the Profile2 module, but something similar
// will work with Content Profile, but you'll need to inspect the code
// to find a function similar to `profile2_load_by_user`
// I'd start by inspecting the $user variable with print_r or dd();
$profile = profile2_load_by_user($user->uid,'facilitator');
if (!$profile) { return ''; }
if (!isset($profile->field_location['und'])) { return ''; }
$locations='';
foreach ($profile->field_location['und'] as $location) {
  $locations.=','.$location['nid'];
}
return substr($locations,1);

Don't forget to select 'Allow Multiple Terms Per Argument' before saving your new argument.


To print out the the profile2 profile Programmatically, you can do the following:

module_load_include('inc', 'profile2_page', 'profile2_page'); // Include profile2_page module
global $user; // Current user.
$profile2 = profile2_by_uid_load($user->uid, 'profile2_machine_name');
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit'); // Or 'add'
print drupal_render($entity_form);

This should allow you to edit a Profile2 fields from the current logged in user. For registration I'm not sure how to print that other than redirect the user to the specific Registration Path from the Profile2 Registration Path, but for Logging in you can use the default form like in my question:

 print(drupal_render(drupal_get_form('user_login_block')));

P.S: Remember to clear you cache.


How can I assign a URL with a fragment (#) as an array value?

You can use an array for $form_state['redirect'], the elements of which mirror the arguments passed to the url() function.

So you can use...

$form_state['redirect'] = array(
  "mypage/$nid",
  array('fragment' => 'comment-form'),
);

The method it used quite sparingly in core (just 5 occurrences as far as I can tell); node_form_delete_submit() contains an example.


How do I apply a discount for the second and successive items only if the quantity for those items is higher than 1?

You should be able to do this out of the box if you have the Commerce Discount Extra module installed. The offer type to use is Per-quantity product discount (% off). This offer type (and the other per-quantity offer types) was created to support BOGO style offers (buy 1, get 1 free), but we developed them to support any type of discount for any number of matching products.

In your case, you'd set the "Buy #" to 1 and the "Get up to #" to a very high number... whatever you consider reasonable for the quantity you'd expect to discount. This will result in the creation of a new discount line item.

Note that the pattern for matching products will be SKU based or product category based.


Cannot use object of type Profile as array

This

$user_full = profile2_by_uid_load($user->uid);

Returns an object, which you are then accessing as an array:

$user_full['client']

Which is illegal in PHP. You should access objects as objects, e.g.

$user_full->client

Or whatever it might be for that object type.


To release the lock, remove it from semaphore table, e.g.:

drush sqlq "DELETE FROM semaphore WHERE name LIKE 'feeds_source_%'"

If you got different error like:

  The feed is currently importing.

then you need to clear out state and fetcher_result data from feeds_source table, e.g.:

drush sqlq "UPDATE feeds_source SET state = NULL, fetcher_result = NULL WHERE id = 'FEEDS_MACHINE_NAME' AND feed_nid = 'NID'"

Note: Change FEEDS_MACHINE_NAME and NID into appropriate values.


How to replace authentication links with custom routes?

You need to alter the route, in your custom module add:

mymodule/src/Routing/RouteSubscriber.php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/login' to '/customn-login'.
    if ($route = $collection->get('user.login')) {
      $route->setPath('/custom-login');
    }
    // Change path '/user/register' to '/custom-signup'.
    if ($route = $collection->get('user.register')) {
      $route->setPath('/custom-signup');
    }
  }

}

mymodule/mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

For more in depth information, see Altering existing routes and adding new routes based on dynamic ones.

If you still want /user/login to work, then you can create a new route for it.

mymodule/mymodule.routing.yml

mymodule.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

Remember to clear all caches to see changes.


Does xyz field name contain underscores?

  Note that underscores in a Field's machine name are replaced by
  hyphens. Also remember to include "field-" in custom field names, e.g:
  field--field-phone.tpl.php.

https://drupal.org/node/1089656

EDIT:
Add a hook_preprocess_field(&$vars) in your theme and dpm($vars) to check up on theme_hook_suggestions array for this field.


Node reference - limit so node can only be referenced once

Node reference (for Drupal 6) and Entity Reference (for Drupal 7) fields can be configured to use a View to show the available choices.

So, first create a View that shows all buddies that are not related to a runner. Then configure the field that points to the buddy to use that View.

To construct that View you may use the Corresponding Node References. It syncs the node reference between two node types which have a nodereference to each other. WIth this module your View only has to list buddies that have no runner related. This module is for Durpal 6 (I'm guessing your are using Drupal 6), but there's a similar one for D7.


Get paragraph field in a specific text format

$basic_content_block->get('field_content')->summary;

I believe that should do it.


How do I remove duplicates when using the random sort?

The simple way to achieve distinct values in a view is to make the following:

Go and edit your view
In Advanced » OTHER section click on "Query setting"
Check "Distinct" check-box.


Remove Welcome message and "No front page content has been created yet."

Both are displayed by the different code, hence you need to unset/remove both.

1. Create a separate front page template: In your theme's tempaltes folder make a duplicated of page.tpl.php and rename the dulpicate one as page--front.tpl.php. Now your all other pages will be handeled by page.tpl.php and the only front-page will be handeled by page--front.tpl.php.

2. Edit the page--front.tpl.php template: Now, as you said you are able to remove the message using the code which is in your Question, so go ahead with that.

Secondly, remove the following code from your page--front.tpl.php, which will remove the Welcome...... part.

<?php if ($title): ?>
   <h1 id="page-title">
     <?php print $title; ?>
   </h1>
<?php endif; ?>


Update the actual file associated with a file entity while keeping the fid?

As @clive noted in the comments, all that is needed is to replace the file itself. We were having some other server issues that were causing the change not to show up. You may need to flush your image styles in order for those to pick up the new image, though.


How to call a specific library file inside the div

Attaching a library via the #attached tag will add it to the header (or bottom of the page if that's the settings). It does not get added into the "content" area. So, wrapping it in a
 is not applicable.

If you are using JS to generate some content that needs to be placed on the page, then it needs to be written to find some selector and insert the content.  E.g.

jQuery('#my-dynamic-content').html("My new div content");

Then just add the

 to your template/content as needed.


How to show last login time and user email to all authenticated users?

EDIT:

I set up a test View myself and confirmed the issue you reported. Upon some search, I see this is intended behaviour.

There is a thread discussing it here: https://www.drupal.org/project/drupal/issues/2799049

The thread has a very simply Core patch to resolve the issue that could be applied. Or, there's also information on using hook_entity_field_access() to grant field-level access to User fields.

https://www.drupal.org/project/drupal/issues/2773645

************************ORIGINAL INFO***************************

From what you've said, it seems like it should work as you'd expect.

One thing you can try is checking the "Disable SQL rewriting" checkbox in your View. This will bypass ALL permission checking for the View. It is located in the Query Options setting in the Advanced section of your View config.

If checking this works then you'll know that,at least, the issue is permissions related.


After having asked a friend, I can now answer the question myself.

The solution is pretty straightforward: At FILTER CRITERIA, I simply add field_active, with the operator "Is one of" checking the value "On".

I thought, FILTER CRITERIA may only be fields actually displayed, but this is not the case. It works for all fields being in any form used in the view.


Yes it is, you just need to look a bit harder ;)

Have a look at the serialised array in the data column of that table. You'll find the label for the field listed in there.

If you want to extract this in code the best way is to use the field API functions, it saves you having to mess about with the serialised array directly:

$entity_type = 'node';
$field_name = 'body';
$bundle = 'article';

$info = field_info_instance($entity_type, $field_name, $bundle);
$label = $info['label'];


How to avoid "An illegal choice has been detected" when updating select list values via ajax?

--- Original answer. Is wrong, check update below.

Just set

$bla['#validated'] = TRUE

On the select that will be updated with AJAX.

Checkout "Illegal Choice has been detected"

--- Update 17 Dec 2019 ---

Actually that was not good advice, that was a long time ago, now I know better.

Ajax callback function is supposed to only return the piece of form that has changed or some ajax commands.

In this case form modification must be made on the form function or a form alter hook. Form building and validation functions are run each time an ajax callback is called. Just check $form_state on your form build or alter function and adjust values accordingly.

See Resolve the error "An illegal choice has been detected..."


Embedding Views programmatically getting argument overridden title

Okay I got it...

After executing the view in your code (e.g. with a $view->preview()).
You need to find the argument in the view that sets the title, and then call set_title() on it.

Here's what I did (note that I'm assuming that in the case of multiple arguments setting titles it's the last one that works, hence the array_reverse, haven't tested this yet).

<?php
$view = views_get_view('taxonomy_term');
$view->preview('panel_pane_1', array($tid));
foreach (array_reverse($view->argument) as $argument) {
    if ($argument->options['title_enable']) {
        $page_title = $argument->get_title();
        break;
    }
}
?>

Hope that helps someone else out.


How to make two vocabularies works as section and category for article?

I think you can use views with arguments to create this pages.

you should create links manually with l('title', "/{$vocab1_term}/{$vocab2_term}"); in your .tpl.php files associated with this views


Looking at menu_link_save(), you will see that it calls menu_cache_clear() to clear only the cache of the menu the menu item belongs to. Other entries in the menu cache are not cleared.

The entire menu cache is only cleared when menu_cache_clear_all() is called directly (eg. by menu_enable(), which runs whenever a module is enabled) or indirectly (often through menu_rebuild() or drupal_flush_all_caches()).

If I were you, I would store my own data in the default 'cache' bin. I consider the menu cache to be private to the menu system; I don't want to touch it and accidentally mess something up. To clear my cache data at the right moment, I would implement hook_meu_link_insert() and/or hook_meu_link_update() and clear/rebuild my cache data from there.


Drupal Commerce: Prices on Variations not displayed when selecting a variation

This seems to work out of the box. There was a JQuery version conflict that was causing javascript errors.


How to implement user enrollment or subscription?

It seems that this can be done with Entity Registration module.


Unresolved dependency updating the module

Just download a newer version of views and replace in your project.

https://www.drupal.org/project/views/releases

If you're using composer just require a newer version.

Then, you should be able to install your drupal.

Best regards
:)


Getting the field of a user based on uid or name

I think if you need show more info of author of node, you can try this way.

STEP 1

in file template.php write hook_preprocess_node

function YOURTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $user = user_load($node->uid);

  // if you want render field user
  $phone_render = field_view_field('user', $user, 'field_phone')
  $phone_html = drupal_render($phone_render);

  // if you want get value of filed
  $phone = field_get_items('user', $user, 'field_phone');
  $phone_value = $phone[0]['value'];

  $vars['phone_value'] = $phone_value;
  $vars['phone_html'] = $phone_html;
}

use need change field_phone with your machine name of your field user.

STEP 2
In file node.tpl.php. You can use

<?php
  print $phone_value;
  print $phone_html;
?>

print where you need.


How to pre-generate image styles after image is uploaded

You can look into Image Style Pregenerate module to generate images.


How can I attach a view for each row of another view?

1) Viewfield is a good solution.

Views attachment attach to a views display (Page, Block etc) not to each row.

So, first remove the Contextual filter uid.

Then add one more field, the flag of the node. Then you will have User_Name, Node Image, Flag and each row will represent a node.

2) Another option is to use the Views_Merge_Rows. In the Merge Rows settings you have to set the Merge Options for the User Name field as "Use the values of this field as filter" and uncheck the "Exclude this field from display". For the other fields select the "Use the first value of this field".

3) If you don't want to use a contributed module use the "Group results together" on the Format display settings. Group by user name and then Exclude from display the User Name field.


What is the template file name for a bean block?

As I can infer from the class name, your module name is "bean", so the template name should be block--bean--hero.tpl.php. For more information you can check the Template (theme hook) suggestions documentation.


Show a dynamic text depending on the day

You can use views_embed_view() to get the output of a view manually. Supposing your view is called 'days' and you want to display the output of this view:

print t('Today is @dayname day.', array('@dayname', views_embed_view('days')));

(This assumes the output of your view is just some text, and contains no HTML.)

By 'on the right-top', do you mean the page title? In any case, you could set a variable in your theme's preprocess function (which goes in the theme's template.php), like this:

function mytheme_preprocess_page(&$vars) {
  $vars['daystring'] = t('Today is @dayname day.', array('@dayname', views_embed_view('days')));
}

Now, in your page.tpl.php, you can write something like this:

print $daystring;


How to theme a node form from my custom module?

Use this:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    // Expected format: NODE_TYPE_MACHINE_NAME_node_form
    case 'resource_node_form':
      // Requires devel module to be installed.
      // See all available elements displayed using krumo.
      $dpm($form);
      break;
  }

}

Update:

Depending on the complexity of your layout, check Display Suite and Field Group modules, as their functionality might be what you need.

You can also follow up this article if you want to do this from a tpl file. The approach is similar to what you were trying to do.


How do I access the node's uid in hook_node_access()?

The $node parameter is

  Either a node object or the machine name of the content type on which to perform the access check.

When that hook is invoked with the create op, there's no node object available, so $node is a string.

You're already handling that bit, but you're missing a check on the $op parameter. The reason it's working is because when your function is invoked with the op you're trying to target (probably view), $node is an object and has a uid property.

With your current code, you'll get one of those notices every time someone other than user 1 tries to create a node, because $node is not an object.

Try re-working your code like this:

function mymodule_node_access( $node, $op, $account)
 {
   if ($op == 'create') {
     $type = $node;
     // You can be reasonably sure that $account is the user who's trying to create the node here.
     // You'll probably want to ignore this bit and check $op specifically for the
     // actions you're looking for; this is just here to show the workflow.
   }
   else {
     if ($node->type == 'myCustomType') {
       // Be sure to use the $account var here, not the global $user object
       if ( ($account->uid != $node->uid) && !user_access("view other's posts", $account)) {
       return NODE_ACCESS_DENY;
     }
   }

   return NODE_ACCESS_IGNORE;


Add a column to a Views table display conditional on argument

I don't know if this is the best way to do it, but when I've needed conditional columns I've removed them in hook_views_pre_build() (which is before the query gets built). The code would be something like this:

/**
 * Implements hook_views_pre_build().
 *
 * Removes column X on condition Y from all displays of view Z.
 */
function MYMODULE_views_pre_build(&$view) {

  // Check this is the right view.
  if ($view->name != 'Z') {
    return;
  }

  // Check if the column should be removed.
  if (!$Y) {
    return;
  }

  unset($view->field['X']);
}

The code above will affect all displays of the view. If you want to target a particular display just check against $view->current_display as well.


I am not able to assign a group to a node while creating it

I have tried posting group content but didn't work in all field widgets (select, checkbox or auto complete)

I see there exist an issue with that field og_group_ref take a look at that question have an answer with a patch hope to solve the issue.


How to call function from PHP file (or another module) in JS file from my custom module?

You can add a menu callback in your module, that will be used by JS to send-receive values from PHP.

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['my-module/my-function'] = array(
    'title' => 'Ajax callback for my function.',
    'page callback' => 'my_module_function',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_function() {
  // Remember you have to print your results if you want to
  // send any values back to JS.
  print 'Hi, there!';
  drupal_exit();
}

Now in your JS code, you make an Ajax call and, optionally, get values back from PHP (if desired).

$.ajax({
  url: Drupal.settings.basePath + "?q=my-module/my-function",
  done: function(data) {
    // If my_module_function returns any value, it will come in the data variable.
    alert(data);
  }
});


How to hook_form_alter() inside paragraph item

For Drupal 8 you can implement hook_field_widget_WIDGET_TYPE_form_alter.

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function paragraphs_test_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'altered_paragraph') {
    $element['subform']['field_text']['widget'][0]['#title'] = 'Altered title';
  }
}

see my answer here: How do I alter the behavior of the form fields contained within the paragraph field?


How to update one select element via Ajax when using node_add

Since you're dealing with fields created in by Drupal admin, You may want to check the option values you replaced in the fields that it matches in the field settings.

[EDITED]

Try the Hierarchical Select module. In the page, it also supports Taxonomies.


Surround specific webform elements with a div

Why do you need a div?

Just use a field set and hide label and turn off the collapsible feature.

If anything this is more semantic than using a div in splitting up fields in a form. Visually will look excately the same and you can also use CSS class generated from the field set name in your styling.


URL redirects within drupal 7 site breaking image display in blocks

Well, this image will play nice only if you are in your homepage or something and then the relative path is as: http://site.com/sites/default/files/footer-get-in-touch.png

Off course this won't play for other paths as this is invalid

http://site.com/<PATH>/sites/default/files/footer-get-in-touch.png

Quick Solution:

Enable php filter module, to be able to write php inside the blocks contents and provide correct image path for all cases

<?php
    global $base_path;
?>

    <img src="<?php echo $base_path; ?>sites/default/files/footer-get-in-touch.png" alt="" width="250" height="291" />


How do I present the user login form from a callback, and redirect them after login?

You can render the user_login_block on your page. Once the user successfully log in, they will be redirected to the same page on which the user login block was generated (so the same page actually).

To render the user_login_block, you can make use of the drupal_get_form and passing the form name as an argument.

function YOURMODULE_page()
{
    $build = array();

    // construct your build with parts of the page
    // ...

    if (!user_is_logged_in()) {
        // user not logged in, add the login form
        $build['user_login'] = drupal_get_form('user_login_block');
    }

    return $build;
}


installed memcache, no noticeable improvements

I recommend you to try/use Authcache module

http://drupal.org/project/authcache

Make sure to configure it with memcache by adding the following line in your settings file

$conf['cache_inc'] = './modules/authcache/api/authcache.inc';