Populating select list from a taxonomy term field I'm trying to populate a select list dynamically by pulling its values from a taxonomy term field linked to the current-user account. Just to clarify, below function is a hook defined by a module that came with a custom installation profile. It is basically used to create fields on a specific form.
So, my custom module has-

function some_function_attributes() {

      global $user;
      $user_fields = user_load($user->uid);
      $termid = $user_fields->field_user_organization['und']['0']['tid'];
      $taxonomy_term = taxonomy_term_load($termid);
      //dsm($taxonomy_term);
      $options = field_get_items('taxonomy_term', $taxonomy_term, 'field_org_environment','select');
      dsm($options);
      return array(
        'environment' => array(
        'type' => 'select',
        'options' => $options,
        'name' => t('Environment'),
        )
      );
    }

Allowed values in the field (for this user)-

E1|Env1

E2|Env2

Here's the devel screenshot for dsm($options);

So, its populating the right field but not in the way it should.

Actual form element looks like this-

Currently, its just returning the array and I can't figure out what I missed. Been banging my head to the wall for this-
How would I populate Env1 and Env2 in this select-list ?

You'll have to reformat the options array to be in the form 'return value' => 'display value'. See https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#options


How do I use variables in links.task.yml? I have a local links.task.yml file to display the tab for the node data , But it seems to have a problem passing argument to the path . As you can see i am extending the node's basic fetaures like edit,delete.revision with an additional function using tab .  I have module_name.links.task.yml

entity.node.check_backend:
  route_name: module_name.my_route
  base_route: entity.node.canonical
  title: My title

And i have the route in module_name.routing.yml  as follows

module_name.my_route:
  path: '/node/{arg1}/function_name'
  defaults:
    _controller: '\Drupal\module_name\Controller\ControllerName::function_name'
    _title: 'My title'
  requirements:
    _permission: 'access admin tab'

But it throws me error like :

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("arg1") to generate a URL for
  route "module_name.my_route".

How can i pass variables in links.task.yml file ?

In your module_name.links.task.yml file you can add a route_parameters: array that lists the parameters you want to pass, in your case it would end up:

entity.node.check_backend:
  route_name: module_name.my_route
  base_route: entity.node.canonical
  title: My title
  route_parameters:
    arg1:  'value_for_arg1'

You can find this by looking at the code in \Drupal\Core\Menu\LocalTaskManager which parses this file.


Submit few forms in Drupal 7 I try to add  Poll-voting to my website, on page I addet 5 votings forms, I try to make submission of all 5 forms by one click instead of 5 clicking. I wrote this script :

 <script language="javascript" type="text/javascript">
      function submitDetailsForm() {
           $('#poll-view-voting').submit();
       }
 </script>

But this code submit first form only(the forms has one id).
Console.log retrieve this:

[form#poll-view-voting, context: document, selector: "#poll-view-voting", init:  function, jquery: "1.4.2", size: function…]
0: form#poll-view-voting
context: documentlength: 1
selector: "#poll-view-voting"
__proto__: Object[0]

How i can solve this issue, help please. I am new in Drupal 7 and JS.

Use Advanced Poll module. I think this may help you to solve your query.


Cannot edit existing content I've unfortunately run into a rather major issue on an existing Drupal site.  I recently applied the updated from core 7.12 to core 7.14. Since then, I can create new content in the admin panel, yet I cannot edit or make any changes to existing content.  I see the following errors:

  Warning: array_merge() [function.array-merge]: Argument #1 is not an array in _form_set_class() (line 4134 of .../form.inc).
  Warning: implode() [function.implode]: Invalid arguments passed in theme_radios() (line 2809 of .../form.inc).
  An illegal choice has been detected. Please contact the site administrator.

I deleted and reverted the site back to how it was before running these updates, yet again, after updating Drupal core, I still can't edit any content.  Is there any direction that can be given in resolving this issue?

I had an issue similar to this. The update to Drupal core caused issues with content types using the References Dialog module. We noticed that altering any nodes with a type using these reference dialog fields had issues. What tipped me off was that the other content types didn't have an issue. Odds are that this error is being caused by another module. Here are a couple things you can try in a development environment:

Create a new content type with core fields (a title, body, and maybe an image field will work). Do you get the same problem?
Verify whether or not all of your content types are affected. I know you said you can't alter any content, but you can save yourself time by being absolutely sure. Choose a few nodes for each type and try editing them to see if you get any other issues. If you see that there are only some content types affected, you can find out what fields / widgets they're using and start to deduct which one is causing the problem.

Good luck!


Make block visible to specific IP (in D6) On a D6 site I want a block that it visible only to visitors from a specific IP. If I choose Page specific visiblity settings with the PHP code

<?php
  if(strcmp(ip_address(),'1.2.3.4')==0) {
    return true;
  } else {
    return false;
  }
?>

it works fine on all pages, except for the front page.

How can I make this setting work also on the front page?

Is this snippet not executed on the front page?

Update: Or is this some caching issue? It's working on the front page, if I connect with https. But block caching is disabled on the site.

The commentators questions and remarks pointed me in the right direction, so here's the solution to my own question:

With page caching enabled, the above PHP condition is evaluated only occasionally on cache rebuild. If someone with the correct IP visits the site at the right moment the block can get visible and cached. Visitors with the wrong IP may then also see it (from the cache). Therefore the above approach is wrong.

Correct solution: Use IP login to authenticate some real or special user, then make the block visible to this user with the PHP condition:

<?php
  global $user;
  if($user->uid==123) {
    return true;
  } else {
    return false;
  }
?>

Of course, one could also define a new group and use the group-based visibility settings.


How to create test users on the localhost? I would like to make test users on my localhost (in my case I am using WAMP). Since I need to be able to authenticate them via email. I am not getting it to work what can I do?

To add new user you can go to admin/people/create (localhost/YOUR-SITE/admin/people/create) and create the user, you don't need to enter a real email. And if you want to test the site with different users you can use the Masquerade module.

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

  This is helpful for site developers when trying to determine what a
  client, logged in as themselves, might see when logged into the site.


javascript smooth scroll I would like to implement smooth scrolling on my page made in drupal 6. I have a list of topics on top of the page. I would like the page to smooth scroll down direction to the topic. Can any point me how to do it in drupal 6?
thank you

Try customising the Scroll to Top module. Which provides a similar functionality.


commerce_order_status_update() doesn't update the order status After the order is paid in full (or not checkout is complete if there is no payment required and I ever get that working) I need to do a bunch of processing to set up the product the user has just bought. Only once that is done can I say the order is complete and I thought this would do it

commerce_order_status_update($order, 'completed');

But it doesn't change the order status. They are always left as Pending.

How do I programmatically change an order status from pending to completed?

It sounds to me like you're updating the order to completed before the checkout completion rule fires that updates the order to pending. You can confirm this by looking in your revision log for the order in question.

If I were you, I'd just add a condition to that default checkout completion rule to not update the order status if it is already completed.


Access a 'global: custom text' field in fieldpluginbase render() I'm trying to get more familiar with FieldPluginBase to create a new custom field for views. As an example I implemented a new field called 'dropdown list' that "wraps" other view-fields the user selects. Therefore I implemented a form in buildOptionsForm() that shows all currently displayed view fields and let's the user select multiple via checkboxes (kind of similar to the dropbutton behavior).

This works well and in render() I can see which fields the user checked via $this->options['field_types'].

Next I want to add the user-chosen fields to a renderarray and display them as an item list ('#theme' => 'item_list') to later add some custom css classes and style them. However, I have currently no way of accessing all fields that are shown in the view, only the entity fields via $entity->get('field_name')->getValue(). That gives me the standard entity fields like title, body, nid ... But I do have a Global: Custom text (id='nothing_2') that I need to access (that is excluded from display and output as a custom link). I found no way of accessing the value of such fields that do not directly belong to the entity (I tried $this->view->field[...] and $this->displayHandler->getValue(...) without success).

Any idea if what I'm trying to do is possible and what I'm missing ?

class DropDownList extends FieldPluginBase {

  public function query() {

  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['field_types'] = ['default' => []];
    return $options;
  }
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {

    $fields = $this->displayHandler->getFieldLabels(TRUE);
    $pos = array_search('dropdown_list', $fields);
    unset($fields[$pos]);

    $form['field_types'] = array(
      '#title' => $this->t('Which fields should be included?'),
      '#type' => 'checkboxes',
      '#options' => $fields,
      '#default_value' => $this->options['field_types'],
    );
    parent::buildOptionsForm($form, $form_state);
  }

  public function render(ResultRow $values) {
    $items = [];
    if ($entity = $this->getEntity($values)) {
      // Dummy loop to show how I wanted to approach this
      // Checkboxes results are available like this (in this output
      // the user only checked the custom text 'nothing_2'):
      // nothing_2=>nothing_2 nid=>0 title=>0 body=>0 uid=>0
      foreach($this->options['field_types'] as $key=>$value) {
        if ( $value != '0') {
          // There is no field 'nothing_2'
          $items[] = $entity->get('field_name')->getValue();
        }
      }
    }
  $build['theme_element'] = [
      '#theme' => 'item_list',
      '#title' => $this->t(''),
      '#items' => $items,
    ];
    return $build;
  }
}

UPDATE

Using $this->view->field['nothing_2']->getValue($values) as also suggested by 4k4 returns an empty string, although I know that nothing_2 contains a link: Edit but it does not seem to be directly contained in getValue()

As indicated by @4k4 the solution is using advancedRender() inside a for loop

public function render(ResultRow $values) {
  $items = [];
  foreach ($this->options['field_types'] as $key => $value) {
   if ($value != '0') {
    $items[] = $this->view->field[$key]->advancedRender($values);
   }
  }
$build['theme_element'] = [
  '#theme' => 'dropdownlist-theme',
  '#title' => $this->t('Dropdown List'),
  '#items' => $items,
 ];
 return $build;
}


How to add site Validation for all pages I want to implement google site validate meta tag on each page page of my site. I tried Site_validation module but its allows to implement the google meta tags only on front page.
Could anyone help me?

One way to do that is using the "site_verify" module and you can add another hook to add it to all page that will look like this:
 /**
 * Implements hook_init().
 *
 */
function YOUR_MODULE_init() {
  $meta_tags = db_query("SELECT svid, meta FROM {site_verify} WHERE meta <> ''")->fetchAllKeyed();
  foreach ($meta_tags as $svid => $meta_tag) {
    $data = array(
      '#type' => 'markup',
      '#markup' => $meta_tag . "\n",
    );
    drupal_add_html_head($data, 'site_verify:' . $svid);
  }
}

you need to change "YOUR_MODULE" with your custom module name. Also clear drupal cach after adding it


Is the field item delta in the database reliable? Use case / background:

A node type "product".
A taxonomy vocabulary "feature". E.g. "color" and "size". (forgive the name, it has nothing to do with the features module)
Every product can have up to one value for each feature. E.g. color = green, size = big.

At first, this sounds like I should be using one (single-valued) field per feature, instead of a taxonomy. But this really does not scale, because there are going to be many many features, and new features can be dynamically added.

Another option would be a new entity type or bundle "node feature value". Or a new field type with two database columns, which stores both the tid of the feature, and the value.

But I thought, what if I use a regular text field with a custom widget? I would use the "delta" to store the feature tid, and the text value for the value.

Because, let's face it, the delta would be redundant anyway, if there can be only one value per product x feature.

The only question is, how reliable are the deltas? Can it happen that something will "normalize" the deltas to a regular continuous integer sequence 0..n ?

The answer is definitely "no", but it's a hard "no", not engine-dependent like it might appear. Under normal operation, the 0..n delta reset happens before the data is ever sent for storage.

If field values are saved using the API (field_attach_submit() etc), then they're unconditionally run through _field_filter_items():

function _field_filter_items($field, $items) {
  $function = $field['module'] . '_field_is_empty';
  foreach ((array) $items as $delta => $item) {
    // Explicitly break if the function is undefined.
    if ($function($item, $field)) {
      unset($items[$delta]);
    }
  }
  return array_values($items);
}

As you can see, any indices you might have manually set in the $items array will be discarded, and the resulting array will always be indexed 0..n. I don't think Drupal gives you another opportunity to affect that array before the data is persisted.


Producing collapsible field sets with theme functions In an older Drupal 6 instance, I'm updating a module to produce a collapsible fieldset with the following:

function my_module_function($table_collections) {
    // include JavaScript for collapse functionality
    drupal_add_js('misc/collapse.js');

    foreach($table_collections as $table) {
            $to_return .= '<fieldset class="collapsible collapsed">';
            $to_return .= '<legend>' . $title . '</legend>
' ;
            $to_return .= theme_table(array_keys($table[0]), $table);
            $to_return .= '
</fieldset>';
    }

    return $to_return;

}

My question, is there a better way to wrap this in a complete theme function? theme_fieldset and ctools_collapsible_theme(&$items) appears to be for forms. Is there a more standard or better approach than what I have above?

You can call theme_fieldset() directly, even if it's not for a form, as long as you structure the $element correctly:
https://api.drupal.org/api/drupal/includes!form.inc/function/theme_fieldset/6

You can see an exemple in core here:
https://api.drupal.org/api/drupal/modules!system!system.admin.inc/function/theme_system_modules/6

$fieldset = array(
  '#title' => t($package),
  '#collapsible' => TRUE,
  '#collapsed' => ($package == 'Core - required'),
  '#value' => theme('table', $header, $rows, array('class' => 'package')),
);
$output .= theme('fieldset', $fieldset);

theme_fieldset() is also valid in Drupal 7, but it seems to have changed in Drupal 8.


How to create more than 1 block with different .tpl (theme) file in a single module? How to create more than one block with different .tpl (theme) file in single module in Drupal 7?

Suppose I have a module name mymodule, I want to create two blocks in this module name as myblock1 and myblock2 and these two block should be associated with different tpl file like block1.tpl.php and block2.tpl.php. and both blocks have same content.

Any help?

Block code from custom template is here

 /**
 * Implements hook_theme().
 */
function my_custom_block_theme() {

    $theme = array();

    $theme = array(
        'my_custom_block_output' => array(
            'variables' => array('items' => array()),
            'path' => drupal_get_path('module', 'my_custom_block') . '/templates',
            'template' => 'block--my-custom-block'
        ),
        'my_custom_header_block_output' => array(
            'variables' => array('items' => array()),
            'path' => drupal_get_path('module', 'my_custom_block') . '/templates',
            'template' => 'block--my-custom-header-block'
        ),
);

    return $theme;
}

/**
 * Implements hook_block_info().
 */
function my_custom_block_block_info() {

    $blocks['my_custom_block_output_block'] = array(
        'info' => t('Custom one'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );

    $blocks['my_custom_home_block_output_block'] = array(
        'info' => t('Custom two'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
  return $blocks;
}

**
 * Implements hook_block_view().
 */
function my_custom_block_block_view($delta = '') {
    $block = array();
    switch ($delta) {
        case 'my_custom_block_output_block':
            $block['subject'] = t('Block one');
            $block['content'] = _my_custom_block_block_content();
            break;
        case 'my_custom_home_block_output_block':
            $block['subject'] = t('Block 2');
            $block['content'] = _my_custom_home_block_block_content();
            break;
 }
    return $block;
}

/**
 * Callback implemented by hook_block_view().
 */
function _my_custom_block_block_content() {
    //Your custom values for output in $items
    $items = get_data();
 $output = theme('my_custom_block_output', array('items' => $items));
return $output;

}
function _my_custom_home_block_block_content() {
   //Your custom values for output in $items
   $items = get_data();
 $output = theme('my_custom_header_block_output', array('items' => $items));
return $output;

}

 //Data to be output
 function get_data(){
     //Your custom code
    }

Template file(.tpl) should be in "template" directory
Eg :

template/block--my-custom-block.tpl.php
template/block--my-custom-header-block


Update the from name in workbench email template I'm trying to update the "from" name in my workbench email template. I created a custom module and added the following hook ('hook_mail_alter') but it's still not updating the from name for my email template. Does the below hook look right?

function my_module_mail_alter(&$message) {
  if ($message['id'] == 'needs_review') {
  $message['from'] = 'Full Name <email@address.com>';
  }
 }

https://api.drupal.org/api/drupal/core%21core.api.php/function/hook_mail_alter/8.7.x

I'm pretty sure that $message['from'] shall be an email address.

Try to set the From header instead, like this:

$message['headers']['From'] = 'Full Name <email@address.com>';


No data showing in tableselect This is a very weird one...

I am building a table using

'#type' => 'tableselect'

I have

$header = array('date', 'name', 'email', 'location', 'time');

and

$options[$result2[$i]['id']] = array(
    'date' => gmdate("d / m / Y", $result2[$i]['timestamp']),
    'name' => $result2[$i]['name'],
    'email' => $result2[$i]['email'],
    'location' => $str_location,
    'time' => $str_time,
);

then I am building the table like this...

    $form['table_' . $n] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $options,
        '#prefix' => '

' . $record1->name . '
',
        '#suffix' => '
',
    );

The problem is this: The rows are showing.... but with no data in them!

I can output the $options array and it contains the data I want to see in the table.
I have cleared the cache as mentioned here

Any clues as to why there are the correct rows with the correct columns but with no data?

Ahhhh!

Just as I posted this I discovered that my $header was malformed!!

$header = array('date', 'name', 'email', 'location', 'time');

should have been

$header = array('date' => 'Date', 'name' => 'Name', 'email' => 'Email', 'location' => 'Location', 'time' => 'Time');

Phew!


Webform duplicate entry on edit Webform creates a duplicate entry on edit, instead of editing the entry, is there a way to make it work the way it should (by not creating a new entry)?

Using Drupal 7 and Webform 7.x-3.17+3-dev.

I've never had this problem and I use Webform in pretty much every project.

I would suggest your problem is based on the fact you're using a dev version of the module. Webform has a stable release of 7.x-3.18 whereas you're using 7.x-3.17+3-dev. The first thing I'd do is upgrade to the stable version, clear the caches, and see if the problem persists.

If it does, or you want to stick with the dev version for whatever reason, then you should report any problems to the module issue queue in the first instance.


Is it possible to add a menu to a menu? I've created a "Staff menu" with various menu items. However I want to add it to the "Main menu" as a drop-down list (e.g. set Staff as Vertical, while Main is the navbar / horizontal menu).

Is it possible to just add a menu to a menu by creating a new menu item in the "Main menu" and linking it to "Staff menu" ?

You can use this module http://drupal.org/project/om_maximenu then create parent menus and its child menus .Even you can create blocks inside with the sub menus.


Getting error "Table 'drupal.watchdog' doesn't exist" during install I'm a Drupal newbie and haven't been able to find this problem posted elsewhere online, so I'm hopeful someone here can help.

I have just set up php/mysql on a shared hosting environment and copied drupal 8.0.5 over to begin the installation (I changed some file permissions and copied settings.php and .htaccess over to the correct locations as per the instructions).

The server seems to be running MariaDB 10.0.23-MariaDB~trusty (debian maybe?) and ostensibly php 5.6. However, when I run php --version on the server I get PHP 5.5.32-nfsn1 (cli) (built: Mar 11 2016 21:11:51). However, Drupal hasn't complained so it seems to agree that they're running 5.6.

Where I'm getting stuck is during the installation phase, where it breaks about half way through with the following error message:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /core/install.php?rewrite=ok&langcode=en&profile=standard&id=1&op=do_nojs&op=do
StatusText: OK
ResponseText: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.watchdog' doesn't exist: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array
(
[:db_insert_placeholder_0] => 0
[:db_insert_placeholder_1] => DrupalKernel
[:db_insert_placeholder_2] => Container cannot be saved to cache.
[:db_insert_placeholder_3] => a:0:{}
[:db_insert_placeholder_4] => 3
[:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] => http://www.mysite.info/core/install.php/?_format=json&id=1&langcode=en&op=do&op=do_nojs&profile=standard&rewrite=ok&rewrite=ok
[:db_insert_placeholder_7] => http://www.mysite.info/core/install.php?rewrite=ok&langcode=en&profile=standard&id=1&op=start
[:db_insert_placeholder_8] => 43.247.118.190
[:db_insert_placeholder_9] => 1459041023
)
in Drupal\dblog\Logger\DbLog->log() (line 84 of /home/public/core/modules/dblog/src/Logger/DbLog.php).

clicking the link to the error page takes me to this:

  Catchable fatal error: Argument 1 passed to
  Drupal\Core\Routing\CurrentRouteMatch::getRouteMatch() must be an
  instance of Symfony\Component\HttpFoundation\Request, null given,
  called in
  /home/public/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on
  line 92 and defined in
  /home/public/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on
  line 104

I can't make a lot of sense of this message. A quick google search lead me to a bunch of pages for similar errors, but I couldn't find this same issue.

As this is the only database in the mysql instance I have simply given drupal the admin user/password, so I don't see how this could be a permissions issue.

I have not made any modifications to any files, other than copying default.settings.php -> settings.php.

What am I doing wrong here?

As per another user's request, I tried upgrading to drupal 8.0.6 and am now getting a 500 internal server error, with the following in the logs:

[Fri Apr 08 14:11:53.710451 2016] [core:error] [pid 54807:tid 34478458880] [client 172.17.240.6:45115] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

I've posted another question to resolve this issue: https://drupal.stackexchange.com/questions/197400/500-server-error

This is weird, since exactly in 8.0.5 is fixed that kind of error:

#2646410 by claudiu.cristea, dawehner: Container cannot be saved to cache

Can you try Drupal 8.0.6 maybe? Your MariaDB as well as PHP seem to be compatible with D8 requirements (your MariaDB is based on 5.5 plus Mysql 5.6 stuff).


Get the highest Matched output in result I have a table like this

Now my requirement is like below:-

I have to fetch all Content ID related to User Id-31. Here the matching content id are 225,178. I am able to retrieve this. Now I want to do the following:-

I want to get all user id whose Content ID matches with Content ID of 31 in Decreasing order. It means that if all content id matches then it will appear first otherwise  it will appear last. Here User ID 20 matches 2 times,User Id 19 matches 1, User ID 1 also matches 1 times.  So Result set will be User ID 20,19,1. Now I want to achieve this in Mysql as well as db_select in Drupal 7.

It's something like this ... Since I dont have your exact table in my database it could be slightly wrong. But this is 80% or 99% what you're asking.

$query = db_select('my_table', 't')
    ->fields('t', array('UserID'))
    ->condition('contentID', 31)
    ->groupBy('UserID')
    ->orderBy(2, 'DESC');
$query->addExpression('COUNT(t.UserID) AS num_items');
$results = $query->execute();

// dpm() is in the Devel module.
foreach ($results as $record) { dpm($record); }

EDIT:

The final query that worked was:

$query = db_select('flag_content','fcnt')
->fields('fcnt', array('uid'))
->condition('fcnt.content_id', array(178,225), 'IN')
->groupBy('fcnt.uid')
->orderBy('num_items', 'DESC');
$query->addExpression('COUNT(*)' , 'num_items');


Creating menus from terms i want to make a complicated tabs block for terms  (i usually views and quick tabs for this and it works great) . in this block i want a main tabs bar when i click on one of it it shows the content that have that term or any of its chlidren term, also i want a second tabs bar to show, if the main term have any children term and put in that bar the lev.1 children for the main term ,so if i click on it it shows the term's content and any of its children term content to ,i hope i described it well ,  check the image for more understanding

my question is : is that possible using views or any other modules or should i create my own module -which i allready started creating but its taking a long time - ??

thanks in advance

If I understand your question, I think you want the Taxonomy Menu module:

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

However, the last time I did this, I wrote my own module.  Essentially, I wired up taxonomy hooks to call menu_link_save() for new terms, and menu_link_delete() when terms were deleted.  This is a rather complicated process.  If you go this route, I would study the submit handlers for the menu module to see how everything works.  You also need to study the taxonomy API to see how to walk trees when you have a hierarchical vocabulary.


What's the difference between drupalSettings and settings parameter in behaviors? When having the need to pass settings or parameters from PHP to JavaScript, i always used to do so according to a blog post from Acquia - create a dependency to drupalSettings, attach the settings on the PHP side and use the drupalSettings variable on the JS side.

my_module.libraries.yml:

my_lib:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

my_module.module:

function my_module_page_attachments(&$attachments) {
    $attachments['#attached']['drupalSettings']['my_module']['my_property'] = 'abc';
}

Finally my_javascript.js:

(function ($,Drupal,drupalSettings) {
  Drupal.behaviors.test = {
    attach: function(context,settings) {
      console.log(drupalSettings.my_module.my_property); // would output 'abc';
    }
  }
})(jQuery,Drupal,drupalSettings);

However, I came to a sudden realization that the settings variable of my attach function already contains exactly the same variable:

(function ($,Drupal) {
  Drupal.behaviors.test = {
    attach: function(context,settings) {
      console.log(settings.my_module.my_property); // would also output 'abc';
    }
  }
})(jQuery,Drupal);

So why is there even a separate way to load drupalSettings and it's proposed in every guide I found, when in fact we already have a variable containing our settings, so we don't need to mention the global drupalSettings variable?

Thanks for your clarification!

Update 1

I found out in my test behavior that the variable settings is a reference to drupalSettings, so if you modify one of the two, the other also has the direct changes, and they are therefore equal.

Drupal.behaviors.anotherTest = {
  attach: function(context,settings) {
    console.log(settings == drupalSettings); // outputs true
    drupalSettings.testproperty = 'abc';
    console.log(settings == drupalSettings); // still true
    console.log(settings.testproperty); //  outputs 'abc'
    // works also the other way around
    settings.testproperty = 'def';
    console.log(drupalSettings.testproperty); // outputs 'def' now
  }
}

This applies to every call of my behavior. On my rather complex project, the behavior gets called 12 times, and while the context variable changes on every call, settings is always equal to drupalSettings.

The thing to remember is that behaviors can fire both on page load and on AJAX requests.

Upon page load, the global and the parameter passed to the behavior should be identical.

During the course of page interaction, and depending on the AJAX commands, the settings parameter may be different when it fires.

When writing behaviors in Javascript, always use both the jQuery context to scope selectors, and the settings variable that get passed in to be safe and future proof your code even if you aren't using AJAX.


How to create a custom table containing data to be rendered using the Views module I have a module which is pulling in some remote data. this is only temporary as long as page is opened i dnt want to store the data on my drupal site. is there a way i can create a custom data table in order to render my data results using the views module.
i looked into hook_views_data()but it seems this only works with database table in the drupal system

Data module helps you model, manage and query related sets of tables.
The Data module provides

an API for dynamically allocating tables for single-row records.
an API for insert/update/delete operations and describing how tables join to each other.
automatic views integration.
a way to export table definitions to code.

Also next patch in "Describe and use external database tables using Data." allow use external DB tables to show on Views.


Drupal 7.22 and Templating I am developing a site using drupal. I need to create a template file for a specific page.
For instance this is my site url http://www.dev.com. I created a basic page called documents which URL path settings alias is docs. So what I want to do is that whenever the user clicks on http://www.dev.com/docs drupal should use a specific template file. For that matter I create a tpl file called page--docs.tpl.php and put it inside my theme folder. However drupal seems not loading that file.

PLease assist me if I am missing something.

You need to use the non-aliased path for the template name.

For example if you are dealing with node 1 (node ID = 1) try naming the file page--node--1.tpl.php and clearing the cache again.

For more info see: https://drupal.org/node/1089656#page-suggestion

If you don't know what the node id is, go to the node edit page and it will be in the url /node/NODEID/edit.


How to change error message of the webform Possible Duplicate:
  preprocess_node_webform is not working

How can I change the default error message of the webform ? For example "The name field is required"  to  "Please enter your name". Where should I make changes to achieve this ?


Should views search specific caching skip preprocess? Problem

I have a view powered by the Search API, which uses the views inbuilt caching - "Search Specific" in order to provide better performance.

However I also run a number of theming alterations in:

theme_preprocess_views_view_unformatted

However this code appears to be skipped when the views caching kicks in. Is this by design or an I encountering a bug? If it's not, how have people gotten around this sort of thing before?

Re-creation

Clear all caches Load page - Code runs correctly
Refresh the page a number of times usually between 2 & 5
Refresh the page - Code is skipped

I've been testing if the code is skipped by including:

function theme_preprocess_views_view(&$vars) {
  ...
  watchdog('test', 'This chunk of code has just run');
  ...
}

I was misusing theme_preprocess_views_view_unformatted.

I'm running views caching, search specific (I think this may also apply to time specific) in order to cache the results of the view.

This caches the HTML of the view and means that the entire view creation, render and theming steps are skipped. When the view calls the search the correct HTML is returned.

However they do have to be run originally to build the cache. (For some reason it kicks in after a random number of refreshes? Perhaps there's simply a delay on creating the cache.)

I was using watchdog to log when the code runs and so obviously this only runs until the cache is created. This won't be an issue if everything you're doing in
theme_preprocess_views_view_unformatted alters the HTML because that will be cached the first time it happens. However I was using it to add text to header based on the results of the view, which obviously didn't work.

This was possibly muddled by the fact that I run Varnish & Authcache on my live environment so I think this would cache the initial version (before the search cache is built) and thus stop me from re-creating the bug on my live version.

Make sure you're aware of all your caches and how they run!


How to make direct editing of cck imagefield? How to make direct editing of cck imagefield on a user profile node. I want to add link → edit profile photo, which will directly allowes you to change the image. Is that possible?

Is it possible: Yes.
Is there a module for it: I don't think so.

What you need to do, is to display the form for the CCK field. Since much of the CCK logic is wired into the node form, the easiest thing to do, would be to display the entire form, and hide everything but the field you want to let users change.


Webform Conditional is not firing when using a hidden field I am trying to hide/show a field from the user based on a hidden field, whos value is set from the server. I have set up a conditional so that if the hidden field 'X' value is 'a', then field 'Y' will be shown.

However, field 'Y' is being shown no matter what. I have tried reversing the logic (if hidden field 'X' value is not 'a', then hide 'Y'), but that did not change anything.

After much testing, it seems as though the conditionals of Webform will not actually do anything based on the value of a type 'Hidden' field. If I create the same logic with a 'Textfield' instead, the conditional fires as expected.

Is this a bug? Am I doing something wrong? The end result I am trying to accomplish is to hide or show a field based on an input that the user cannot change themselves.

Following up on my response above, things like FAPI autocomplete_path and as your seeing webform conditional (i think) use the States API. Which is a limited version of scriptable javascript API from within Drupal7.

Drupal does ship with jQuery UI built in. And you can make direct usage of jQuery to alter/modify forms directly using drupal core components -- such as the bundle standard jquery packages that come with Drupal 7. Want a working jqueryui autocomplete example as an example -- here's 1 in Russian (Google translate works well here):

http://serho.ru/notes/raznoe/jquery-ui-autocomplete-widget-v-forme-drupal-7

I realize your request may be a non-coding module only solution; but such modules and APIs basically have limits as you've seen. There are pieces of drupal core that exist to let you homegrow your own solution.


How to display blocks depending on the logged in user? How can I display blocks depending on the logged in user?

Let's say I have a Block1 and Block2. When user1 is logged in, that user should only see Block1, but user2 should only see Block2

I found the Logic Block module, but it doesn't seem to work for what I'm trying to do.

You could go to blocks setting and there are Roles tab.
If you check "anonymous user" - this block will visible only for not loggined user. If you check " authenticated user" - block will be visible loggined user.


Regular Drupal 7 site users do not see new tabs added by hook_menu_local_tasks_alter I used hook_menu_local_tasks_alter to add new tab items for node pages like so:

function custom_module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if (arg(0) == 'admin' || arg(0) != 'node') { return; }

  $href='user/'.arg(1).'/hobbies';
  $data['tabs'][0]['output'][] = array(
    '#theme' => 'menu_local_task',
    '#link' => array(
      'title' => t('Hobbies'),
      'href' => $href,
    ),
  );
  $href='user/'.arg(1).'/events';
  $data['tabs'][0]['output'][] = array(
    '#theme' => 'menu_local_task',
    '#link' => array(
      'title' => t('Events'),
      'href' => $href,
    ),
  );

However while admin can see the new tabs, regular users (Drupal 7) do not. Adding '#access' => TRUE, to item array does not help as hook_menu_local_tasks_alter doesn't have options for access argument.

And they appear normally if users are given node edit permission.

How can I make access to these new tabs without giving users permission to edit their nodes?

You have to use hook_permission

So in your module file something like this will do the job. (taken from the hook's page).

function hook_permission() {
 return array(
  'administer my module' => array(
  'title' => t('Administer my module'),
  'description' => t('Perform administration tasks for my module.'),
  ),
 );
}

When you do that you will get a new entry in your permissions page (admin/people/permissions). Enable that for the anonymous users and it will show up ok.


Simple key => value array with QueryInterface I'm looking at building a simple key => value array with a certain type of node I have in order to generate a select list in a form.

The thing is that I have thousands of nodes of this type and the page takes forever to load with the current code I have.

Is there a way to load only certain fields using the QueryInterface in order to cut on loading times? Is there a more efficient way to do this?

$query = \Drupal::entityQuery('node')
  ->condition('type', 'product')
  ->condition('status', 1)
;

$nids = $query->execute();

$nodeStorage = \Drupal::entityTypeManager()->getStorage('node');

// Load multiple nodes
$nodes = $nodeStorage->loadMultiple($nids);

$list = array();

foreach ($nodes as $node) {
  $list[$node->field_code->value] = $node->title->value . ' (' . $node->field_code->value . ')';
}

The only way I know to do this is similar to what @Ivan Jaros mentions in the comment above. That is to use a Database service instead of EntityQuery service. There is a handy method on the query Statement, fetchAllKeyed, that I use all of the time in Drupal 7.

$database = \Drupal::service('database');
$query = $database->select('node', 'n');
$query->join('node_field_data', 'nfd', 'n.nid = n.nfd.nid');
$query
  ->fields('n', ['nid']),
  ->fields('nfd', ['title'])
  ->condition('n.type', 'product')
  ->condition('nfd.status', 1)
  ->execute()
  ->fetchAllKeyed();

Unfortunately this has drawbacks:

Multilingual - you need to do this manually in the query above.
Probably not going to work well with non-SQL drivers.
Might run into performance issues still because the data is not cached.


Do not import configurations if already exists I have built a custom module and there are two configuration files in config/install directory of my module. When the module is installed the configurations are installed correctly.
When I uninstall the module and try to reinstall it, I get the error that that the `

  fields already exist in the database

These fields are defined in the configuration files and I want that they should be installed only if they not exist.

`

Move them to config/optional instead.

In that case, they will only be installed if they don't exist yet and if all their dependencies are met.


Creating fielded entities in a module: how to ensure unique field names? I created some entities with the Entity Construction Kit, exported them with Features and proceeded to build a module upon that.

I had been pretty much ignoring field names, then realised I'd used really generic names for my fielded entities. Oops.

What's the best way to ensure names are not going to crash into the namespace of something else [in future]?

Is it module_name_entity_name_field_fieldname?

And if so, is there any problem with really long field names (and presumably, therefore even longer column names in the tables)? Is there a limit?

EDIT: yes, there seems to be a 32 character limit for field names. So how can you be sure of a unique field name?

The only way to be sure you have a unique field name is to test on creation whether the same field already exists.

As you have realised, this is a problem when deploying your fields as a feature, as you do not know what environment your fields will be deployed in. Unfortunately Features does not provide you with a way to rename the fields when a feature is first enabled.

This is something you could implement yourself ; it should be possible to do this in a way that doesn't stop you from automatically re-creating the feature. Here is an idea about how this could be done:

(1) Name all your fields prefix_fieldname (I will assume you used 'mymodpref' for the prefix) and ensure they are no more than (say) 30 characters ;

(2) In your module's .install file, implement hook_install such that you find a safe field prefix that will make your fields unique. For instance:

function mymodule_install() {
  $prefix = 'mymodpref';
  $prefix_index = $prefix;
  $index = 1;
  $found_unique = FALSE:
  while (!$found_unique) {
    $c = db_query("
      SELECT COUNT(*)
        FROM {field_config}
       WHERE field_name LIKE :prefix",
    array(':prefix' => $prefix . '_%')
    )->fetchField();
    if ($c > 0) {
      $prefix_index = $prefix . $index;
      $index++;
    } else {
      $found_unique = TRUE;
    }
  }
  if (strlen($index) > 2) {
    // Our fields are up to 30 characters, so we can't have an index
    // of more than 2 characters. If this happens we're in trouble -
    // add some code here to tell the user we can't install the module.
  } else {
    variable_set('mymodule_field_prefix', $prefix_index);
  }
}

(3) In you feature's main module file, add an implementation of hook_field_default_fields_alter which allows you to change the default field definitions, and rename them with the right prefix :

function mymodule_field_default_fields_alter(&$fields) {
  $prefix = variable_get('mymodule_field_prefix', 'mymodpref_');
  $new_fields = array();
  foreach ($fields as $key => $field_info) {
    // Replace 'myentity' and 'mybundle' accordingly
    if (strpos($key, 'myentity-mybundle-') === 0) {
      $new_field_name = $prefix . '_' . $fied_info['field_config']['field_name'];
      $field_info['field_config']['field_name'] = $new_field_name;
      $field_info['field_instance']['field_name'] = $new_field_name;
      unset($fields[$key]);
      $new_fields['myentity-mybundle-' . $new_field_name] = $field_info;
    }
  }
  $fields = array_merge($fields, $new_fields);
}


Stop Drupal from redirecting to "Reset Password" on user account activation I have a Drupal dev site where users register, then get sent an email with a link that they need to click in order to verify the account. The issue is that link directs them to a page with the title being "Reset Password" (but it doesn't actually enforce a password change). How do I change the page that the user is directed to when activating their account? It shouldn't be enforcing this.

I am also using the https://drupal.org/project/logintoboggan module to improve the registration process, and perhaps this is causing the issue? I am using the "Set a password" option on the plugin to force users to create a password when creating an account, so therefore the registration process should not be enforcing the user to then reset their password.

Go to: admin/config/people/accounts

Edit: Welcome (no approval required) Email

Replace "[user:one-time-login-url]" with "[user:validate-url]"

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


Pathauto like pattern setting for creating menu link titles Pathauto is great, in that it allows you to set the URL alias of a node to some pattern like '[node:menu-link:parent:url:path]/[node:title]-DEV' for DEV content type.

I am trying to build a single menu containing menu links for two content types. There is typically a node titled: nodecontent for each content type, then with pathauto we set the URL for the DEV content to be nodecontent-DEV by using the above pattern. It allows us to append a string, which is great.

I cannot figure out how to do this dynamically for menu links though. Since the only automatic action Drupal does is fill in the title for 'Menu link title'.

It would be great if I could append -DEV to each menu link (for that content type), so in one menu I could have:
Country>State>City and Country>State>City-DEV.

You could use the Automatic Node Titles module to create the titles including the DEV string, which depending on your other settings could appear in the menu:

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

EDIT

You could also create a simple module to change the title of the nodes for the DEV content type:

Custom Node Title

  custom_node_title.info

name = Custom Title (DEV)
core = 7.x
description = Appends appropriate titles with DEV
package = custom

  custom_node_title.module

<?php
/**
*   Custom Node Title Module
**/

function custom_node_title_node_presave($node)
{
    /* only run if node type is correct and '-DEV' is not found in title to prevent duplication */
    if($node->type == 'article' && strpos($node->title, '-DEV') === false)
    {
        $node->title .= '-DEV'; /* add '-DEV' to title */
        $node->menu['link_title'] = $node->title; /* reset menu link to new title */
    }
}

In this example, it changes the title of an Article content type to include -DEV at the end.


How to add a language dropdown switcher to top panel? I try to create a multilingual (3 languages, incl. English) website, and I’d like to create a language dropdown switcher (ideally in the top panel/menu). I tried to accomplish this using Flags, and Language Dropdown Switcher, but couldn’t display it though. It presume, I just don’t know how to add it in a block; although I could find the Language Dropdown Switcher in the block and add it there, but it did not show up. I could set the Flags up in the Configuration, but I did not find it in the blocks.

How do I install/enable/place a language dropdown switcher (preferably Flags, but this is not a condition)? It would be awesome (again: this is not necessary) if this switcher would be in the top panel and that it would contain country flags only (not the language as text).

Drupal 8.5.6 with configuration translation, content translation, interface translation and language enabled and the particular languages are already added in the configuration.

I believe Flags does not integrate with Language switcher dropdown (contrib module) it only integrates with the core language switcher block

Here is some alternatives

1. Language Switcher Dropdown + languageicons

Install both modules
Go to config > regional and language > language icons and choose

  Icon placement
    Before link
    After link
    Replace link

Go to Structure > block layout add Language dropdown switcher block to your desired region

2. Bootstrap Languages

Compatible with bootstrap based themes only

Install module
Go to Structure > block layout add Bootstrap Language switcher block to your desired region

3. dropdown_language

With this module icons have to be setup manually using css


Services 3 Output alter hook Are there any hooks to alter the Services modules output.
For eg : If I get a result like this for a file object.

{
  "fid": "132",
  "uri": "public:\/\/512dab4918036.jpg",
  "filename": "512dab4918036.jpg",
  "filemime": "image\/jpeg",
  "uid": "1",
  "status": 1,
  "timestamp": 1361947464,
  "filesize": 2521,
}

I want to limit it for users with certain roles.

I am looking for this as I have made many services resource manually so I don't want to edit them all and simply use the output alter hook to do something.

Is it possible ?

The available hooks for Services are documented in the api docs for services

You probably want hook_services_request_postprocess_alter($controller, $args, $result); which allows you to change the array of $result any way you want.


Injecting database values with a non-Drupal application I have a D7 site which I would like to allow a non-drupal application to be able to inject values into the database. Specifically, I would like to upload a file to a specific field and then associated that field entry with a predetermined user.

The external program is not running PHP either, so it's intended to be an entirely SQL based approach, and not touch Drupal code at all.

Is there a recommended or useful approach to this, for a way to extract the Schema from Drupal, or a CMS-agnostic method of tracking database updates / inserts?

Thanks!

One method would be to use the Services module to create a web service that the external program could then communicate with.


Remove Commerce Payment Method Pane? So for my project there will only ever be one payment method with is Credit Card by Sage Pay.

Essentially I want to remove the pane where you select a payment method and
set the payment method always as Sage Pay. I want to hide payment selection from the user.

This way after entering user details the user can go straight to the payment gateway redirection. How would I go about this?

You'll need a custom module with the following function:

function yourmodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
 // Do something here
}

You'll probably want to add a dpm($form); (assuming you have Devel installed) to get the exact item, but the array you'll probably want to target is:
$form['commerce_payment']['payment_method'] by perhaps setting the #access to FALSE if you only have one choice. In other words, add the following:
$form['commerce_payment']['payment_method']['#access'] = FALSE;

Be sure to clear the cache after adding this function.


Attributes in table in custom content type form I am creating a custom content type named "Invoice".
 This content type is having attributes like Company Name (entity reference to company content type), Bill details, tax details and calculations.
Can you please suggest how can I get elements/attributes like shown in an image in custom content type add new content form?

You will need to override the node form template for your invoice content type with a custom template in your theme. More info -> Theming Node Forms in Drupal 7 and here

In your template you'd build a layout for your fields and output form fields in place like this

<?php print drupal_render($form['fieldname']);?>


Change commerce price I've setup another commerce price field which I want to use instead of 'default' commerce_price field (under certain conditions). hook_commerce_product_calculate_sell_price_line_item_alter() does the job on full product page but it doesn't work 'globally'. In shopping cart / order page   price goes back to default commerce_price field. Actually it's acting strange because when I add product to the shopping cart it shows amended price but it goes back to default price once page is refreshed...

p.s. I can't use Rules to change price.

Unfortunately using rules is the only option to dynamically alter a product's price in Commerce 1.x. From the 2.0 roadmap:

  In Commerce 2.x, we should ensure that our modules define robust internal APIs that are then used by forms, Rules actions, etc. as opposed to embedding functionality into these systems' related callbacks. Most notably, we should seek to make price manipulation and price component management much easier as we open up the sell price calculation process to direct manipulation in module code (as opposed to strictly using Rules) when sell price pre-calculation is disabled.

emphasis mine.


I don't find something similar to drush field-create in Drush 9 I'm looking for a similar command drush field-create with Drush 9, I only find drush generate field but when I execut it I don't get nothing, also if I try drush generate field --help  I get:

Too many arguments, expected arguments "command" "command_name".

There is any way to get drush field-create running with Drush 9?

Thanks.

drush field-create has not been ported to Drush 9.

You can install Drupal console and use drupal generate:plugin:field instead.


Where is the Boost cached files? I use Drupal 7.9 and Boost 7.x-1.x-dev

Last month i disabled Boost. I used only core caching with the all options are enabled.
And min cache 6 hours, max cache 1 day.

Then without chancing core cache settings i enabled Boost module.
I didn't change any setting.
- Cache specific pages: All pages
- Cache HTML output, usually a webpage of type text/html: Enabled, 6 hours, 1 day
- Root cache directory: cache
- Normal cache directory: normal

But the "html" files aren't saved to my public html folder.
I have this folder:
"/public_html/cache/normal/www.example.com"

But this folder only has a ".htaccess" file.

I get 25 hits in one hour, but there is no html file inside these folders.

What would be the problem.
Thank you for help.

cache/normal/www.example.com is indeed where Boost would store your cached files.

Have you added the proper Boost directives to your public_html/.htaccess? It sometimes takes a bit of fiddling to get them right - you need to experiment by accessing the site as an anonymous user and viewing source on the returned page to see if the Boost signature is in there.


Creating and updateable block on home page of site I have a 'featured resource' block on the home page of my site. I'd like my very non-technical folks to be able to update this block with a new node every week. Note that it would just display the teaser of the node, with a 'read more' link.

Ideally, it would be easy for them to do this (for example, by just checking a box on the node creation/edit page to add it to the featured resource block).

Anyone have recommendations for the best/easiest way to do this?

Drupal allows a node to be marked as "Promoted to front page" when editing the page (it's at the bottom, under "Publishing options").
You can make your block from a View

Enable the Views module.
Add a new view admin/structure/views/add
Create a block (untick create a page)
Click "Continue & edit"
Add a filter by "Promoted to front page"
Alter "Use pager" to display 1 item.
You should already have a sort by post date.
Save changes.
Add the block to your home page (it sounds like you already know how to do this, but ask if not).

This view will show the most recent item with promoted to front page set.


How does a menu item get hidden with the Domain module? I have a node that is restricted to site dev2. In my menu, I have a link to that node. On dev1 site, the link doesn't show up.

I have created a hook for node_access that returns NODE_ACCESS_ALLOW  for the view operation. Shouldn't it show up in the menu for both sites even though it is restricted to dev2 by the Domain module?

I did a project this summer that used Domain Access to split a site into desktop and mobile versions of the website.  The client wanted to be able to target pieces of content for the desktop, mobile, or both.

If a piece of content is in a menu, the the domain rules will decide if that piece of content is available, which is what you are seeing.  This is done with the standard node_access methods, which grant permissions rather than take them away.

I think you have a two options here.

I think proper thing you should do it to send the node to all or multiple affiliates, which should be an option when you edit the node.

If you want to go the node_access route, then I suspect you need to clear caches and also rebuild the node permissions.  I totally forget where this option is in the UI, but you essentially need to call node_access_rebuild.  The easiest way is probably with drush

drush php-eval 'node_access_rebuild();'

Just keep in mind that the link will appear in the menu, but the node will also be viewable.  The two go hand in hand.


Drupal module to make html pages of all nodes automatically I am looking for a solution / module which can create the whole site in HTML .

So every time the user does content changes, he can click on a button, it will create the html for that node only or the whole site and syncs it to an FTP or same hosting.

I do not want to use caching or any other technique to speed up the site.

is it possible with drupal ?
thanks

The Boost module is the closest thing to 'Drupal as a static generator'.

  Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic.

EDIT: You could also look at the Static module. However it doesn't provide a mechanism to get the files onto a server, you would need to set that up separately.


Alternative to the Inline module I've been using inline images with the Inline module to display the attached image like [inline:dreamspark.jpg=DreamSpark], but this module doesn't have a Drupal 7 version, yet.

Is there any alternative to this module? I have many nodes using this module.

There is a Drupal 7 version of that module, it's just in dev at the moment.

I think it's highly unlikely someone else will be developing a competing module along side the development of this one.

I'd advise downloading and installing the dev version of the module, if you get any errors report them back to the issue queue to help push it along.

You can actually check the current issue queue to see if there are any known problems that may stop you being able to use this in your new site...at least you'll know as early as possible.


Where does the menu trail get added into the $data parameter in pathauto_tokens()? I have seen this post: where does $data come from in hook_tokens?, but that did not help me answer my question, maybe it could've but there's no way for me to interact with that post.

I am working in Drupal 8.5, using pathauto 8.x-1.1.

I am looking at pathauto.tokens.inc, here is the code for pathauto's hook_tokens():

function pathauto_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();

  if ($type == 'array' && !empty($data['array'])) {
    $array = $data['array'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'join-path':
          $values = array();
          foreach (token_element_children($array) as $key) {
            $value = is_array($array[$key]) ? render($array[$key]) : (string) $array[$key];
            $value = \Drupal::service('pathauto.alias_cleaner')->cleanString($value, $options);
            $values[] = $value;
          }
          $replacements[$original] = implode('/', $values);
          break;
      }
    }
  }

  return $replacements;
}

I can't seem to find how the menu trail makes it into the $data parameter. I can see the menu trail in $data when I set a breakpoint at array = data['array'].

My ultimate goal is to figure out why pages with a menu_position rule associated with them are not getting the joined-path history in their url alias.

Token resolving is recursive. The caller of replace() is responsible for providing the data.

As far as this token is considered, it's not an active trail, it's just an array with strings that is combined together.

Your token probably looks something like [node:menu-link:parents:join-path]. If this doesn't receive the right parents then you need to look at where the parents are fetched and passed on, which is in token.module: https://cgit.drupalcode.org/token/tree/token.tokens.inc#n721

And if it is a different token then you need to look up whatever intermediate tokens you are using


Edit a node using AJAX I'm loading the edit node form in a block and I want to use Ajax to save the node.

class MyBLockNameBlock extends BlockBase{

  public function build() {
    //I find the $nid i want to display

    $entity = Node::load($nid);
    $form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
      'wrapper' => $wrapper_id,
      'callback' => '::ajaxCallback',
     ],
   ];

   $block['form'] = $form;
   $block['#markup'] = $this->t('
Project Plan
');
   return $block;

  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if($form_state->hasAnyErrors()){
      return $form;
    }
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
     return $form;
  }
}

But it doesn't work.
If I change the $form['actions']['submit'] to

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes'   =>array('class' => array('btn btn-info use-ajax-submit')),
  '#ajax' => [
    'wrapper' => $wrapper_id,
    'callback' => '::ajaxCallback',
  ],
];

The Ajax works but it doesn't validate the form.
Should I create the validation by myself for each field?

Also I tried ajax_form_entity module but even if the ajax works, reloads the form, doesn't clear the fields after submission and still doesn't validate.

Also I need an extra handler when the user clicks the submit button in order to update a field from an other form.

Any idea?

You cannot add elements to the form outside of the form definition. You are adding your form elements in your block class, which is why it's not working as you expect. If you want to alter the entity form, you'll need to use hook_form_alter() and add your ajax there.


Show related content. Search results? I am working on an Equipment Checkout system using Drupal 7, MERCI, views, panels, rules, and many other modules. I am working for a community college in Oregon. I am upgrading features on an already running system that was built by myself with the help of a few other people last year. The system is offline for the summer.

One of the features that I am trying to implement is that when we pull up a customer account, we also see content related to the customer blog posts, reservations, and some custom content types.

I have created a block called 'Customer History' on the customer view for the information to be displayed.

So now I need to figure out how to get the content into that block.

I'm thinking that I could somehow do a search for the customers name and display results in the block. What do you think? Is this a good way to go?

Any help would be great thank you.

Views is probably your best option, using a contextual filter, and various Views Blocks

If for example the url was www.mysite.com/user/12/profile, you could list all of any number of content types where the user id matches 12.

The specific answer depends on the structure however. If you include that information, I will update this answer with more specific direction.

EDIT 1:

create a separate view for each content type you want visible on the user's page
for each, set it as a BLOCK, not a page, and set the fields and order, etc as appropriate
set a contextual filter - this will depend on your structure, but I will show one as an example and you should be able to extrapolate. Contextual Filter->Content:Author uid
Contextual Filter, When not Available -> Provide Default Value, Raw Value from URL, Path Component 2 (for /user/12/*)
go to admin/structure/blocks and you should see the new views blocks. set them to only show on user/* for example to show in the profile pages, and place the blocks in the appropriate region


How to add a checkbox to a Content Type and act if box is set to true or yes Module name, 'text_grabber'
Content Type, 'node' name 'essay'
**When I enable this module, I want a checkbox to be added to the ~/node/add/essay page. So when an user adds a new essay to the site they can select yes on the checkbox that will enable the text_grabber module for that specific essay.
If the user selects yes, I want to be able to add a js script specific to that essay before it is saved. This will allow me to execute code if event is triggered. Is this possible.

I think I can add a checkbox using an .install like mentioned here: Using field_create_field and field_create_instance to add a checkbox to a content type

but the other part, what can I do?? In layman's terms, I am not tremendously experienced.

You can add a field in a number of ways:

Edit the content type and add a Boolean field through the UI
In your .install file as you already mentioned
Using hook_form_alter() to add a #checkbox.

If you used option 1 or 2 you can pick up whether the field is checked or not using hook_node_presave() or hook_node_update().

If you used option 3 you'll probably need to add a #submit value to the form which calls a custom function in your module.


author profile info in a content type Need to print the profile fields of author of a node in a particular  content type

I am using support tickets for my home owners association website. where in users can login in and create tickets for house keeping, electrical etc. Support tickets modules provides a content type support ticket which is been used for ticket creation. I would like to add profile fields to above content type  example:apartment no, contact nos of the user who creates the ticket node so that the support team looking at the ticket know the contact info.

I am presently on D7
Thanks

Use Views module and make a content view in relation with Content authored.


How to allow users have only alphabetical "username"? I suddenly realized that username can be any character after seeing someone just made his or her account in Japanese characters. I don't really have a problem with that but just would like to let them register only with alphabetical characters to keep the things tidy. Is there anyway to do this?

Check out the Custom Username Validation module, it seems like it should do exactly what you like.

If not, (In Drupal 6) you can set up "Access Rules" in the administration pages.  Set up multiple access rules to deny usernames that contain undesired symbols.  Access Rules Docs. Unfortunately that would take a lot of time to deny all non-alphabetical characters.

Finally, you could also create a custom module and use hook_form_alter() (or hook_form_FORM_ID_alter()) to change the validation on the username field. Here's a related question on SO: Hook into Drupal registration and validate user info against business logic


Is there a clear separation between user data and Drupal data in the database? Possible Duplicate:
  Deploying content updates from staging server to live server

I am trying to find a solution to the following scenario:

Let's assume a Drupal site is in production. Users create a lot of content everyday.
In development, additional features (content types and others...) and modules are being added to the site.
Comes the day to move the upgraded site to production.
The upgraded site is out of synch with user data in production.

How does one solves this issue? Is there a clean way to perform this? Should one export 'some' databases tables from current production and import them into the upgraded system? If yes which tables?

You might want to look at the Deploy and UUID modules together.


Which cache have to clear to update new hooks? I added a new hook inside a module (hook_cart_commerce_pricecomponent_type_info_alter), which cache have to clear to only update that new hook? I mean i do not want to clear all caches.

Administration menu?
Class registry?
Menu?
Page and else?
Theme registry?
Token registry?
Update data?

To register a new hook, you can clear the following caches:

cache_clear_all('module_implements', 'cache_bootstrap');
cache_clear_all('hook_info', 'cache_bootstrap');

More info: https://api.drupal.org/api/drupal/includes%21module.inc/function/module_implements/7


MySQL 5.1 to MySQL 5.6 update causes php-cgi error: PDO issue? I recently performed a MySQL upgrade on Windows Server 2008R2, moving from MySQL 5.1 to MySQL 5.6.22 (Community Edition). The server is currently using PHP 5.3.0.

Things went just fine for all my WordPress installs (no problems on cutover); however, all my Drupal 7 sites are now generating 500 errors (coming from php-cgi.exe via php5ts.dll from what I can tell).

To address concerns about the broad nature of the question, this is the specific Windows event log message:

  Faulting application name: php-cgi.exe, version: 5.3.0.0, time stamp: 0x4a492a25
  Faulting module name: php5ts.dll, version: 5.3.0.0, time stamp: 0x4a4929bb
  Exception code: 0xc0000005
  Fault offset: 0x0015e1b0
  Faulting process id: 0x7bb4
  Faulting application start time: 0x01d01fa8dec6e9a6
  Faulting application path: C:\PHP\php-cgi.exe
  Faulting module path: C:\PHP\php5ts.dll
  Report Id: 2e661541-8b9c-11e4-a303-001b210e0a6a

I've checked database credentials, time zone defaults, and haven't changed IIS settings, folder permissions, or anything of that nature.

The one difference that stands out is that Drupal uses PDO for access, and I'm wondering if there is a potential issue there with the version being used, since all these sites worked fine with MySQL 5.1.

PDO seems to be showing version 5.0.5-dev (rev 1.3.2.27).

I can't locate anything that leads to identification, troubleshooting or resolution.

(I'm off to try to replicate with just a simple PDO test.)

Has anybody encountered this and/or have documentation that might help isolate/resolve things?

NOTE: The closest I've come is to somebody using PDO drivers for MSSQL (not MySQL) where there was a faulty Drupal layer on top of PDO. Details here - http://forums.iis.net/t/1181446.aspx?PHP+5+3+8+Problems

UPDATE:

Not PDO...

The following example (with real values) works fine.

$dsn = 'mysql:host=localhost;dbname=DBNAME';
$username = 'USER';
$password = 'PASS';
$options = array();

$dbh = new PDO($dsn, $username, $password, $options);

if ($dbh) {

    $stmt = $dbh->query('SELECT * FROM MYTABLE LIMIT 1');
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    print_r($results);

}
else {
    echo 'Failed.';
}

UPDATE 2:

I have double checked any options set by the prior install of MySQL 5.1 that might not have been carried over. I realize more things are auto-set and defaults might have changed, which could be part of the issue.

The other issue that might come into play is changing the server collation default from utf8 to utf8mb4 ... It looks like Drupal 7 should support this (discussion, in the framework of Drupal 8 goes back to 2011 - https://www.drupal.org/node/1314214). The tables continue to show ut8 collation, so data should be unaffected.

MySQL 5.6 does introduce explicit_defaults_for_timestamp but I haven't been able to find anything implying it should be an issue either (setting 0/1 results in the same error).

As noted above, the whole thing was resolved by pushing the default character set back to utf8 from the incompatible (for Drupal, but not for WordPress) utf8mb4...

Relevant my.ini settings as follows:

[client]

default-character-set = utf8 # not utf8mb4

[mysql]

default-character-set = utf8 # not utf8mb4

[mysqld]

# REF: http://stackoverflow.com/a/24487309/3174018
collation-server = utf8_unicode_ci
character-set-server = utf8 # not utf8mb4


Groups audience list shows NONE in Organic Group module In my drupal site i have implemented the Organic Group module for user group management

Here I have created a number of groups like grp1, grp2 ... .
I have a custom content type as Opinion that has a field Groups audience with FIELD TYPE Entity Reference so that user can able to post the content type and choose group from GROUPS AUDIENCE to which group the post should belong

The issue is when i am adding Opinion by admin dashboard  the groups are showing in the list GROUPS AUDIENCE as  grp1, grp2 ... and posted to that required group

But when the authenticated user want to post that the GROUPS AUDIENCE shows NONE , by which after posting the content it is visible in  Home page but not showing the corresponding group page

I have gone through  this link

Also given the full permission to the Role that assigned to the user . Any guidance will help me a lot.

Thanks

I just changed the following to get my work Admin -> structure -> content type -> custom content type(i.e. Opinion) -> manage fields -> changed the WIDGET name to Select list of the field name having FIELD TYPE as Entity Reference


Using views, how to render a block of father terms with a brief shortlist of child terms? I've a list of taxonomy terms with related subs as follows:

Father 1

child 1.1
child 1.2
child 1.n

Father 2

child 2.1
child 2.2
child 2.n

Father 3

child 3.1
child 3.2
child 3.n

and so on.

I need to put a list of the father followed by the first 5 child elements in a block and put it into homepage.

Now the point is, that after lots of trying, I didn't find a solution about how I can do this.

The only thing that I managed was the selective display of the fathers, but I didn't reach the child in any way. I don't reach the father through a node, or his own term page, because I only need the taxonomy tree iterated in a block containing a list of unformatted columns.

I have already themed all but I'm still not capable of displaying the childs under the father term.

For short, here is a representation of what I'm looking for:

I'm going out of my head because of this, so any help will be greatly appreciated!

If you didn't find better solution you may create one view that will display parent term name and parent tid and second view that will display four children with a contextual filter by parent tid. And using template_preprocess_views_view_field insert view with terms children in the view with parents.

/**
 * Implements hook_preprocess_views_view_field().
 */
 function mymodule_preprocess_views_view_field(&$vars) {
   switch ($vars['view']->name) {
     case 'terms_parents':
       if ($vars['field']->options['id'] == 'tid') {
         $vars['output'] = views_embed_view('children_view', 'display', array($vars['output']));
       }
       break;
   }
}


Content type with Multiple fields reference I am building a website a website which holds date about players and teams. There are two content types Player and Team.
I want it to work like this, when we are adding a team we can add and reference multiple players into it. How can this be achieved?

The simpliest way to do what you like is to use ief module. But i dont sure it works with node reference field type. So you will need to use entity reference as a generic entity reference field.


applyUpdates() is deprecated. Is it really needed in hook_install() anyway? I maintain a contrib module which defines two base fields, but these are not added to any content type on installation, as this is done during admin config. The module has

// Add our base fields to the schema.
  \Drupal::service('entity.definition_update_manager')->applyUpdates();

in it's hook_install() and hook_uninstall().
Now that this function is deprecated in core 8.7 I've tried removing the lines and installing, and it seems to work OK.

So can it be OK to simply remove the calls to applyUpdates() ?
I think there were problems with fields not being deleted in the early days of Drupal 8, but maybe it all works better now.

For info, the change record is https://www.drupal.org/node/3034742

Edit: Config inspector is only partially helpful. The fields show up only after saving the content type form display. After uninstall the fields are still shown, but I think this was the case anyway (there is a Core issue relating to this)

The change record you've linked is about update hooks for already installed modules, not hook_install().

You've never needed applyUpdates() in an install hook. If your custom module is adding a new field, it will be added automatically when the module is enabled, and removed when the module is uninstalled. There was only an issue with base fields containing data, but this is resolved since Drupal 8.5. See this change record: Base fields with existing data can now be uninstalled.


How do I redirect on flag save programmatically? I want to redirect users to a view when they flag a taxonomy term.
This question is about how to use Rules to redirect on flag save.  I want to do this programmatically.
I tried to use hook_form_alter() to add a submit handler with the redirect.  Unfortunately, while flaggings have an edit form that can be targeted by hook_form_alter() (MYMODULE_form_flagging_FLAGTYPE_edit_form_alter()), they do not seem to have a "create" form.
So how can I add a redirect programmatically upon flagging?
EDIT
Based on 4k4's comment I looked at /flag/srs/Entity/Flagging.php:
 *    "form" = {
 *      "add" = "Drupal\flag\Form\FlaggingForm",
 *      "edit" = "Drupal\flag\Form\FlaggingForm",
 *      "delete" = "Drupal\flag\Form\UnflagConfirmForm"

However, when I tried to do a hook_form_alter() with:

function MYMODULE_form_flagging_FLAGGINGTYPE_add_form_alter(&$form, FormStateInterface $form_state, $form_id)
function MYMODULE_form_flagging_add_form_alter(&$form, FormStateInterface $form_state, $form_id)

I could not get either to pick up my code (I rebuilt the cache).

This can be done in hook_entity_presave().
function MYMODULE_flagging_presave(FlaggingInterface $flagging) {
  switch ($flagging->getFlagId()) {
    case 'FLAGTYPE':
      $redirect_url = Url::fromRoute('view.VIEW_MACHINE_NAME.VIEW_DISPLAY_ID')->toString();
      $response = new RedirectResponse($redirect_url);
      $response->send();
     break;
   }
 }


Dynamically display view block based on based on different view filters I have a view as a page layout. That view allows the user to choose from a list of tags to filter content.

What I'm trying to do is - when someone selects one of the tags to filter content, a separate view block is displayed, based on the tag they select from the filter list.

Is there a way to do this?

We did something similar on our site -- on the left hand side we had a list of lesson plans, and when you clicked one, it used AJAX to dynamically update the lesson pane on the right. Sounds basically like what you want.

Here's the set up:

Make a view with both a block and a page, and configure the block so that the two show up on the same page. (example.com/my-view should show the block on the left side and the page on the right side.)

In the block body, he put the list of lessons alongside the following code in <script> tags:

$('.lesson').on('click', function(e) {
   e.preventDefault();
   // loads lesson into the content part of the page
   var contextualFilter = $(this).text(); // get the lesson title from the selection
   var AJAXPromise = AJAXLesson(contextualFilter); // get lesson from server and load into the content part of the page
   AJAXPromise.done(function() {
      // make promise, waiting for ajax call to return before changing URL and sending analytics page view
      window.history.pushState(contextualFilter, "", "http://example.com/my-view/" + SpaceEncodeString(contextualFilter)); // change URL to requested lesson with dashes instead of spaces
   })
});

Where AJAXLesson() is a function that returns a $.ajax({ ... }); object with the lesson plan data.

function AJAXLesson(lessonName) {
   // loads lesson from server
   return $.ajax({
      url: 'http://example.com/views/ajax',
      type: 'post',
      data: {
         view_name: 'myview',
         view_display_id: 'lessons', // this'll be different for you
         view_args: SpaceEncodeString(lessonName), // removes spaces and replaces with dashes
      },
      dataType: 'json',
      success: function(response) {
         if (response[1] !== undefined) {
            document.title = lessonName; // change page title
            $('#block-system-main').html(response[1].data); // CRITICAL: paste lesson in content
         }
      }
   });
}

Your code will look different, but that's the basic concept anyway.


Drupal Commerce Shopping Cart Form Alter I'm trying to use hook_form_FORM_ID_alter() in my theme's template.php file to change the 'Remove' button in the Commerce add to cart form to an image button. To do this I'm using the following code:

function tempestra_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
  foreach($form['edit_delete'] as $item) {
    if($item['#type'] == 'submit') {
      $item['#type'] = 'image_button';
      $item['#src'] = base_path() . drupal_get_path('theme', 'tempestra') . '/images/search.png';
      unset($item['#name']);
      dpm($item);
    }
  }
}

When I look in the array printed by dpm() everything is as it should be, however the HTML for the image button isn't printed.

Thanks in advance.

Simple mistake, you don't change $form but only $item if you did

foreach($form['edit_delete'] as &$item) {

or

foreach($form['edit_delete'] as $key => $item) {
  ...
  $form['edit_delete'][$key] = $item;
}

it should work.


Altering display mode for authoring information I'm trying to deal with authoring info for articles in Drupal 7. I've found the way to hide or unhide it, and that's all I can do. But what I'd need is find a way to display on certainly tagged articles, but hide when that specific tag is not added. Is there any solution for this without coding? CSS is okay, but I know no PHP.

Thank,
cs.

As you prefer css, checkout the module Field Formatter CSS Class

  The Field formatter CSS class module allows you to set any
  text/list/option/taxonomy field to render as CSS class on the node.
  This enables the node author to select predefined CSS styling per
  node.

Also Field Formatter Class

  This module allows site administrators to add classes to the outer
  HTML wrapper for any field display.

Then you can hide your info with css based on this unique class provided by either of these two modules


How to export field's default image in Features I have Image field type and provide Default Image. This default image doesn't seem to be exported by Features. Is there another module that need to be added so the image also exported? Or are there another way or alternative to achieve this?

Try the Default image ft module looks like it is what you need.

Remember when you wanted to featurize that default image for that profile picture? Yeah, that's not possible, because the feature would save a fid in its code, and we all know it's not good to have id's in features. Plus, the website manager might want to change the default profile picture.


Strict case in content URL alias (Pathauto: Leave case the same as source token values)

When I create a node with "Nullam vehicula pharetra" as title, the Pathauto module will create /content/Nullam-vehicula-pharetra as URL alias. But we can browse the same content with a different URL case, such as /content/NULLam-vehicula-pharetra.

How do I make Drupal strict on the URL alias case?

Wikipedia is good example about what I need. Two different case request return different contents:

https://en.wikipedia.org/wiki/Drupal
https://en.wikipedia.org/wiki/DruPal

Even if you don't use pathauto,  Drupal7 can not differentiate case sensitive urls. This 'issue' is not code related,  but it has to be with the database collation. non-binary string comparison are case-insensitive by default.

A solution could be to set the 'alias' columns (menu_router.path, url_alias.alias) to binary (case-sensitive).

Be aware that changing the structure of those two columns in existing sites could result in broken links because paths/alias would have to match base on case.


How to ajaxify simplenews module? I have installed and enabled the simplenews module and I have a newsletter subscribtion block in my website frontpage now.
I would ajaxify the subscribe's button in that block so I googled many websites about that, but I couldn't find any answer about 'How to ajaxify simplenews subscribtion form in drupal 7, any suggestion?

I don't know if you found your answer but I had the same problem and found a solution :

In a hook_form_alter

  if ($form_id == 'simplenews_block_form_' . variable_get('simplenews_id', 23)) {
    $form['submit']['#ajax'] = array(
      'callback' => 'simplenews_block_form_ajax_submit',
      'wrapper' => 'block-simplenews-' . variable_get('simplenews_id', 23),
      'method' => 'replace',
      'effect' => 'fade',
      'progress' => array('type' => 'none'),
    );
    $form['submit']['#executes_submit_callback'] = TRUE;
    unset($form['#submit']);
    unset($form['#validate']);
  }

And then in the ajax submit

/**
 * Ajax callback to reload the image field
 */
function simplenews_block_form_ajax_submit($form, $form_state) {
  $return = '
';
  $return .= '
' . t('Newsletter') . '
';
  $return .= render($form);
  $return .= '
';
  if (!valid_email_address($form_state['values']['mail'])) {
    $return .= '
' . t('The e-mail address is not valid.') . '
';
    return $return;
  }
  else {
    if (module_exists('simplenews')) {
      module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
      $tid = $form['#tid'];
      $account = simplenews_load_user_by_mail($form_state['values']['mail']);
      $confirm = simplenews_require_double_opt_in($tid, $account);
      $subscription = simplenews_subscribe_user($form_state['values']['mail'], $tid, $confirm, 'website');
      $return .= '
' . t('You have been subscribed.') . '
';
      return $return;
    }
  }
}

This will do a simple registration to the database in AJAX. You can adapt depending on what you exactly need.


How to show event title and time in calendar block? I have create a view based on the template. The events are shown up properly as a link in the calendar block:

How to I add also the event name and time (similar to the month page)? i.e.:

Do you mean you would like to add the event name and time to the calendar you have provided on the top? If that's what you're asking, I don't think you can, and that is what the month page is there for. In Views, can you make the month page a block instead and place that wherever you need it?


Custom form with multiple textarea fields How can I create a textarea field in a custom module which has multiple (unlimited) fields? It should be the same result as selecting unlimited amount of values when adding a textarea fields to a content-type.

There is no property in Drupal's Form API to create multi value fields. You have to create that functionality manually. Check this tutorial.

[Edit] the tutorial seems to have a couple errors (e.g. the values entered in names are not inherited as default_value when the form is rebuilt when adding a field). But it can give you a general idea on how do this.


Spliting a node into multiple pages Content type - article. I want to make articles split into multiple pages when the article itself becomes too long.
For example if we have an article "how drupal works" it would be huge :), I want to split it to several pages and at some point you get "continue to page 2 of 10" and then "continue to page 3 of 10" and so on. Hope you got me and can share some ideas.
Thank you in advance!

I suggest  split your text to some part  with jquery and by scrolling you append(may with some effect like fadeIn .... ) another part to main part.
I suggest you achieve this job by jquery (client side solution)


How to create node and reference it in Drupal 7? Possible Duplicate:
  Options for “create and reference”

How can I put a link "Add another item" on a node edit page that would create a new node and reference it at the same parent node ?

Also, I need to put Edit link beside the new created & referenced node.

I found modules like the Popups API and Popups: Add and Reference, but, sadly they are not ported to D7

Thanks for any hints!

http://drupal.org/project/noderefcreate

This one is available for D7, and allows you to create & reference nodes within the create / edit form for another node type. Unlike the popups_reference module, it will only allow you to create the extra nodes with titles (no other fields). You could, however, use this and then write a small custom module that uses hook_form_alter() to redirect the user to the edit forms for newly-created nodes to enter the rest of the information.

Not as nice as popups_reference, but it should work.


Drupal commerce WPS , if user not go back to the site after paypal payment? this is the problem.
The payment used in my site is WPS (With Paypal Business account) so user switch from my site to Paypal site to pay order in cart.

BUT

If User close paypal site after paypal message "Payment complete" and NOT go back in site, the status order stay on "Checkout: Complete". Drupal Commerce has no way of knowing that payment is complete so not send order email and decrease stock.

Is there a way to get around this problem?

I work with drupal commerce kickstart 2 (+ stock module)

Ty for your reply :)

I was experiencing a similar problem - no confirmation emails etc.

Apparently what was causing the problem for me was that I had created a custom Rule that fired "When an ordered is first paid in full"  and updated the order status to "Completed." This custom Rule triggered after the user used PayPal WPS to complete payment. I did this to avoid the confusion of having the default status "Pending" after the the PayPal payment was successful.

For some reason, having this custom Rule there prevented all the Rules that use the trigger "Completing the checkout process" to trigger (these default rules include all the notification emails among other things).

See this posting here for a few cases of other people who ran into this problem: https://drupalcommerce.org/discussions/1150/resolved-completing-checkout-process-not-firing

This issue was resolved (in my case) by just getting rid of the custom Rule.

I'm wondering if this is causing the problem for you too.


Create a block showing the latest of a certain content type I am very new to drupal, so I already apologize if I ask something very simplistic...

I have a site where I would like to add a new block to the front page of the website. This block would show the companies newest available training's. I created the sub-pages of the training's.
My thought process was that I create the sub-pages, then create a new type of content (with the cck) where I can add the new sub-page node names and their links.
I created the new content type with two fields. field_offeringlink and field_offeringtext. Where the the text would be the actuall promotional text and the link directing to the sub-page.
After this I wanted to create a Block that I would place on the front page, showing these two fields.
I couldn't figure out this part...
So how do I make the bloody block show my fields?

OR

If you have a better idea for this whole shannanigan then I am welcome to ideas.

My goal:

Create a dynamic block on the front page, that shows all the latest training's. Under dynamic I mean, that we can add-remove the links from the admin/content menu.

Thanks in advance!

This definitely sounds like a job for views. I could explain how to do this exactly BUT for your own learning you should install views and go through the documentation also as you will thank me in the long run for not explaining exactly how to do it. You do not need to do it the way you have started doing it already, Views will manage everything you have already tried to accomplish with listing articles.

If you want a shortcut without going through the documentation, click this which will give you a thousand tutorials to do what you want to do.


How do I fetch versions of a module compatible with latest core version? I've been using the endpoint https://updates.drupal.org/release-history/[module]/[version], where [module] is the module name and [version] is its version (as 8.x or 7.x). This endpoint, however, doesn't work for 9.x.

For example https://updates.drupal.org/release-history/search_api_solr/8.x works fine but https://updates.drupal.org/release-history/search_api_solr/9.x has nothing, although the module has releases compatible with Drupal 9.

Also, the endpoint for 8.x doesn't return new releases in SEMVER format.

How can I get module releases for Drupal 9? Why aren't SEMVER releases  included?

You can use https://updates.drupal.org/release-history/search_api_solr/current to get the versions either prefixed with 8.x- or without an API compatibility prefix. (The latter is the case for SEMVER versions.)

The output from that URL contains information about this release, for example.

<release>
<name>search_api_solr 4.1.1</name>
<version>4.1.1</version>
<tag>4.1.1</tag>
<status>published</status>
<release_link>https://www.drupal.org/project/search_api_solr/releases/4.1.1</release_link>
<download_link>https://ftp.drupal.org/files/projects/search_api_solr-4.1.1.tar.gz</download_link>
<date>1591714636</date>
<files>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-4.1.1.tar.gz</url>
<archive_type>tar.gz</archive_type>
<md5>7f2dbc01229b118c02c66f4ac210d430</md5>
<size>3207604</size>
<filedate>1591714636</filedate>
</file>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-4.1.1.zip</url>
<archive_type>zip</archive_type>
<md5>511e33c0b0ae47a0bd455109f87d07d1</md5>
<size>3792678</size>
<filedate>1591714636</filedate>
</file>
</files>
<terms>
<term>
<name>Release type</name>
<value>Bug fixes</value>
</term>
</terms>
<security covered="1">Covered by Drupal's security advisory policy</security>
<core_compatibility>^8.8 || ^9</core_compatibility>
</release>

It also contains data for this release. (This shows that the URL doesn't return information only for SEMVER versions.)

<release>
<name>search_api_solr 8.x-3.9</name>
<version>8.x-3.9</version>
<tag>8.x-3.9</tag>
<status>published</status>
<release_link>https://www.drupal.org/project/search_api_solr/releases/8.x-3.9</release_link>
<download_link>https://ftp.drupal.org/files/projects/search_api_solr-8.x-3.9.tar.gz</download_link>
<date>1581700341</date>
<files>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-8.x-3.9.tar.gz</url>
<archive_type>tar.gz</archive_type>
<md5>5050a8e2bd6b4965d414cade7aae3dc8</md5>
<size>1052117</size>
<filedate>1581700341</filedate>
</file>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-8.x-3.9.zip</url>
<archive_type>zip</archive_type>
<md5>140f15134d4e8f2239b96e682186e021</md5>
<size>1278054</size>
<filedate>1581700341</filedate>
</file>
</files>
<terms>
<term>
<name>Release type</name>
<value>Bug fixes</value>
</term>
<term>
<name>Release type</name>
<value>New features</value>
</term>
</terms>
<security covered="1">Covered by Drupal's security advisory policy</security>
<core_compatibility>^8.7.7 || ^9</core_compatibility>
</release>

Unfortunately, there isn't a way to get all the versions that are compatible also with Drupal 9 and not just with Drupal 8, using an updates.drupal.org URL. For that, you need to parse the XML output and filter those versions containing ^9 in the <core_compatibility> tag.

As side note, the all, 8.x, 7.x end-points are considered legacy. I guess that means they could be removed in the future.

References

Update status XML