Newbie - I want to trigger an action when a user creates / updates a profile I would like to trigger an action when a user creates or updates a profile.

What classes should I look for?

I search for the documentation but I didn't understand it much. Can you point me to the right direction?

Thanks a lot

You can use the Rules module for that.

http://drupal.org/project/rules

Create a new triggered rule and set it to fire on event "User account has been created" or "User account has been updated."  If you're using Content Profile, you'd set the event to be "after saving new content" or "after updating new content" and specify the node type was whatever you're using for content profiles.


Unable to set URL alias I am running into a problem with url alias in my drupal 7 installation:

I have a drupal 7 installation which uses a purchased theme. This theme has a portfolio section (in its demo installation with dummy data). I updated the demo installation and changed all sections are required by my project - everything works out fine.

Now the portfolio section has a url called http://<my_drupal_site>/portfolio/4 I need it to be http://<my_drupal_site>/branch-locator. Things I have tried/noticed so far:

I checked the node table, the url_alias table, the admin > content section as well as admin > search > url_alias there is nothing related to portfolio/4. When I open the corresponding block it does not have any body/code in it (I believe that is because it is a block that is part of the theme). When I open the view, I still am not able to find anything where portfolio/4 is mentioned.
The only place where I found portfolio/4 was in menu_router table which had an entry for the same. I updated this record to branch-locator and everything worked fine for a few minutes. Then it showed me a 404 error. When I went back to the menu_router table I found that portfolio/4 was back again in place of branch-locator. (I read somewhere that menu_router table gets cleaned and recreated somehow - not sure how)

So my question is, how can I have portfolio/4 get rendered as branch-locator? Since this is a custom theme I know it will be hard for anyone to give an exact answer how to solve this, but any pointers will be VERY much appreciated!!

P.S - I am not sure what tags to add..If you feel this question can be better tagged, please do so :)

Sounds to me like you just have to add an URL alias for ´portfolio/4´.

Go to Configuration > Search and metadata > URL aliases.
Click "Add alias".
Enter portfolio/4 as "Existing system path" and branch-locator as "Path alias".
Hit Save and it should be ok.

If you want nodes to have a similar path alias, e.g. branch-locator/node-title, you should look into the Pathauto module.

Cheers,


How do you load extra javascript files required for wysiwyg api plugin on node/edit pages? I'm building a plugin using the WYSIWYG API module for Drupal 7 that will add a button to the toolbar of supported editors.

I'm using the hook_wysiwyg_plugin() hook to create a new button on editor toolbar but I need to load a few other javascript files. The hook_wysiwyg_plugin() hook seems to allow you to specify one JS and CSS file.

How can I load extra required javascript files required for the plugin javascript?

I've implemented hook_library() to define a library i.e. js/css files but am unsure how I hook that up to wysiwyg api so that they load on the node/edit screens?

With drupal_add_js:

function yourmodule_preprocess_page(&$vars)
{
  $node = $vars['node'];
  if($node->type == 'yournodetype' AND arg(2) == 'edit')
  {
    drupal_add_js([...]);
  }
}


Reaction rule throws exception when previewing node I have very simple reaction rule condition 'Node is Type' in Drupal 8 (8.5.3) Rules module (8.x-3.0-alpha3):

Data selector: @node.node_route_context:node

(Note: the mentioned issue occurs also for simple value node in the data selector.)

Content types: page

It works well when a node is viewed, but the rule causes crash with the error message The website encountered an unexpected error. Please try again later. when a node is previewed (button 'Preview' is clicked on the node form).

Note: To replicate the issue you should clear the cache on node form before hitting the 'Preview' button to ensure the node isn't served from the Drupal cache in which case Rules aren't fired.

The logged Error Message is:

Drupal\rules\Exception\EvaluationException: The context for node is NULL,
but the context node in rules_node_is_of_type requires a value.

Any hints on better Rules condition to catch the node type, or a patch for Rules?

Thank you!

I have found a workaround.

It seems that this is indeed a bug in the Rules module. The working solution is from here (although it was originally written for different situation, it fits this case as well): https://www.drupal.org/project/rules/issues/2929588#comment-12385257, and basically suggests to use a different condition:

Rule condition: 'Condition: Data comparison'
Data to compare (switched to data selection): node.type.target_id (Content type ID)
Operator (switched to Direct Input mode): ==
Value (switched to Direct Input mode): your_node_type

I hope this helps somebody.


How to parse out links and img src references from body copy? I need to modify links and img references in the body of nodes and comments. MPD already gave me good advice regarding using a script.

Is there an easy way in Drupal or PHP to parse out all the links in the body copy?

It's never easy to do something like this because parsing HTML is a bit hit-and-miss, depending on how well formatted the input is.

I've always found the best way to do it is to load the HTML into a DOMDocument object, loop through and change whatever element attributes/values I need to, then use the DOMDocument to give me the new output.

This is a very rough example but hopefully it'll give you the idea:

$html = '

Blah blah blah

Link Text

';

$doc = new DOMDocument;

// This is a reasonable use of the @ operator as malformed HTML will produce
// a lot of warnings. Please don't shoot me ;)
@$doc->loadHTML($html);

// Get the links.
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
  // Change the value of an attribute based on the current value.
  if ($link->getAttribute('href') == '/some-path') {
    $link->setAttribute('href', '/some-other-path');
  }
}

// Get the images.
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) {
  // Change the value of an attribute based on the current value.
  if ($image->getAttribute('src') == '/some-path.jpg') {
    $image->setAttribute('src', '/some-other-path.jpg');
  }
}

// Get the new HTML
$new_html = $doc->saveHTML();

// Strip out the tags that loadHTML() introduces to get the clean HTML.
$patterns = array("/^\<\!DOCTYPE.*?/si", "!$!si");
$body_text = preg_replace($patterns, '', $new_html);

// Update the node body.
$node->body[$node->language][0]['value'] = $body_text;

EDIT

I knew I'd seen a good question about this on SO; have a look at How to parse and process HTML with PHP? for a good discussion on the subject in general.


Views contextual filter from custom taxonomy field I have added a custom field to taxonomy vocabulary. Now I need to use contextual filter from Views to display items that matches that custom field value in URL, e.g. /my_page/custom_field_value . Is it possible with Drupal 7 and Views 3.x ?

Yes!
If the view is a view of nodes you have to add the relation based on the term field, than you should have the contextual filter available.


views pager showing X results per page I was wondering if anyone knew how to go about adding a drop down or even a list of links to help change the amount of views results per page.

Ideally, when there's a lot of results you would want to be able to choose:

5 per page
10 per page
20 per page
50 per page

A drop down box would be brilliant for this; it is the sort of thing you see on many search forms.

Have a look at Steven Ward's site for a bit of a hacky way to do what you're looking for.


How can I display the content of user profile using the Views module? I want to create a view for displaying the title of the content posted by the user whose profile is being currently shown using the Views module. I am using the following modules:

Views for displaying the profile related content
Panels: for displaying the user profile

How can I do this?

Wow what a coincidence this question was posted for drupal 6 just this morning.

To list content owned by a user you can:

Create a View that lists content
Create a Block Display within that view
Configure a "Contextual filter" for "Content: Author UID" and set its "When the filter value is NOT in the URL" setting to "Provide a default value", then select "User ID from URL" for the "Type".
Place that block on the user profile page using some mechanism for Block placement, like the drupal core block system or the context or panels modules.


Path breadcrumbs Link title for webform submission I have one Webform field call "Name". I use views to retrieve Webform result and edit link. I am using Path breadcrumbs module.

Example:

UserA - Edit
UserB - Edit
UserC - Edit

User A, B, and C had submitted the form. When I click edit, it will goes to their submission form where they can edit the info again.

When I click on the link, I hope breadcrumb will display "Name"

Example:

home > UserA
instead of
home > webform

home > UserB
instead of
home > webform

home > UserC
instead of
home > webform

Name is text. Link is not needed.

Can I add it to breadcrumb link title? How to do that?

I was going to post something with Crumbs, but maybe you can start with something simpler:

I am trying to make this answer useful to different visitors who might have different ideas about their breadcrumb for webform submission pages.

Page access considerations

Do your visitors (those this is meant for) have access to pages like

node/28/submission/1/edit ? (I suppose the answer is yes)
node/28/submission/1 ? (Please check)

With hook_menu_alter()

I'm not sure what this does on a site without Crumbs enabled, but you can give it a try. This will change the page title / navigation title, which I think is used by core for building the breadcrumb.

This means if you had "Submission #1" as part of your breadcrumb, this will replace it with "Submission #2 by NAME".

Consider this code a stub. Especially the $submission->data[1][0]. This just happened to work for me, but might be different for you. devel dpm() is your friend!

/**
 * @param array[] $items
 */
function d7light_menu_alter(&$items) {

  if (!empty($items['node/%webform_menu/submission/%webform_menu_submission'])) {
    /* @see _d7light_webform_submission_title() */
    $items['node/%webform_menu/submission/%webform_menu_submission']['title callback'] = '_d7light_webform_submission_title';
  }
}

/**
 * @param object $node
 * @param object $submission
 *
 * @return string
 *
 * @see webform_submission_title()
 */
function _d7light_webform_submission_title($node, $submission) {

  if (empty($submission->data[1][0])) {
    return t('Submission #@serial', array('@serial' => $submission->serial));
  }

  return t(
    'Submission #@serial by @name',
    array(
      '@serial' => $submission->serial,
      // @todo Maybe something more generic than ->data[1][0]?
      '@name' => $submission->data[1][0],
    ));
}

With Easy Breadcrumb + hook_menu_alter()

Tbh I have only tested the code above with Crumbs enabled. So I don't know if it works without it.

I am also quite confident that it will work with Easy Breadcrumb, based on my understanding how it works.

With Crumbs + hook_menu_alter()

As said: You could try if enabling Crumbs makes a difference.

If you do, you might want to check admin/structure/crumbs/display and enable the "show current page".

With the Crumbs API.

This is an alternative to the method above, which does not change the page title but only the name in the breadcrumb.

Here is a starting point.

/**
 * A hook to register crumbs plugins.
 *
 * @param crumbs_InjectedAPI_hookCrumbsPlugins $api
 *   An object with methods to register plugins.
 *   See the class definition of crumbs_InjectedAPI_hookCrumbsPlugins, which
 *   methods are available.
 */
function MYMODULE_crumbs_plugins($api) {

  $api->routeTitleCallback(
    'node/%/submission/%',
    'webform_submission',
    function($path, array $item) {
      $node = $item['map'][1];
      $submission = $item['map'][3];
      if (0
        || !is_object($node)
        || !is_object($submission)
        || $node->type !== 'webform'
        || empty($submission->data[1][0])
      ) {
        return NULL;
      }
      $submission_name = $submission->data[1][0];
      return $item['title'] . ' (' . check_plain($submission_name) . ')';
    });
}

The same comment applies about $submission->data[1][0].

Changing the trail

Once you have tried those things, you can ask if you need more. I will then write more in this section.


Updating core from 8.5.4 to 8.6.3, can I skip the releases in between? I have a website that is running on Drupal 8.5.4. I want to update it to Drupal 8.6.3 through the manual update option (link).

Can I directly update it to 8.6.3 skipping the releases in between? None of the releases in between (8.5.5, 8.5.6, 8.6.0, 8.5.7, 8.6.1, 8.5.8, 8.6.2) had updates to the default.settings.php file, and I don't have any custom modifications to the files composer.json, .htaccess and robots.txt either (which means I can overwrite these 3 files with the ones that come with the updated Drupal code).

I read somewhere on the internet (link) that, while updating Drupal, we can skip minor and patch updates in between. But the release notes for 8.6.2 (link) says sites running Drupal 8.5.X should first update to 8.5.8 and update to 8.6.X later.

Does this mean I should first update to 8.5.8 and then to 8.6.3? Or can I directly update to 8.6.3?

You can skip releases and update directly to the latest release, unless you want to narrow down update issues by taking smaller steps.

You've mentioned the release note for 8.6.2:

  Sites on 8.5.x should update immediately to Drupal 8.5.8 instead, and
  plan to update to the latest 8.6.x release before May 2019.

This had a different background. This advice was for an urgent security update of versions < 8.5.8, because this wouldn't have been the right time to evaluate the update to 8.6.x if you hadn't done it yet, while the minor update from 8.5.7 to 8.5.8 was easy to apply, because it didn't require a database update.


Module has conditional Checkboxes, need to remove value I am building a module that will have a bunch of checkboxes to enable the addition of metatags like HandheldFriendly, MobileOptimized, etc.

I want to have the first checkbox only displayed. Upon checking that item, other options should appear. (if itemA == checked, then show itemB) I actually have that working. The problem is that if you check itemA and then check itemB and save, but then uncheck itemA, when you return to the configuration page itemB will still have a value.

Here is a simple timeline showing the issue

Snapshot #1:
itemA: unchecked
itemB: unchecked (invisible)

Snapshot #2:
itemA: checked
itemB: unchecked (visible)

Snapshot #3:
itemA: checked
itemB: checked (visible)

Snapshot #4:
itemA: unchecked
itemB: checked (invisible) // PROBLEM

Between each snapshot, the form was saved. How can I automatically hide AND uncheck the value for itemB when clicking itemA so that when I re-enable itemA, itemB is still unchecked?

If I need to  provide further clarification, I can.

module code for poetic_toolkit.admin.inc file

Add a secondary submit handler to run before the main one:

array_unshift($form['#submit'], 'poetic_toolkit_admin_submit');

Then in that:

function poetic_toolkit_admin_submit($form, &$form_state) {

    // check if field A is checked
    if(!$form_state['values']['poetic_toolkit_mobile_viewport_setting']) {
        // if it is not then set field B value to 0
        $form_state['values']['poetic_toolkit_enable_webapp_setting'] = 0;
    }

}

Then after this the main submit handler will fire and save our updated values.

This will only update the values once the form is saved.

Additionally, you don't want the unchecked condition on the depending item poetic_toolkit_enable_webapp_setting, because then it becomes checked whenever the dependent field poetic_toolkit_mobile_viewport_setting is checked (double negative). You also want to make sure you have the #default_value on the second item set, so that the user see's what is currently set (which will always be unchecked when the first is unchecked but could still be unchecked if the first is checked).

If you want B to become unchecked as soon as A is unchecked then you will need a jQuery solution.


Creating a dynamic menu I'd like to make a Drupal 8 menu dynamic so it can i.e. point to the latest node of the articles or news or hide another from the menu if it doesn't have an entry at all.

How can I achieve this?

You can't really have dynamic menus that point to different things. You can write a deriver and so on, but that will be persisted and not updated until you tell it to. You can trigger the necessary updates also without a full cache clear, see how MenuLinkContent does it, but it's still persisted.

Another approach would be to not make the route/output dynamic and not the menu. Point to a custom controller, and there you either dynamically display the latest node (can easily be done with a view, for example) or you redirect to the latest content, to avoid duplicate content.


Drush command to download AND enable a module To download and install a module, I run:

drush dl module_name
drush en module_name -y

I put that in a Bash script function, and just call "drin module_name" to simplify.

function drin(){
  drush dl $1
  drush en $1 -y
}

Is there a one-line command in Drush to download and enable a module?

The following will download and enable the module:

drush en module_name -y

Edit:  The download (dl) command is not needed.  When trying to enable a module that is not downloaded yet, Drush will ask if you want to download it and then ask if you want to enable it. The -y automates the "yes" answers to these questions.

This was added in Drush 6.0.0 (#1364814 by eiriksm, jonhattan: Added Extend pm-enable to offer downloading the project for missing extensions.)


Live user not found in stage and dev I am new to Acquia.

I have got access to the backend of drupal live instance. I cannot login to stage or dev instance.

Should a new user be created for every instance separately?
What should I do to login to the dev and stage instance?

Currently I am using Acquia Dev Desktop to pull the files locally.

What should I do to get access to the other 2 instances? Please advise.

Acquia works on a three-environment system. When working in such a system, code moves up, from dev -> stage -> prod, while databases move down from prod -> stage -> dev.

You should always consider content on dev and stage, such as nodes, users, taxonomies etc, as temporary. This is because the way to migrate content is by migrating the entire database from prod -> stage/dev, or sometimes from stage -> dev.

In order to get your user on all environments, you would create the user on prod, then migrate that database to stage and dev. You will then be able to log in with your user on those environments.


Add Language Switcher on admin toolbar What is the correct way for adding Language Switcher (Dropdown) or links on the admin toolbar menu from my custom module or from a contributed module?

Well, I got something up and running via hook_toolbar. Only thing left is, that you can't click directly on the "Language: EN" string in the toolbar. You have to click slightly next to it. Maybe you can fix this.

Apart from that, please also have a look at the Devel module and their implementation of hook_toolbar where they have an extra src/ToolbarHandler.php class for everything. You better should rebuild the code below into a dedicated handler.

use Drupal\Core\Url;
use Drupal\Core\Link;

/**
 * Implements hook_toolbar().
 */
function MYMODULE_toolbar() {

  // Get languages, get current route.
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $languages = \Drupal::languageManager()->getLanguages();
  $route = \Drupal::service('path.matcher')
    ->isFrontPage() ? '<front>' : '<current>';

  // Get links.
  $links = [];
  foreach ($languages as $language) {
    $url = new Url($route, [], ['language' => $language]);
    $links[] = [
      '#markup' => Link::fromTextAndUrl($language->getName(), $url)
        ->toString(),
    ];
  }

  // Set cache.
  $items['admin_toolbar_langswitch'] = [
    '#cache' => [
      'contexts' => [
        'languages:language_interface',
        'url',
      ],
    ],
  ];

  // Build toolbar item and tray.
  $items['admin_toolbar_langswitch'] += [
    '#type'   => 'toolbar_item',
    '#weight' => 999,
    'tab'     => [
      '#type'       => 'html_tag',
      '#tag'        => 'div',
      '#value'      => '' . t('Language') . ': ' . strtoupper($current_language) . '',
      '#attributes' => [
        'class' => ['toolbar-item-admin-toolbar-langswitch'],
        'title' => t('Admin Toolbar Langswitch'),
      ],
    ],
    'tray'    => [
      '#heading' => t('Admin Toolbar Langswitch'),
      'content'  => [
        '#theme'      => 'item_list',
        '#items'      => $links,
        '#attributes' => [
          'class' => ['toolbar-menu'],
        ],
      ],
    ],
  ];

  return $items;
}


FAPI Fivestar settings in custom form I have a multistep form with mforms in forth step my form have fivestar field from a review node content type.
All fivestar field display option are set to basic, but fields are displaying differently.

I tried to change the display widget in my module, with no luck. If i try to change the widget it returns to defaults.

Any suggestion are welcome. thx

function _reviewform_step4(&$form_state, &$next_step, $params) {

    $form = array();

    //attaching existing content type fields
    $review = new stdClass();
    $review->type = 'review'; //content type

    field_attach_form('node', $review, $form, $form_state);

    foreach ($form_state['field'] as $field) {
        if ($field['und']['field']['type'] == 'fivestar') {
            $field_name = $field['und']['field']['field_name'];
            // not working
            $form[$field_name]['und'][0]['rating']['#settings']['widget']['name'] = 'flames';
            $form[$field_name]['und'][0]['rating']['#settings']['widget']['css'] =     'sites/all/modules/fivestar/widgets/flames/flames.css';
            // not working to
            $form[$field_name]['und'][0]['rating']['#widget']['name'] = 'flames';
            $form[$field_name]['und'][0]['rating']['#widget']['css'] = 'sites/all/modules/fivestar/widgets/flames/flames.css';
        }
    }

I am not familiar with mforms, but I see a few potential issues:

1)  your form doesn't have a standard signature ($form, &$form_state, ...).  I obviously can't see how you're calling it, but this is not a typical thing to do.

2)  when getting the path of the css, you should be using drupal_get_path
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached

3)  widget is not a property of #settings


Themes folder path changes I am developing a site, in which my client has only access to sites/default/files path(their company allows only this path as public) today i got a new requirement that theme files such as css and js needs to be editable by admin , so they want theme files in sites/default/files/themes/site-theme. Is this achievable ? if so please give me any ideas on this .

One possible solution would be to alter the $theme_path global during hook_init(), although that would mean that all your theme files should be in another directory. I'm not sure if that's what you're going for.

If you just want to change some paths (ie for the stylesheets), alter the paths during hook_preprocess_page(), look up $vars['styles'] and change the paths there.


How can I validate exposed filter from View? I have build View which work for search exactly content by number filed "ICO".
How can I validate exposed filter form for only number and regular expression which enable only eight digit number?

Can you any help me with some example code for build it?

You should use hook_form_alter() to add a custom submit handler to the form like so:

$form['#submit'][] = 'my_custom_validation';

function my_custom_validation() {
  // Add the logic that you want in here
}

Then use form_set_error() to indicate if the value is wrong.


Get value for a field from url while saving a new node How to find a next Entity ID/Node ID?

Here is my scenario. I created my own Content Type which has 10 fields, one of these 10 fields has to save to DB thru a custom module. Value to this field is being passed thru URL filter.

Really appreciate any help.

With the comments so far , I could understand that you have a content type with 10 fields, so the time so create a node you will be putting 9 fields on the node form and the 10th field has to be filled with some value from url parameter,so lets assume your site url while adding the node looks like www.sitename.com/node/add/your_content_type?field_value=xyz.

One of the possible way can be to pick the value from url and make it as 10th field default value, an example code can go something like below.

 // Assuming 10th field as textfield.
 function mymodulename_hook_form_alter(&$form, $form_state, $form_id) {
   if($form_id == "your_node_add_form_id") {
     if (is_null($form['nid']['#value'])) {
         $form['your_10th_field_machine_name'][LANGUAGE_NONE][0]['vaue'][#default_value] = $_GET['field_value'];
     }
   }
 }

Rest saving of fields will be handled by drupal itself.


drupal_add_js and drupal_flush_all_caches I was trying to call drupal_add_js in the callback of a button. It seems, even with after_build, that this can be done successfully only you are working without cached data.

So, before i start the page, i run drupal_flush_all_caches, and the javascript is successfully added to the page.

The problem is I want to get some user input data from a form, pass to the javascript and exibit the result. The way i'm trying to do, it is getting a string that contains the processed values and concatenating with another string that contains the other part of the javascript (probably this is not a good practice), and calling this string with drupal_add_js. But, when if i call drupal_flush_all_caches, the form will be reset and i will not be able to get the data.

So, my questions are: How can i pass values from a form to a javascript?

Do i need to flush all caches every time to use drupal_add_js?

Is there different solutions to deal with this during development and production?

Thanks for the help guys. I found some answers:   How can i pass values from a form to a javascript? I had to name my variable as Drupal.settings.myModule.myVar in the javascript code. This way i can pass variables from php code to javascript. If you want to modify the javascript code you really need to flush caches. Until now, i have not found nothing about differences between production and development best pratices.

Is there any problem with writing a menu callback that does this, and processing in PHP?

If you must use JavaScript for the processing, why not intercept the user's value in JavaScript and never "really" submit the form?


These lines of code gets me out this error and i cannot understand it $number_to_keep = db_select('variable', 'va')
    ->fields('va.value')
    ->condition('va.name', 'dblog_row_limit', '=')
    ->execute();

And it gets me out that errors:

Notice: Undefined index: table in SelectQuery->preExecute() (line 1245 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->compile() (line 1079 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->compiled() (line 1097 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: arguments in SelectQuery->arguments() (line 1024 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->arguments() (line 1028 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->compiled() (line 1097 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->__toString() (line 1531 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->__toString() (line 1538 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: alias in SelectQuery->__toString() (line 1543 of /var/www/html/drupal/includes/database/select.inc).

The signature for SelectQuery::fields() is:

public SelectQuery::fields($table_alias, array $fields = array())

So you need:

$number_to_keep = db_select('variable', 'va')
  ->fields('va', array('value'))
  ->condition('va.name', 'dblog_row_limit', '=')
  ->execute();


When I update my database schema with drush entity-updates. I get an error When I try to update my database Schema I'm getting the following error:

  Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException:[error]
  The SQL storage cannot change the schema for an existing field
  (order_total in uc_order entity) with data. in
  Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->updateSharedTableSchema()
  (line 1376 of
  /www/htdocs/xxx/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).
  Failed:                                                              [error]
  Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException:
  !message in
  Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->updateSharedTableSchema()
  (line 1376 of
  /www/htdocs/xxx/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).

What can I do?

Sounds like you are trying to update existing field order_total in uc_order. You can't update it since you have some data in it already. Remove content that uses it (orders), and try again.

Also note that drush entity:updates currently doesn't support all changes (e.g. changing table keys). See this Change Record for information on providing a hook_update(): https://www.drupal.org/node/2554097


What is causing "Object of class stdClass could not be converted to string" I'm receiving the following error:

Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() (line 2227 of includes/database/database.inc).

I've narrowed it down to this code but I am still able see what is wrong with the code, it worked before but now I am getting this recurring error.

case 'field_home' :
$tids =  field_get_items('node', $node, $key, $node->language);
$terms = taxonomy_term_load_multiple(array(), array('tid' => $tids));
// Gets Field Array Based on Term IDs
$name = array();
foreach($terms as $term){
$name[] = $term->name;}
$return[$key_clean] = $name;

Please pass $tids array direct to the function.
E.g:

$terms = taxonomy_term_load_multiple($tids);

NOTE: Also before passing $tids to the function, please check it is include only tids.
E.g:

$tids should be like $tids = [10,11,12,13,...];


What "access argument" or permission-string to use for a custom module? When developing a custom module that has a configuration area, what is the correct or preferred permission to use? In core, you see a mixture of:

administer site configuration
access administration pages
administer {modulename}

They appear to be applied almost at random, and searching the documentation does not show me a unambiguous "Best Practice" or "HUG" for this.

In this case, the module is small, has only one configuration-page and is related to Taxonomy, so a fourth option would be to re-use administer taxonomy.

Is there an unambiguous, or distinctive guideline on this matter?

If you set a custom permission for your module you get finer control over who can configure your module's features. If your module is strictly related to Taxonomy you may stick to Administer taxonomy. You may find this link useful for your decision.


Civicrm membership expiration date after renewal I'm using D7, with CiviCRM 4.4.6. I had created a contribution page, with membership form included.

By now after renewal membership, the expiration date extend according to the end date. Eg:

Start Date: 1 Nov 2014
End date: 5 Nov 2014
Status: Expired

If renewal payment made on 11 Nov, for one month, the expiry date is changed to 5 Dec 2014.

But I want the expiry date to be one month after payment date, which is 11 Dec 2014.

Is there any way I can configure it to get the above result?

If not in configuration, any way I can change it in codes?

This works in the 4.5.2 sandbox (unknown if it works in 4.4.6)

Set your membership type to rolling instead of fixed
Disable the "Grace" membership status
If you are having a membership period shorter than 3 months, also disable or shorten the "New" membership status

An alternative workaround, which however may be a bit too clunky, would be to create a new membership type monthly and update the contribution page, so that it forces people to sign up for a new membership rather than renewing their existing one. This would, however, lead to the potential for overlapping memberships if they sign up for the new membership before the end of their old one.


How do I add an edit button on each row of a "tableselect" form element? How do I add an edit button on each row of a "tableselect" form element?

The code I have is the following one.

function example_elements_form() {
    $form = array();
    $header = array(
        'title' => array('field' => 'n.title', 'data' => t('Title')),
        'author' => array('field' => 'u.name', 'data' => t('Author')),
    );
    $query = "SELECT n.nid, n.title, u.name FROM {node} n INNER JOIN {users} u ON n.uid = u.uid". tablesort_sql($header);
    $result = pager_query(db_rewrite_sql($query));
    while($partial_node = db_fetch_object($result)) {
        $options[$partial_node->nid] = array(
            'title' => check_plain($partial_node->title),
            'author' => theme('username', $partial_node),
        );
    }
    if (!empty($options)) {
        $form['nodes'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $options,
        );
        $form['pager'] = array('#value' => theme('pager'));
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
        );
    }
    return $form;
}

Check out http://api.drupal.org/api/drupal/modules%21node%21node.admin.inc/function/node_admin_nodes/7

In particular, take a look at the lines that contain "operations". You need to set up a new element in $header to contain a column for the "operations", and then add at least one operation inside $options for each row.

You could either manually add a link to the edit with l(), or you could use module_invoke('node_operations') - again, an example of that is shown in the API.


When I going to Disable Twig template cache , Fatal error When I going to Disable Twig template cache , Fatal error . i.e

  The website encountered an unexpected error. Please try again later.
  Error: Unsupported operand types in
  Drupal\Core\Template\TwigEnvironment->__construct() (line 69 of
  core\lib\Drupal\Core\Template\TwigEnvironment.php).

I followed below steps :

1.Copy and rename the file from sites/example.settings.local.php to  sites/default/settings.local.php
2.Open settings.php file in sites/default and uncomment these lines:

if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
include $app_root . '/' . $site_path . '/settings.local.php';
}

3.Uncomment these lines in settings.local.php

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

Open development.services.yml in the sites folder and add the following code

 parameters:
twig.config:
debug: true
auto_reload: true
cache: false
Rebuild the cache and your good to go

My development.services.yml code :

parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
  debug: true
  auto_reload: true
  cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

The least hassle way is to install Drupal Console

Then run the command drupal site:mode dev (turns off caching and turns on twig debug)

Once you're done, run drupal site:mode prod (turns off twig debug, turns caching back on).


How to make a taxonomy vocabulary overview page with Drupal 7 I have a simple vocabulary named knowlegde with several terms. This vocabulary is localized and can be used in many languages. My question now is how can i make a simple page where i can display all content tagged with that vocabulary. The important thing is that the (localized ) vocabulary is part of the url.

For example in german the url should look like

http://example.org/wissen

and in english it should look like

http://example.org/knowledge

If you refered that taxonomy term in a content type then a listing page is created by default.

For example if you created a taxonomy named Category  and terms inside it are

Knowledge
courage

If you created a content type and refered category taxonomy then listing page will be at category/knowledge , category/courage and so on

To display all the contents of the vocabulary then

  Create a view of type Node

  Add a display of type block or page according to your need

  Add your desired fields(CCK) along with a field Taxonomy: Term

  Add a filter Taxonomy: Vocabulary and select is one of operator and choose the
    particular vocabulary name.

This solution will include taxonomy terms associated with content node but filter according to the defined vocabulary in filter.


Drupal 7 custom form submit handler is not being called I am trying to write a custom handler for one of the Drupal 7 forms:

function mymodule_formid_alter(&$form, &$form_state, $form_id) {

 array_unshift($form['#submit'], 'mymodule_formid_submit');

}

function mymodule_formid_submit($form, &$form_state) {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
    return
}

But it is not accessing the handler. Alter method is being called and printing 'mymodule_formid_submit' in the #submit array.

Maybe I am missing something, but exiting answers on Stack Overflow related to custom handlers are not helping in my case.

I had this same problem trying to edit commerce_product form. For some reason the submit handlers are registered under actual submit button and custom handlers added to the #submit -element weren't registered.

$form['#submit'][] = 'my_custom_handler';
$form['actions']['submit']['#submit'][] = 'my_custom_handler';

So when I added that second line to register my custom handler to button and atleast it works.


user/logout access denied v7.34 Admin or normal user can not logout using www.myswebsite.com/user/logout

An access denied page is displayed and the user is still logged.

using ?q=user/logout works.

It is not a rewrite problem, all other url are ok.

I have cleared the cache and deleted the cookies, tried on FF, IE & Chrome.

Any idea to investigate ?

Try different way

This works for me if I substitute the logged-in username for 'user', like this:

http://my_site/my_user/logout

ie:

http://example.com/jdoe/logout

this might be problem with not enabling clean url in your site go to

http://example.com/admin/config/search/clean-urls

enable clean url and check if its working

as you mentioned use http://example.com/user/logout will logout the current user section

Further readings:
logout problem - https://www.drupal.org/node/1572984

enabling clean url - https://www.drupal.org/node/1572984

access denied + logout - https://www.drupal.org/node/2192401


Can Drupal be used for hierarchical multi-site? Can you use Drupal to make a site hierarchy?
The main reason would be managing permissions and general connections between sub sites, like the following one:

                       Site 1
        Site 2         Site 3         Site 4 …
    Site 5   Site 6                   Site 7 …

This is a very vague question in that it doesn't give any semblance of the relation between the sites, or how they link to each other.

There are at least 3 different ways to make a unified site using multiple domains/subdomains using drupal:

1) Organic Group/Taxonomy/User based subdomains.

Each Group, Primary Taxonomy, or User gets their own subdomain, and their content is listed there.  Cross domain login issues are relatively mild, and just a matter of fixing the cookie domain as .domain.name, where the subdomains would be group.domain.name or user.domain.name or term.domain.name.

2) Domain Access based domains

This is more an "affiliated network of sites" concept.  Content is assigned to a specific site, and can be shared among all sites, or specific only to one. You link sites together using modules like Views as you can select content in any way you please, and give each site an individual look, or maintain a more consistent network theme.
  This can be implemented either as domains or subdomains, so cross-domain login issues are possible here, and can be difficult to mitigate effectively if you're trying to give an integrated feel.  SSO is one possible way to solve the issue, but other tweaks, such as pulling the login id across domain boundaries is also possible.  (This takes a little bit of technical wizardry)

3) Drupal sites based on a single install

All the sites share a code base, but each has their own database.  Automated links between the sites would need to be done through communication channels like RSS or RPC, or else maintained manually. As the user databases are separate, there are no common logins across sites.  SSO is probably a must in this case.

What solution fits your specific needs is not apparent from the question you're asking here, so please narrow the scope of your question by providing details as to what you mean by "site hierarchy".  What specifically makes otherwise unrelated host names (or domain names) into a hierarchy?


Pathauto patterns produce segment duplicates I have set up a pathauto pattern for a wiki-section that looks like this:

wiki/[node:menu-link:parent:url:alias]/[node:menu-link:title]

I want it to produce links such as wiki/page and wiki/page/subpage and it works fine for first level links, but for sublinks it duplicates the first segment and produces links such as wiki/wiki/page/subpage.

What is the correct pattern I should use?

Use just [node:menu-link:parents:join-path]/[node:menu-link:title] and make sure that you set the root node's URL alias manually as 'wiki'.


How do I create a new Group after installing OG? I downloaded the Organic Groups module for my drupal 7 account. I moved it to my sites/all directory and was able to see it in the Drupal settings where I checked off all of the Organic Groups sections and the Locale. However when I go to Create/Add Content I don't see the option to create a Group. Did I do something wrong? Has anyone else seen this problem before?

You have to do it in the content type. Go to a content type you would like to use as a group and you will see a fieldset Organic groups

Also check your permissions, you will have permissions for creating the content types and for administering og


altering access callback in hook_menu_alter So, I want to set a new function as access callbacks for URLs specified by registration module.

Specifically I want only users that have the update rights on the node to be able to manage registrations for the node.

I implemented hook_menu_alter in this manner:

function enge_events_menu_alter($items){
  $items['node/%entity_object/registrations']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/list']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/list']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/settings']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/settings']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/broadcast']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/broadcast']['access arguments'] = array(1);
}

but for some reason the function never fires.

If I instead redeclare the module's hook_menu and change the access callback functions there, it works and it get's written in the database after a cache clear.

Is it possible to alter access callbacks in hook_menu_alter?

function enge_events_menu_alter(&$items){
  $items['node/%entity_object/registrations']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/list']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/list']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/settings']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/settings']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/broadcast']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/broadcast']['access arguments'] = array(1);
}

$items should be reference variable... For more information hook_menu_alter


Multiple local Drupal sites for development on WAMPServer? I'm still very new to Drupal.  I'm hoping to create multiple site instances via my local WAMPServer WAMP stack.  I have one.  I realize that Acquia makes this very simple via their DAMP stack, but have heard that it can be very painful upgrading and/or transferring these to a server due to the non-standard paths that Acquia uses for some of its files (some of its modules specifically).  So I'm wondering how I can emulate what DAMP does, albeit without their Dev installer app.  I've searched here and googled, but can't seem to find anything...

This question is a bit off-topic. What you need to do is to setup Apache with name-based virtual host support. Of course you could place your sites in sub-directories, but you would be much happier with virtual hosts, i.e. one local 'domain' and www root per site.


How do I send and receive privatemsg? I'm using Services with Drupal 7 and I built a rest service with it, I also included the Privatemsg module and the Entity API module.

I can see under the my service a resource called entity_privatemsg_message it has only retrieve and index as operations.

I also found a pm_service supported in drupal threads by someusers here :
 Add Service methods .

Now I can see also the privatemsg resource in my service. but I'm missing the documentation on how to send and receive pm message over the rest service. what kind of arguments should be sent with the request.  I'm working with js/jquery to make request calls  ($.ajax).

Thanks for any help  about the private message services.

I'm pretty sure that using Services Entity API  will provide what you are looking for.  An endpoint shows up for me after enabling the module.

This module provides support for all Entity API entity types to Services. All entity types get a standard resource, similar to what Services provides for code entity types such as nodes.
This module allows to get entities by properties or fields and also paging and related entities that are defined properly.


How can I manually upgrade my site? I have updated my core to 8.9.0, all modules are Drupal 9 compatible and now I want to upgrade to Drupal 9.0.0. I always did my updates completely manually via FTP/web (swap core/vendor/root files, no SSH/drush/composer).

But for 8 to 9 drupal.org has only instructions using drush or composer, unlike the update instructions for Drupal 8 which had an instruction for how to do it manually.

Upgrading from Drupal 8 to Drupal 9 (or higher)
https://www.drupal.org/docs/upgrading-drupal/upgrading-from-drupal-8-to-drupal-9-or-higher

Is there no way to upgrade manually, without SSH/Drush/Composer?

Yes you can. But it needs a little bit of effort beforehand.

You need to have a composerized and version tracked local copy of your site on your computer. All the updating with Composer will happen there then. Look around a bit for Drupal+composerize, there are a few options out already to composerize your site.

From now on, after upgrading/updating your local site with Composer you upload the updated dependencies (the vendor/ directory, the core/ directory, all contrib directories, all libraries directories etc. but also updated scaffolding files like the robots.txt file, the development.services file etc.) to your host via (S)FTP for example and then access your live site's /update.php URL to trigger pending database updates.

As your local site should be version tracked now via Git for example you'll always see which files exactly got updated. For that you may need to adjust the default .gitignore files a bit to only ignore files with sensitive information like the settings.php file. But everything else (the vendor/ directory, the core/ directory, the contrib directories etc.) should better be version tracked to identify changes more easily. When you are done git add . everything and git commit -m "Update project." and git push to some private repo somewhere before you update your project the next time.

Ah look, there's still one alternative. Although what's been described above should be the recommended way you can follow the guide on Update core manually which tells you that you could Download Drupal zip and then upload certain contents of it to your host replacing the vendor/ and the core/ directory and some scaffolding files. This guide applies for Drupal 9 as well.


How to create Subtheme of Omega while Omega Tools and Drush both has some disclaimer and Moved to Github? I am a beginner in Drupal. I am using Drupal 7.
I wanted to create Subtheme in Omega.
Theses are the methods to create subtheme (With Omega Tools, Drush and Manually)in Omega.
I have install new core Drupal and installed Omega in my
sites/all/themes folder.
So, path for this would be:
"../sites/all/themes/omega"
I followed this Tutorial to create Subtheme using Omega Tools (As this is recommended for Beginners).
Omega Tools is one of the Recommended Modules to create sub theme with Omega.
In Omega Tools there is one DISCLAIMER:
"DISCLAIMER: Do not use Omega Tools with the 4.x version of Omega. Please

create your 4.x subthemes using Drush!
The Drush integration for Omega 4.x comes as part of the theme itself and does NOT require Omega Tools. Please uninstall Omega Tools if you are building a site with Omega 4.x."

So, this message leads me to the Drush where I saw the Drush project has moved to Github.
And theses are the Release Notes.
I read that we can also create sub theme with this method.

But how can I install Drush while Drush has been moved to Github? as I wanted to use Omega Tools to harness the full power of Omega.

Thanks for your help!

I'm speculating a bit, but Drush surely moved to github from the project page on d.o because it simply isn't a module. It is:

  a command-line shell and scripting interface for Drupal

So if you're thinking it's a module that needs be installed and enabled in your site, it isn't. It's a separate utility that needs to be installed on your machine.

You're absolutely right to want to stick with getting it installed for working with Omega, it does make life a lot easier. You can do so by following the detailed instructions on the github page.

There are also a bunch of questions in the composer tag that should help if you get stuck.


Calling web service on page load Until now I'm calling a web service with using specific function like hook_user_logout, _validate, _submit..., but now I need to create a page that will display details that I'll receive results from the web service, but I don't know how to call when I enter lets say user/%/reports.

Also on that page there will be a link that will display more details that will come from the webservice.

Is there a function for page load, url open or something similar in Drupal 7?

Here's my part of the code when a user logouts.

<?php

function mymodyle_user_logout($account) {

    global $user;

    $username = $user -> name;
    $ip_address = $_SERVER["REMOTE_ADDR"];
    $session_id = session_id();

    $xml_string = '<some_method>
       <username>' . $username . '</username>
       <ip_address>' . $ip_address . '</ip_address>
       <session_id>' . $session_id . '</session_id>
       <language>en</language>
       </some_method>';

    $client = new nusoap_client('http://10.10.60.80:8090/CardHolderAuthentication.asmx?wsdl',  array('soap_version' => SOAP_1_1, 'trace' => 1, 'exeptions' => true));
    $client -> soap_defencoding = 'UTF-8';
    $client -> decode_utf8 = FALSE;

    $result = $client -> call('Logout', array('_xml' => $xml_string));

    //$response = simplexml_load_string($result['LogoutResult']);

    //$status = $response -> error->descr_bg;

}

If the page content needs to be fetched via an API request, you can use

hook_menu

to define a URL path to function callback to generate the page content.

Basically your own path to the content.

The page callback will fetch the API response from cache or perform the request, cache the response and display it.


How do I programatically attach fields to a node defined in hook_node_info() I've got a module which defines a node type. I also need to attach a few fields to this node.

I'm defining the node in hook_node_info(), and I'm creating fields in hook_install(). However, isn't this going to create the fields before the node? Isn't hook_install() executed before hook_node_info(), meaning that I'll be attempting to attach the fields to a non-existing node type at that point?

How do I define a node type programatically, and also attach fields to the node type programatically upon module installation?

If you have familiarize with features module. It will be easy. You can get more idea about content type creation and it is related with field. Follow the steps to get a working example.

Create content type and related field in you site.
Enable features module and export this content type as a new module.
The system generated module, you can find the content type creation and field relateion code.
You can find documentation for creating content type and field via code in drupal.


How to validate if node is ubercart product? Im sure this is something simple, but I would really appreciate some help with it. How to check by php if the node is an ubercart product? Empty sku field might work but how can it be accessed ?

I think the most solid way to test would be to check that the node's type is one that the uc_product module considers to be a product node type. You can do that by using the uc_product_types() function:

$node_types = array_keys(uc_product_types());
if (in_array($node->type, $node_types)) {
  // The node is a product
}


Add meta tags on a page generated by a custom module I am trying to modify the meta tags of one of the pages of my web. For example, I want to change the title, the description and add the robots tag.

I have tried using the token and metatag modules to change this, but it is too generic and I do not see the option to change it individually on each page.

Also keep in mind that the page on which I want to change these tags is generated by a custom module: creating the Twig manually and generating the URL by routing.yml. There's the problem, that by not generating by the back, it does not recognize it as a page.

I've tested successfuly Metatag Routes module for Drupal 8. The module adds a button in the default metatag dashboard page. The user can configure metatags for custom controllers generated by code.


How to assign multiple author names for one article? Is there any way to mention two or more author names for a particular article in Drupal 7?

I need to add two author names for one article.

I tried to add two author names in the Author text box, separating them by commas, but it did not allow me to do this.

Is there any module or other way to do this?

My workaround for this would be to enable a user reference field with multiple allowed values on the content type you want to put multiple authors on. Then just disable display of authoring info on that content type and instead display the user reference fields.

There are some things that you can't do with this but if you just want to display or categorize posts by multiple authors I think this will work fine.


Exposed filter cleaner URL I have created a custom content type called building which I have added a entity reference field called category which is the vocabulary and added building type terms. I created a view called buildings and added an exposed filter that is listing the building types. I get the listing of the categories by exposing the filter Has Taxonomy Term and then using BEF to list the categories as links rather than a dropdown or autocomplete. Whenever I click each category link for the exposed filter I get the url www.example.com/building?category=1 is there a way to make it use the term name rather than the term id. Also further, is there a way to have it make the url a little cleaner like www.example.com/building/category/buldingtype

You need to set your Exposed filter Selection type settings to Autocomplete instead of "Dropdown" you will get term names instead of TIDs.

Read more in part of this answer: How to use URL query parameter on a View Exposed Filter?

There is another way to do it: introduce the term information into the view through a Relationship so you can use the term Name. Read the steps in this answer: Get taxonomy name instead of id

That answer also mentions how you can "prettify" the URL: use the Query Parameters To URL module, it's being ported to D8.


Views block showing empty content on front end I created a view to show a list of news items. I placed the view block in the content bottom region of the page. In the Views preview, it shows the results. However in the front end, the content is empty and shows:

I do have a view template for this block - views-view--news-list--block-1.tpl.php. In the Views page it shows this template as selected. I do not see that it is being rendered on the page though. Even when I just put a basic div with text in the views template, nothing shows in the content div.

What are the possible reasons for this? What can I do to get content to show?

Turns out it was my theme's block.tpl.php file. It was displaying content like so, $block->content.

I changed it to match the block.tpl.php file in modules/block:

<?php print $content ?>


Add link gone from main menu and getting errors when trying to add new menu item Running D7

For some reason the add link is gone from the admin menu view...can only edit but can't add any links or menu items, getting errors also:

Warning: Illegal string offset 'hierarchical_select' in
drupal_array_set_nested_value() (line 6776 of
C:\aquiasites\redoII\includes\common.inc).

Fatal error: Cannot create references to/from string offsets nor
overloaded objects in C:\aquiasites\redoII\includes\common.inc on line
6776

I disabled hierarchical_select to no avail...I can't find the view to control those settings, but this is a core view right?

Usually menus say:

    list links    edit menu    add link

But now these options are gone...

It only says:

    MENU LINK   ENABLED TARGET  OPERATIONS

Ok, found the answer, eventually another error popped up when trying usermenu:

Warning: Illegal string offset '#value' in
content_menu_form_menu_item_delete_form_alter() (line 270 of
C:\aquiasites\redoII\sites\all\modules\content_menu
\content_menu.module)

I disabled all possible menu plugins...the offending module didn't create any errors on main menu and other, ONLY on usermenu...

Disabled this module https://www.drupal.org/project/content_menu

Now works fine


Where does the mysterious blue bar and question mark come from (when logged in as admin)? When I'm logged in as an admin, I see a blue bar at the top of the page, with a question mark in a circle, but no text. This is how it looks like:

And the markup is:

<div class="region region-help alert alert-info">

I guess it's some kind of alert, but obviously there's no text, and nothing I can see in any of the logs that might be related either.

Anyone knows what this might be and how to fix it?

I think You should try to:

search Your modules or themes directory for usage of drupal_set_message function or dsm if You are using devel module.
check trigger module settings for User under admin/structure/trigger/user
check theme template for empty container with alert-info class


having multiple instances of blocks with different settings in D7 I have activated Multiblock module, create an instance of one custom block.
The admin/structure/block/instances say my new block instance is not 'multiblock enabled'

The doc say
https://www.drupal.org/node/353565

  To get around this, you can make a block "multiblock enabled". To do
  this, you have to first add an $op to your hook_block called
  'mb_enabled'. It should always return the string 'mb_enabled'.

I don't quite get how to do that and I have tried that with no effect

/**
 * Implementation of hook_block().
 * @param string $op one of "list", "view", "save" and "configure"
 * @param integer $delta code to identify the block
 * @param array $edit only for "save" operation
 */
function amu_hal_block($op = 'list', $delta = 0, $edit = array()) {

    // set up an empty array which will contain the block contents
    $block = array();

    switch ($op) {
        case "list":
            // Generate listing of blocks from this module, for the admin/block page
            $block[0]["info"] = t('On This Date');
            break;

        case "view":
            break;

        case "save":
            break;

        case "configure":
            break;

            case 'mb_enabled':
                return 'mb_enabled';
                break;
    }

    return $block;
}

Is hook_block present in D7 at all?

There's no hook_block in Drupal 7. However if you take a look at your README file inside your D7 version of multiblock module, you can find how to do it:

  Example implementation of hook_block_info:

function hook_block_info() {
  $blocks['powered-by'] = array(
    'info' => t('Powered by Drupal'),
    'weight' => '10',
    'cache' => DRUPAL_NO_CACHE,
    'mb_enabled' => TRUE,
  );
  return $blocks;
}


How to make my custom theme suggestion the most specific Is it possible to guarantee my custom theme suggestion is at the top of the list for theme suggestions? Something like the following

<!-- FILE NAME SUGGESTIONS:
  x my-custom-theme-suggestion.html.twig
  x input--textfield.html.twig  // ALSO WHY DO I HAVE TWO OF THESE
  x input--textfield.html.twig
  * input.html.twig
-->

Also I'm not sure why but I have two theme suggestions that are the same. Anyone else experience that?

Suggestions is a PHP array that is provided by a hook and an alter hook. The standard rules apply, alter hook is later, so add it there to be more likely to be the last.

And if you want to be sure, set the module weight and/or implements hook_module_implements_alter() to ensure that your module is the one that is called last.

If you want to implement this in a theme then you only use the alter hook anyway and the module_implements_alter() won't work, but themes and especially the active themes are called last anyway.

The duplicate is possibly because the defaults include a suggestion for the field type and one for the field name, so if you name it the same as the field type, then you get the same suggestion twice


How can I add extra text fields to the image field when adding/ editing nodes? What is the best way to add additional text fields to the image module, other than the title and alt value, when adding/ editing content? Is there a module which already does this?

Edit

I've read through Add custom fields to image field and unfortunately this fella got stuck and I guess this was at 7 times. The fieldable files module is no big help. It does a lot of magic but it doesnt effect images added via node entity form.

Image is a file entity and to make it fieldable you can use this module:

File Entity (fieldable files)

From the documentation:

  File Entity

  The File entity module extends the capabilities of the core File
  module.

  File Entity defines 5 File Types - Application, Audio, Image, Text,
  Video. The Media module adds an additional File Type - Other
  (currently these File Types are hard coded and cannot be changed).

  When files are uploaded they are automatically assigned the
  appropriate File Type based on the file suffix.

  The File Types as currently defined are:

  Images - .png, .gif, .jpg, .jpeg, .ico Videos - .mov, .mpg, .flv,
  .m4v, .mp4, ,ogg, .ovg, .wmv Sound files - .mp3 Text - .txt Document
  files - .doc, .xls, .pdf, .ppt, .pps, .odt, .ods, .odp Other - ??

  Each File Type can have fields. This allows for additional information to
  be stored along with a media file such as Title, Description, Taxonomy
  References, Node References, Location, Date created, License
  information etc.


Display register form to logged in users I am on Drupal 7. When users log into a Drupal website, they aren't allowed to see the register form anymore. That is the regular behavior and I understand the reason why Drupal behaves like that.

But I have a specific situation in my website. I need users in a specific role to register new users. I will create an invisible field in my form that will tie these new users with the UserId of the "parent" user creating them. Maybe I will use the User Reference module. There is no problem here, I can do that.

The question is: how can I get the register form to be displayed to logged in users in a specific Role without giving them the "Administer users" rights? I don't trust these guys to give them that much access.

Thank you!

The access check is made in the user_register_form() function itself:

$admin = user_access('administer users');

...

// If we aren't admin but already logged on, go to the user page instead.
if (!$admin && $user->uid) {
  drupal_goto('user/' . $user->uid);
}

As you can see the check for the administer users permission is hard-coded. That said, I think you've got 2 options:

Grant the appropriate permission to that user role (obviously undesirable as you've mentioned).
Re-implement the user registration form in a custom module, changing the access check to a more appropriate one for your situation. You should be able to use pretty much all of the code from user_register_form() and piggyback off the validation/submit handlers, so there shouldn't be much coding involved at all really.


Email all users when a new content is published in Drupal 7 I want to send email notifications whenever a new content is published in the site. It would be helpful if I can do it by Actions - using Actions & Triggers I can use token to mail a single user, i.e. author of a node. But how do I send email notification to ALL authenticated users of my site?

P.S. It is necessary that emails appear in bcc field, to avoid Spam. I've searched a lot, but no specific solution was found.

You can use the Rules module, a more powerful version of actions and triggers.
Configure a rule as follows:

React on event: (Node) After saving new content
Action: (System) Send mail to all users of a role

However, you cannot select the authenticated role here.  Instead, you will have to add another role to your site and use it instead.  (You can create another rule to automatically add that role upon registration.)
Also, note that the Rules module has this warning about sending too many mails:

WARNING: This may cause problems if there are too many users
of these roles on your site, as your server may not be able
to handle all the mail requests all at once.

So if you have a lot of users this probably isn't a good solution.


how do I create submenus in my module? I am pretty new to drupal php etc.

I have a module that just add links to main menu and load a .html and a .js when a link is called.

For now my menu looks like this:

Demo

Now I would like something  like:

Demo
More demos

extra demo1
extra demo 2

Ideally "More demos" should be collapsed and should expand on click

Here is the code I have so far:

<?php

/**
 * Implements hook_menu()
 */
function kl_menu(){
  $items = array();

  $items['demo'] = array(
   'title'            => t('Demo'),
   'page callback'    => 'build_demo_page',
   'access arguments' => array('access content'),
   'menu_name' => 'main-menu',
   'type' => MENU_NORMAL_ITEM,
  );

  return $items;
  }

/*
 * build_demo_page
 */
function build_standard_demo_page() {
drupal_add_js(drupal_get_path('module', 'kl') . '/demo.js', 'file');
 return  ( file_get_contents( drupal_get_path('module', 'kl').'/demo.html') );
}

I am not sure to go from there.

Thanks

I've pasted a sample code below. Hope that helps.

 function hook_menu() {
      $items = array();

      $items['demo'] = array(
      //other code here
      );

      $items['more-demos'] = array(
      //other code here
      );

      $items['more-demos/extra-demo-1'] = array(
      //other code here
      );

      $items['more-demos/extra-demo-2'] = array(
      //other code here
      );

      return $items;
    }


Remove entity type without module uninstall I created entity type my_entity in my module. But now I don't need this entity anymore and I want to completely remove it without module's uninstall. I want to remove both definition and all database related tables or data. I thought about using \Drupal::entityDefinitionUpdateManager->uninstallEntityType('my_entity') in hook_update_N, but I can't use it because entity's definition will be removed.

Could anyone help me, and give advice how to delete both definition and database data?

UPD: I created an issue on drupal.org about this https://www.drupal.org/node/2655162

The argument for entityDefinitionUpdateManager->uninstallEntityType() is an EntityTypeInterface, not a string.

Drupal stores the last known state of an entity type, you can get it like this:

$entity_update_manager = \Drupal::entityDefinitionUpdateManager();
$entity_type = $entity_update_manager->getEntityType('your_entity_type_id');
$entity_update_manager->uninstallEntityType($entity_type);

Note that this is using the enitty definitions update manager to get the entity type definition, not the runtime entity type manager.

The field definitions are also read from state and both the entity type and field definitions are purged afterwards.


Does node_delete() function deletes the attached media files as well? I'm deleting my 'articles' created before Sat Nov 1 00:00:00 2014 GMT from Drupal 7.34 site, but I'm not sure whether the node_delete() delete the media files as well?

Below is my processing code:

<?php

// Fetch the NIDs of 'articles' created before Sat Nov 1 00:00:00 2014 GMT
$query = db_select('node', 'n')
->fields('n', array('nid'))
->condition('type', 'article')
->condition('created', 1414800000, '<') // 1414800000 = Sat Nov 1 00:00:00 2014 GMT
->orderBy('created', 'DESC')
->range(0, 100);
$result = $query->execute();

// Code to delete my articles in bulk
while ($record = $result->fetchAssoc()) {
  $nid = $record['nid'];
  echo $nid;
  node_delete($nid);
}

?>

It depends.

If the file has no references left to it in the file_usage table, then yes, it will be deleted.

If there are remaining references, it won't be deleted.

Either way, file_delete() is definitely invoked for the file.


Alphabet sorting does not work properly with unique characters I've a view with sorting by first character and it does not work properly for unique characters (f.x. danish characters: ø å æ).

What should I do in order to sort they properly?

Thanks.

I ended up with writing my own module. It uses hook views_query_alter and change SQL query little bit. Module does not have any settings in UI but hardcoded variables so you need to adjust it in order to solve issue with sorting.

<?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}


Is there a way to programmatically alter a field's schema? Is there a way to modify a fields schema programmatically? I'd like the image field to have a "Premium" checkbox, but I need to store this data somewhere. Also, it needs to work for current fields and future fields as they are created.

I believe you are looking for the API function hook_schema_alter.

Though you should also be aware that the Media module exists specifically to solve this particular problem in a much nicer way.


How to only define hook_menu path to certain URL Consider this simple implementation of hook_menu()

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

This code work when I visit example.com/hello, but so does when I append extra argument to the url like example.com/hello/world. How do I only define the example.com/hello only without getting all these 'derivative' URL defined as well?

Per the hook_menu() docs:

  When path 'abc/def' is requested, no further path components are in
  the request, and no additional arguments are passed to the callback
  function (so $ghi and $jkl would take the default values as defined in
  the function signature). When 'abc/def/123/foo' is requested, $ghi
  will be '123' and $jkl will be 'foo'. Note that this automatic passing
  of optional path arguments applies only to page and theme callback
  functions.

In other words, it's a feature of the Drupal menu routing system to accept additional path components.

If you're looking to try to circumvent this, you can use an access callback function to enforce your sole path:

/**
 * implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_callback',
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return "Hello World!";
}

/**
 * Access callback for /hello. 403 on addition path components.
 */
function helloworld_callback() {
  return (request_path() == 'hello');
}


alterRoutes() is not triggered I am trying to alter the route for the login and registration pages. I followed Altering existing routes and adding new routes based on dynamic ones. I cleared the cache repeatedly, and re-enabled the module several times, but it looks like alterRoutes() is not triggered, even when I try to add a kint() debug or any code.

What I noticed is that alterRoutes() -> kint() is triggered when I use Drush to enable the module. In this case, I see kint() output in my terminal. However, alterRoutes() is not triggered when viewing the site.

This is the code I am using.

md_routes/src/Routing/RouteSubscriber.php

namespace Drupal\md_routes\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;
/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

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

md_routes/md_routes.services.yml

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

I did clear the drupal caches using the interface (admin/config/development/performance), it seems like drush is not clearing ALL caches. It does work now and i guess it was a caching issue. Thanks anyways!


Remove links in the login block I want to remove the following default links on the login block.

Create new account
Reset your password

I used hook_form_alter() but there is nothing in there that creates these links.

Method #1

Implement hook_preprocess_block() in your module/theme.

/**
 * Implements hook_preprocess_HOOK().
 */
function HOOK_preprocess_block__user_login_block(&$variables) {
  $variables['content']['user_links']['#access'] = FALSE;
}

Method #2

Override block--user-login-block.html.twig template and replace {{ content }} with the following {{ content|without('user_links') }}.

Note that hiding those links would not protect respective pages (user/register and user/password) from direct access.


Install without Bootstrap CDN I have the theme Bootstrap CDN 3.3.6 installed on my site and I use the appearance "Journal". How not to use the CDN maintaining the appearance "Journal" ? Thank you

I download on Bootstrap http://getbootstrap.com/getting-started/#download and I copy the folder in my sub-theme, as you can see on the screenshot.
I copy the file overrides-journal.min.css to bootstrap theme of css file my subtheme.
I added a few lines in my file bootstrap_subtheme_front_office.info, see the catch.
I disabled CDN in subtheme /admin/appearance/settings/bootstrap_subtheme_front_office
I deleted the cache.

If I erases the line stylesheets[all][] = css/overrides-journal.min.css the theme works correctly but I want to show the appearance of the theme "Journal".

If I add the line stylesheets[all][] = css/overrides-journal.min.css the theme "Journal" is not applied.

Get the css files , or compile the less ones , and copy them to your theme css folder , then modify your theme .info file so drupal can see the new css files


Updating cached REST resources I'm building my first custom REST resources.  I have a custom entity and returning specific fields from it.  However, it's very important that if a specific field changes (a status field) that it is reflected in the response.

What I'm seeing is that I have to clear the cache every time I update the entity.  How do I make sure the response is up-to-date?

I have tried using both \Drupal::entityQuery and \Drupal::entityTypeManager()->getStorage()... but both require a cache clear.  Maybe I'm loading the entity incorrectly?

It's not about how you load the entity. It's how you build the response. You have to add the correct cache tags. A cacheable response has the method addCacheableDependency(), which accepts objects which provide cache metadata:

$response->addCacheableDependency($entity);

This adds the tag custom_entity:[id] to the cached response. All cached responses with this tag will be invalidated, when the entity is updated.

This is an example from core for the cache data and access checks you need in a response which contains entity data:

Drupal\rest\Plugin\rest\resource::get()

public function get(EntityInterface $entity) {
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException();
    }

    $response = new ResourceResponse($entity, 200);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

    if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $field_name => $field) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $field */
        $field_access = $field->access('view', NULL, TRUE);
        $response->addCacheableDependency($field_access);

        if (!$field_access->isAllowed()) {
          $entity->set($field_name, NULL);
        }
      }
    }

    return $response;
  }


How can I get an entityform attached to an order in drupal commerce? I'm trying to append an entityform to an order in Drupal commerce. I included the several attempts in my code snippet. Version 1 just throws the following error:

Fatal error: Cannot use object of type EntityValueWrapper as array in /sites/all/modules/kalamuna/tb_commerce_panes/tb_commerce_panes.module on line 374

I tried two other attempts. Version 2 and 3 show up in $order, but when I get to the checkout page and var_dump $order it isn't there. Any ideas why?

function commerce_panes_custom_submit($form, &$form_state, $checkout_pane, $order) {
  // Strip out the entityform type.
  $values = $form_state['values'];
  $entityform_type_name = $values['entityform_bundle'];

  // Create a new entityform from the remaining fields.
  global $user;
  $form = new Entityform(
    array(
      'type'     => $entityform_type_name,
      'created'  => time(),
      'changed'  => time(),
      'language' => LANGUAGE_NONE,
      'uid'      => 2
    )
  );

  // The process the rest entityform fields.
  foreach ($values as $k => $v) {
    if (strstr($k, 'field_')) {
      $form->$k = $v;
    }
  }

  //Version 1 - Original
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->field_tb_registration_forms[] = $form;
  $order_wrapper->save();

  //Version 2 - Modified Original
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $node = $order_wrapper->values();
  $node->field_tb_registration_forms[] = $form;
  $order_wrapper->save();

  //Version 3 - modify $order and save it
  $order->field_tb_registration_forms = $form;
  commerce_order_save($order);

}

Have you tried first checking to make sure $order is set? If not then load cart from $user->id first and then wrap it.


Use drush to install a module on all of the sites of a multisite at once I have a Drupal 8 multisite, setup with 6 different sites.  I want to install Admin Toolbar on all of them on my local dev environment (mamp / terminal / drush).  I have downloaded that module using composer:

composer require drupal/admin_toolbar

Is there a single drush command that will install this module on all six of the sites at once?  If not, what is the most efficient way to install it to each?

If you are using Acquia Cloud Site Factory (ACSF) then you can use ACSF command acsf-tools-ml

acsf-tools-ml (sfml): This command will run any Drush command against all sites in your factory. drush @coolsites.01dev sfml en admin_toolbar

 2. Other solution: It's not recommended to enable/disable module directly on the server in this way you lose access to Configuration management.(It will become difficult to manage it)

Recommended Approach:

Enable module in your local environment and then export it via `drush config:export`
import the configuration on the respected server via `drush  config:import`
You can write a simple bash command to automate drush  config:import on all the websites.


Private schema is always used for system.files route I am trying to serve files from Amazon S3(s3:// stream wrapper) via system.files / system.private_file_download routes but no matter what I do the scheme is always set to private.

I have tried to use
/system/files/s3/file.jpg for system.private_file_download
and
/system/files/s3?file=file.jpg for system.files

but I always get private scheme.

The system.private_file_download route seems to be completely broken due to htaccess rules(ie. serving image like this won't even make it to the controller) and system.files somehow completely ignores provided scheme argument.

So far I have observed that the routes get matched to requests in exact opposite as one would expect.
The system.files route is defined first and it expects only "scheme" url argument(with "private" as default value in controller and also in the route itself), for example /system/files/public and what is provided as "file" query argument is used as target, so /system/files/public?file=foo/bar.jpg should result into public://foo/bar.jpg but instead the system.private_file_download route is used(even though it is defined after the system.files route). This route expects the "filepath" url argument, like /system/files/foo/bar/.jpg, and it automatically uses the private scheme because both of these routes use the same controller but this route does not provide the scheme in its definition or path so the default value from the controller itself is used.

I think the issue here is that the second route is using the filepath: .+ argument mask and therefore will match "better" with the path so it will have more priority over previously defined system.files route.

Also strangely the "filepath" url argument in system.private_file_download route has no match in the controller(\Drupal\system\FileDownloadController::download) so the resulting uri will be simply private:// no matter what values are provided to the route.

I have replaced the public stream wrapper with s3 so all files are now served from remote server and it is working just fine. I was able to get the image styles working(system/files/styles/thumbnail/public/foo/bar.jpg) but I am still not able to serve the original files from under /system/files path as well. Since  I need to serve the physical files and not File entities, even if I would switch to private file system the files would not be served because file_file_download() handles only file entities.

I have ended up with custom route. If anyone is interested the important thing is to have two routes(just like the two mentioned above). The second one will transform the url arguments into query argument and return path to the first route. This is done via path_processor_inbound tagged service(see \Drupal\system\PathProcessor\PathProcessorFiles).

I looked into this. Long story short, it's a bug in core: https://www.drupal.org/node/2694129. It will be a bit tricky to fix, since it might require API change and not 100% sure when such a change can actually be made.


Delete multiple images at once from a node I'm having an image field with option set as UNLIMITED to accept infinite images, basically deleting images in single manner is possible, but how it can be possible to delete multiple images at once from a particular node?

I've tried it by applying some logics using Views Bulk Operations and also using Editable Views, but nothing worked for me.

Any suggestion on this?

I'm a little surprised there's nothing available to empty out a field, but in its absence you can just write your own action for VBO. Contrived (and most likely incomplete) example:

function MYMODULE_action_info() {
  return array(
    'MYMODULE_delete_images' => array(
      'type' => 'node',
      'triggers' => array('any'),
      'label' => t('Remove all images'),
      'behavior' => array('changes_property'),
      'configurable' => FALSE,
      'vbo_configurable' => FALSE,

    ),
  );
}

function MYMODULE_delete_images_action($entity, $context) {
  // Pick up pre-batch config entered by user.
  $foo = $context['foo'];

  // Remove all field vals. Using 'changes_property' behavior in the
  // info hook will trigger the entity to be saved, so no need
  // to do so manually.
  $entity->field_FOO[LANGUAGE_NONE] = array();
}

function MYMODULE_delete_images_action_form($context, &$form_state) {
  // Some custom context for the batch op.
  $form['foo'] = array(
    '#type' => 'textfield',
    '#title' => t('Some option'),
  );
}

function MYMODULE_delete_images_action_form_validate($form, &$form_state) {
  // Validate the submission.
  if (bar($form_state['values']['foo'])) {
    form_set_error('foo', t('Blah'));
  }
}

function MYMODULE_delete_images_action_form_submit($form, &$form_state) {
  // Ensure submitted values are passed through to the action callback.
  return array(
    'foo' => $form_state['values']['foo'],
  );
}

Obviously you could extend the pre-batch form to allow for a choice of which field to empty, and even make this generic to all field types with a little effort.


Store age from Date of birth when use registration I am having a date of birth field in my registration form.

I want to add the age in user data when the reregistration form is
submitted.
How can I update the age in the field when crone is run.

Computed Field Module will do the job:

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

You can also google "Drupal Computed Field Age" for more information.


How to make user profiles of specific role as public in drupal 7? I am working on a project and the problem I am facing is,

There are 2 user roles Doctor and Patient.
What I want to accomplish is profile of users with role of "Doctor" is accessible by all including anonymous and profile of users with role "Patient" is accessible by user himself and all the users with role of "Doctor".
Rest no one can access the profile of "Patient" role.

Any help is much appreciated.
Thanks in advance.

You are looking for Profile2 module.

  With profile2 user account settings and user profiles are conceptually
  different things, e.g. with the "Profile pages" module enabled users
  get two separate menu links "My account" and "My profile".
  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)
  Profile2 supports private profile fields, which are only shown to the
  user owning the profile and to administrators

Check out this Demo video.


How to remove a file from a "Choose file..." dialog? Or, how to set things up so users can do that, I guess...

The point: Once you've selected a managed file in a standard Drupal "Choose file..." dialog, there doesn't seem to be a way to remove the file, short of refreshing the page.  For those cases where the file is optional, something like this ought to be there, and I'm actually a little surprised that it's not there already.  I suppose I could throw some jQuery together and hang my own button off the input field, but is there really nothing in core Drupal that will do this (or IS there something, and I'm just missing it or screwing it up somehow)?  Thanks!

I guess you are refering Drupal 7, as Drupal 8 has by default that option.

D7

What Drupal (D7) Provides,

Step-1: File/Image uploading option in node.

Step-2: Example Case: Suppose I uploaded wrong image instead of IMG_0065.jpg, I want to upload IMG_0068.jpg.

Step-3: Just Re-upload the file on the previous file, the new file will be loaded and the previous file will be removed.

Step-4: Image file uploaded and now als0 you can remove as Remove Button is there.

So, In short you want REMOVE button at Step-2, But the default file uploaded do not have that option. That is the fact. But if you manage, Drupal provide the option of replacing, which is quite similar option of removing.

Solution using other file uploader Module

Now, instead of using Drupal's Default File uploaded feature, you can download new module called, Drag & Drop Upload.  Installation: For this also like default file uploaded, you have to create add a field in content type and in widget option you need to choose Drag and drop instead of file.

Now, following is the image of drag and drop in action, now you can see after just browsing, you can see X mark besides file. Which is the the Step-2 option which was missing in above default setup.

Further Reading: On this link there is a detailed comparison of all type of File Uploading Modules, you can refer more from there:
Multiple file upload for node

D8

By default Drupal 8 has this option as shown in following image.


error 403 when trying to log in during checkout It's the first time i'm posting on a forum but i've been really stuck with this problem for a few days.
So thanks for your help.

I'm working on a site that's entirely https.
The site uses the anonym checkout  possibilities. I recently observed that when a user wants to connect during checkout (using the "/user" link, I don't use extra pannel to log in), after adding a product to cart or after a purchase, he gets an error 403.
Whatever role he has, he is stuck with this error. The login and the password are correct. And this doesn't happen when we are on another page. It only appears from the moment a user adds a product in the cart.
Then he has to empty the session and cache of the navigator to connect to his account.

I don't understand the problem because I don't have this problem on localhost, the only difference i see between the two server is that i don't use https on the localhost.
That's why i think it's a session problem but i'm not sure.
I tried all the solutions proposed for the settings.php, I don't use secure page (i used to but i uninstalled it because the site is entirely https now).
The site is on a subdomain.

I have made a redirection to htacess to redirect possible entry by http to https with this code:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$https://a.domain.com/$1[R=301,L]

I don't know what else to do, thanks for your help. Sorry if there's a lack of information, just tell me.

Thanks.

My problem was a session bug with my version of php (5.6.3) the code from here contains a workaround:

function mymodule_user_login(&$edit, $account) {
  $_SESSION['mymodule']['ulogged'] = 1;
}


Creating an editable table which can be updated I have a site with about 150 users. I am going to implement a system whereby things that they do in the real world (it's a fitness company), such as attending sessions, introducing new customers etc will earn them points.

I would like to create a table with 3 columns:

Name | Points | Update

so something like this:

The idea being that my client (editor role) could log in and amend the points that each user has and then click update to modify each row. I guess the table would be equally useful if there were just a single 'update' button at the bottom of the table to update all entries at once.

I don't know how I might go about making a table such as this 'editable', but would really appreciate some pointers as to how you might accomplish this. I would stress that I'm okay with using contributed modules, but quite poor with creating modules and PHP in general!

For your requirement Slickgrid is the best option for you and for that you need to use views module.

At the front end, users can show/hide, resize, reorder columns &
resize the height of the grid. These settings will be stored per user
and used next time the grid is shown. Saving the view (via the usual
views UI) will reset these settings.

For every field defined in the view, you can set its column width, whether it's sortable, and formatters (how the cell data is displayed), an editor, a validator and filters (for filtering the column data).
This modules comes with the following plugins ready to use:

Editors:

Inline cell editor - for excel-like editing of text & numeric data.
Popup field form - the field form pops up in an overlay. All field types can be edited.

Features of the grid:

Grouping field - group fields with a common value together
Collapsible taxonomy fields (tree structures)
Tabs - organise columns into tabs
Resize, reorder & hide columns
Delete entities via the grid
Force fit columns (to fill the available column space)
Undo (undo previous changes - uses node revisions)
Set viewport height
Set row height
Add entities via the grid*
Clone entities*
Export data (via the views data export module)*
Multi edit/delete/clone/export (checkboxes will be displayed in the rows - select as many rows as you want to perform action against)***

or as  Pontus Nilsson said use this Editable Views module.


How to display references entities in single field? I have a view of nodes. These nodes are connected with users via entity reference. User has a profile (Profile2). I want to display profile fields for all referenced users in single field.

You might need to use something like Views Field View and pass your node number as an argument, then use the reverse relationship to list members.


Link two content types by mutual value I have two content types: man and food;

The man content type contains the man's name several more fields and a unique id field created by the serial module.

The second content type is created by the users via an external form.
The results from the form are set as the food content type. One of the fields is equal to the unique id field at the man content type.

My question is:
1. I want to create a view that will show me all the man values, But when the value is clicked, it will lead me to a table that contains all the food content type entries where the unique id in food is equal to the man unique id value.

It so easy to do this in php but I am new to drupal.

Any help of lead will be great.

Create a views page and list all food results with a contextual filter on the unique id. Give it a path with a wildcard % . In another block or page list the man names. Include the unique id and put that field on top and exclude it from display. Rewrite the output of the name as a link to the views path but replace the wildcard with the token of the unique id.