render add to cart using views Is it possible to use views to render block with add to cart button, then add a contextual filter, so I can use it in panels?

For testing, I tried to make a simple view consisting of add to cart buttons and use it on a product page, but it displays nothing.

The same is with displaying pictures attached to product. I can see them when creating view in view UI but how do I pull out data from product so I can display them on product page using using views or just placing a block on a page.

Any help would be appreciated. Thank you

Self answered by user1031742

I had to enable permissions for viewing product - namely: View any Product product. Otherwise any content pulled from product would be forbidden to all users but administrator.


Drupal Commons make group content visible for anonomous users? I have a Drupal (7.52) Commons (commons-7.x-3.40) website which currently requires users to log-in to see published content.

Now I need to publish content so it is visible to non-authenticated users... I'm not sure the best way to accomplish this.  I'm not very experienced with Drupal, the most logical thing to me would be to simply create a new Group which allows anyone (anyone|Any site member can contribute) to view content but this option seems to still require authentication.

Other options seem to be add:

new content-Type e.g. Public_Group (or perhaps Public_Page)
new role for unauthenticated users (e.g. called anyone), or
a module like this: https://www.drupal.org/project/og_visibility ?

Not sure where to start looking - please help!

Thanks

Simple solution - in Permissions (People), check 'Anonymous User' for the 'Node' setting 'View Published Content'.


IMCE 6.27 Missing Buttons to Upload to Editor I'm attempting to correct my IMCE file browser issue where the images don't appear. I cannot click on the file names to select them, I am, however, able to move around the left hand navigation sitemap and choose different roots and folders.

I'm running on Drupal 6, and using IMCE 6.27 (non-dev). CKEditor is not installed, and TINYMCE is turned off. Turning it on didn't seem to solve any issues. There are no SSL pages, so that fix didn't resolve my issue by letting it ignore the IMCE files.

Any thoughts?

The issue in this instance laid with Google Analytics and it's Event Tracking. A quick test is to turn on the Google Analytics Module, then try to use the IMCE upload buttons again. If they return, do the following:

Re-enable Google Analytics Modules you'd previously turned off to test.
Goto /admin/settings/googleanalytics
Open the collapsible menu option "Page Specific Tracking Settings"
Add imce to that list Click Save
Configuration and test again.

Your IMCE should be working again without issue should the Google Analytics have caused your issue in the first place.


Why is this query not working? I have this snippet:

$nid = db_query("select nid from {node} where title = :title", array(':title' = 'scrivimi'))->fetchField();
dsm($nid);

It should work, at least from what I've read around the drupal api reference, but it doesn't.

I think the problem is with placeholders. In fact, if I execute the query without them, it runs perfectly, and returns the expected result!

Can you help me please?

I am using Drupal 7 (updated to the latest version), and I am testing this code using the Devel module.

You have a tiny error in your code, the placeholder array should be

array(':title' => 'scrivimi')

not

array(':title' = 'scrivimi')


add a new field in a view that uses a teaser view mode fomat I have a view that extarct a specific content type, this view shows the teaser view mode for rendering fields and not fields format :

the teaser view mode is managed with display suite module to order content type's fields in custom regions.

Im using hook_node_view to add a new field conditionally :

function MYMODULE_node_view($node, $view_mode, $langcode){
    global $user;
    $uuid = $user->uid;
    switch ($node->type){
        case "rewards" :

            if(!empty($node->field_reward_users) && isset($node->field_reward_users[LANGUAGE_NONE][0]['target_id'])){
                if($uuid == $node->field_reward_users[LANGUAGE_NONE][0]['target_id']){
                    $node->content['get_reward_link'] = array(
                        '#type' => 'markup',
                        '#markup' => l('Click Here', '/', array('attributes'=>array('class'=>'my-link-class'))),
                        '#weight' => 100,

                    );
                }
            }
           // dpm($node);
            break;
    }
}

when i debug i can see the new field in the $node object, but it's not rendered.
Have you any idea how to add fields conditionally in my case?

Update

I added a new preprocess field ("pre_rewards") via display suite, like montionned in the answer of Reynold, then I added the following prerocess function :

function MYMODULE_preprocess_node(&$vars){

    if(isset($vars['preprocess_fields'])){
        foreach ($vars['preprocess_fields'] as $key => $pre){
            if($pre == 'pre_rewards' && isset($vars['content']['get_reward_link'])){
                $reward_link = drupal_render($vars['content']['get_reward_link']);
                $vars['preprocess_fields'][$key] = $reward_link;

            }
        }
    }
    dpm($vars);
}

and the same thing the element won't be rendered! and it exists in the $vars variable when i debug!

also the new field created exists in manage field page of my content type :

So why it's always not rendering the content of this field in my page!?

Thanks in advance.

Seeing that you are using Display Suite, you should add the field via Display Suite as node.tpl.php is no longer being used. Display Suite has 4 Custom fields that you can add via the interface. You should look into the 'preprocess field'.

You need to define a preprocess field in Display Suite

and the machine name of the preprocess field

should correspond with the name of the field that you provide in your preprocess_node function:

function MYMODULE_preprocess_node(&$vars) {
  $vars['my_new_field'] = "some html or rendered field";
}

You are of course not limited to creating your field value in the preprocess_node function, you could just hand the value over like this:

function custom_preprocess_node(&$vars) {
  $vars['my_new_field'] = drupal_render($vars['content']['get_reward_link']);
}

The only limitation (AFAIK) is that you have to render the field before you let Display
Suite pick it up.

Once you have defined your preprocess field like this, Display Suite will make it available in the manage display tab for the node type.

Also look at Theming with Display Suite and Preprocess Functions


Creating a Custom Formatter to replace a Link with an Icon / Image I would like to replace links in a view I have created with icons. The links are dynamic(varying URLS) but will be be within 5 domains, eg:
www.example.com/page7
www.example.com/page2
www.example2.com/page9
www.example3.com/page77

I would like to provide an Icon for each of the Domains which is applied to the link, so that clicking on the link takes the user to the URL(in a new window) and the text is hidden.
I am aware of CSS image replacement technique but would like to use https://drupal.org/project/custom_formatters to do this. I am also aware of https://drupal.org/project/image_link_formatter .

Using the Custom Links Formatter module would allow me to import/export, save, reuse and share this function.

Just click on the rewrite results option in the view for the field you want the changes then just add the following :

 href ="www.example.com/page7 ">

In a similar way you can add images


Problem with trailing slash and global redirect I have a site with some languages, with language prefix enabled.
I wanted the homepage url will be with trailing slash (i.e /en/), so i installed the trailing slash module.

I also want that users who entered my site without language prefix will redirect to the url with the prefix (i.e www.mysite.com -> www.mysite.com/en/), so i istalled th global redirect module, which works well without the trailing slash module.

When the two modules enabled, the redirection in the home page not working. Does someone has solution for this?

if you are looking to redirect your users site or visitors to the right language you can do this without global redirect module
to do that

install [Localization update][1] , [variable][2] , [Internationalization],
after install modules active Locale , Localization update , Internationalization , Variable
go to Configuration > Languages > detection and selection
the 1st option URL u can choose between (Path prefix or domain)
the 2nd option is Browser and here u can Determine the language from the browser's language settings. if your browser's visitor is English he will go to English site ....
the 3rd option is User in this option the site Follow the user's language preference.

that's all


General error when creating an account I'm testing the creation of user accounts on the new website and I get a general database error after attempting to create an account. The error log shows:

  Sep 14 09:06:01 test drupal_www_example_com:
  https://test.example.com|1505379961|php|97.120.1.69|https://test.example.com/user/register|https://test.example.com/user/register|0||PDOException:
  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  'user-203409-0-0-und' for key 'PRIMARY': INSERT
  INTO {field_data_field_name_first} (entity_type, entity_id,
  revision_id, bundle, delta, language, field_name_first_value,
  field_name_first_format) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7); Array#012(#012
  [:db_insert_placeholder_0] => user#012
  [:db_insert_placeholder_1] => 203409#012
  [:db_insert_placeholder_2] => 203409#012
  [:db_insert_placeholder_3] => user#012
  [:db_insert_placeholder_4] => 0#012    [:db_insert_placeholder_5]
  => und#012    [:db_insert_placeholder_6] => betachristia556#012    [:db_insert_placeholder_7] => #012)#012 in
  field_sql_storage_field_storage_write() (line 514 of
  /var/www/html/example/docroot/modules/field/modules/field_sql_storage/field_sql_storage.module).

I looked in the user table and there is no user for the ID 203409.

The field_data_field_name_first field had some data stored in it for that user ID, apparently because it was migrated in at a later time than the user table or because I didn't drop the database before I imported new data. As a result, the system couldn't write to the database user table and field_data_field_name_first table. The solution was to do a fresh import of the user table and the first and last name custom fields.

This was on a test site.


How to use Drupal.behaviors? I am trying to do a simple ajax request when the document is ready. Along with that, I also want to provide a function that is an onclick event.

Here is my code:

(function ($) {

  Drupal.behaviors.user_alert_get_message = {
    attach: function(context, settings) {

            $.ajax({
               type: "GET",
               url: "/admin/user-alert/get-message",
               success: function(data){
                   $('div#block-user-alert-user-alert').html(data);
               }
             });

        $('div.user-alert-close a', context).click(function() {
          alert(1);
        });
    }
  };
}(jQuery));

The click function does not fire. The ajax does. What can I wrap the ajax in so it only does this on page load, or, is that assumed through attach?

I also tried an onclick on the a tag, but Firebug said the function was undefined, even when it was defined as function (function name) in the .js file.

Edit:

If you have a click event that accepts an argument, how can I pass that in?

As I understood it, Drupal.behaviors attach would allow the .click to fire on an element created at anytime. But just in case, I would try using .delegate(), as in

$('body').delegate('div.user-alert-close a', 'click', function() {
  alert(1);
});


Add custom ajax command to ajax response after webform is submitted What I'm trying to do is to invoke some javascript after a webform is successfully submitted by ajax.

To do that I followed this advice and created an EventSubscriber to intercept ajax response and add my custom command there. The problem is that on some reason I can't check if the webform is submitted (data are sent) or not.

  public function onResponse(FilterResponseEvent $event) {
    if($event->getResponse() instanceof WebformSubmissionAjaxResponse &&
       $event->getResponse()->getWebformSubmission()->isCompleted()) {
         $event->getResponse()->addCommand(new MyCustomCommand());
    }
  }

The problem is in isCompleted() method which always returns false on some reason. Actually I checked other methods from WebformSubmissionInterface and in this my event subscriber this WebformSubmission entity always looks empty (getters return nothing) and geState() always returns "STATE_UNSAVED" not depending if a webform is successfully sent of failed on validation.

What I'm missing? Is anything I'm doing wrong here? Or maybe are there any other method to achive same goal?

I had this same issue, what worked for me was under webform settings > Confirmation > Confirmation Type. Change the confirmation type to 'Inline (reloads the current page and replaces the webform with the confirmation message)'

This returned true for $event->getResponse()->getWebformSubmission()->isCompleted()


file_create_url printing different addresses on live and local installations I'm using the following code to print out the path of an image uploaded through theme-settings.php:

<img src="<?php print file_create_url(file_build_uri(theme_get_setting('my_setting')); ?>" />

Locally, everything works fine -- the path renders as I expected:

http://localhost/drupal/sites/default/files/image.jpg

When the site is online, however, the same code renders the following address:

http://www.mydomain.com/sites/default/files/public%3A//image.jpg

Does anyone know why public:// would be printed out on a live server but not on a local installation? My guess is that the problem is related to the use of file_build_uri.

I'd like to find some code that prints out the URL correctly on both live and local installs. Perhaps I'm not using the best approach with the API to achieve this end?

The following code worked on both the local and live install:

<?php print file_create_url(theme_get_setting('my_setting')); ?>


Is there a reference by url widget type for term reference field as we have it for node reference field? Is there a module for term reference as we have "Node reference url widget" module for node reference field. So that I can auto-populates a term reference field with a value from the URL.

Closest thing is RSpliet's sandbox module:

https://drupal.org/sandbox/RSpliet/1416486


How to troubleshoot my VBO operation which freezes at 50% every time? I have written custom code that creates a new action for Views Bulk Operations (VBO). I am trying to run the action and it gets stuck at "Prepared 46748 out of 46766".  If I run the same action with 25 or 100 records it works perfectly.

Code has been changed but not that directly impacts this process. I do not know what code causes the regression and too many changes have been made to go back one commit at a time.

There is nothing Watchdog related to this process.

A little more on the custom action. The custom action adds the nid for each node to a queue to be processed fully over many cron jobs. I think the issue stems from the fact that every time a node is prepared by VBO it does a node save but I do not know what is happening to be sure.

I am looking for advice on how to troubleshoot this scenario and find a solution.

Try to (temporary) increase the available memory with like 10 or 25%, and see if you get past that nr of 46748 (possibly even past 46766). If it doesn't help, it won't hurt ...

BTW, even though this question is not about using Rules in combination with VBO, you might want to also watch the video about "More details about VBO settings" (especially what is explained between (about 04:00 and 05:00). It provides some extra hints / tips to process like 100.000 nodes at once, which is quite a challenge to get to work (memory requirements, etc).


Exclude specific nodes from a view based on role permissions I am using View access per node to hide certain nodes from the general public and allow specific roles to view it, which is simple and works like a charm.
The issue is that those nodes are shown, even when browsing with anonymous user. I can't find a way for the view to identify the "View access per node" status for each row.
I thought to change my approach; I was looking through the Comparison and Overview of Access Control modules, but any non-deprecated option available in Drupal 8 seems an overkill for this case.

Views does not respect hook_node_access which is what this module uses. Module creator should've used hook_node_access_records along with hook_node_grants instead.
You could try comment #3 as a workaround.

/**
 * Implements hook_views_pre_render().
 */
function example_views_pre_render(ViewExecutable $view) {
  $user = \Drupal::currentUser();
  $vapn_config = \Drupal::service('config.factory')->get('vapn.vapnconfig');
  $vapn_node_types = $vapn_config->get('vapn_node_list');

  foreach ($view->result as $key => $row) {
    if ($row->_entity) {
      $is_vapn_bundle = FALSE;
      if ($bundle = $row->_entity->bundle()) {
        $is_vapn_bundle = in_array($bundle, $vapn_node_types);
      }

      if (!$row->_entity->access('view', $user) && !$view->query->options['disable_sql_rewrite'] && $is_vapn_bundle) {
        unset($view->result[$key]);
      }
    }
  }
}

credit: ash2303


File upload with ajax Is there any example how to set up form element with type file to upload it via AJAX. I want to be same as field image in node type article.

thx

Maybe this will be helpful (in a custom module):

function testmodule_forma($form, & $form_state) {
    $form['im-container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $form['image_file'] = array(
        '#type' => 'file',
    );

    $form['upload'] = array(
        '#type' => 'submit',
        '#value' => 'upload',
        '#submit' => array('upload_image'),
        '#ajax' => array(
            'callback' => 'upload_image',
            'wrapper' => 'im-area',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );
    return $form;
}

function upload_image($form, $form_state) {

    $file = file_save_upload('image_file', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", FILE_EXISTS_REPLACE);
    if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
        $form['im-container'] = array(
            '#title' => t('Preview:'),
            '#prefix' => '
',
            '#markup' => ' filename.
            '" height="250" width="250" />',
            '#suffix' => '
',
        );
    } else {
        drupal_set_message('No file uploaded.');
    }

    return $form['im-container'];
}


How do I add an anchor attribute to a route? I've created a route:

regions.taxonomy_term.edit_form_header:
  path: '/taxonomy/term/{taxonomy_term}/edit'
  defaults:
    _entity_form: 'taxonomy_term.default'
    _title: 'Edit term'
  options:
    _admin_route: TRUE
  requirements:
    _entity_access: 'taxonomy_term.update'
    taxonomy_term: \d+

But now I can't add to path anchor attribute.

For example:

path: '/taxonomy/term/{taxonomy_term}/edit#header'

Thanks everyone!

I have solution my for problem.
You just had to add it to this my_module.links.contextual.yml file.

regions.taxonomy_term.edit_form_header:
  title: Edit this block
  group: region_taxonomy_term
  route_name: regions.taxonomy_term.edit_form_header
  weight: 10
  options:
    fragment: 'edit-group-header'


How to hide "Counter" and "Date" on certain page/node? How do I hide the "Count content views" of a certain page/node?

I want to hide the numbers of reads along with the date the page was updated without effecting other pages on the site.

You need to interact with the theming layer (template.php in theme)

As you want to alter an element within a node, you may use function template_preprocess_node(&$variables) to alter, remove or disable that element. You will need to do a conditional test first ($variables['node']->nid) and check $node->nid against the nid of your specific node page. You can then look for the element within $node.

You may also just use Drupal 7 Template (Theme Hook) Suggestions, if the element you wish to hide is a standalone element (ie not embedded in a larger render array), in which case you will copy over the base theme's node template and just comment out/alter the bit in question - for node it is node--[type|nodeid].tpl.php.

When working in the theme layer remember that your theme always has the last say so you can safely make alterations knowing that you cannot cause problems for any other modules or base themes in the process.


How to change head title of a page having a Omega 4 subtheme? I'm trying to implement this: http://ryanissamson.drupalgardens.com/blog/html-node-and-view-title to add the possibility of having HTML injected in node titles. It works great for the node titles in the pages and the views.

But there's something I cannot accomplish: the "$head_title" part. I can't change the text of the title showed in the browser tab, so, assuming that I have a mid-italic title like "Title", in the browser tab it shows something like "Ti[i]tle[/i]".

I think it's because Omega 4 uses the Layout system, that works perfect, and we don't have to override page.tpl.php, as seen in How do you override page.tpl.php in Omega 4?

Here people say to this guy to disable Layouts, but for me that's not an option at this moment.

Any ideas? Thanks.

Changing head title for a page in Omega 4 based on node id - same approach will work for any other content. (code below goes into template.php)

Didn't test if this method supports described above HTML injection.

    function yourtheme_preprocess_html(&$variables) {
        if ($node){
        $mynodeid = $node->nid;
// this will set "Custom Title" for a node with NID = 10
        if($mynodeid == 10) {
            $variables['head_title'] = t('Custom Title');
        }
      }
    }


Date popup select wrap I want to wrap date popup selects in <div> to customize drop-down button of the select. But I can't find where to wrap it. I don't want to use jquery for such.

You're going to need to override an existing theme function in order alter the HTML output for the date popups. You can override a theme function either from within your template.php file within your theme, or from within a custom module.

Whenever I need to identify the correct theme function to override in a hurry, I use a module called Devel Themer. It allows you to click on any on page element, and provides you with a great break down of all the theme functions and variables associated with the element you're trying to override.

Hope this helps.

EDIT: including theme function link

The theme function you need to override is theme_select


Drupal 7 Display a block on custom tab I would like to display a view block on a custom tab I created as follows, but the tab is always empty. The block has the option to be shown only on specified path node/%node/calendario-corsi. Is it correct to have an empty page callback?

function custom_morebuttons_menu() {

  $items['node/%custom_node_calendario_corsi/calendario-corsi'] = array (
   'title' => 'Calendario corsi',
   'page callback' => 'custom_node_calendario_corsi_page',
   'page arguments' => array(1),
   'access callback' => 'user_is_logged_in',
   'type' => MENU_LOCAL_TASK,
   'weight' => 10,
  );

  return $items;
}

function custom_node_calendario_corsi_load($arg) {

  $node = node_load($arg);

  if($node->type == 'centro' || $node->type == 'sede') {

    return $node; }

  return FALSE;
}

function custom_node_calendario_corsi_page($arg) {

  return '';
}

Should be next:

function custom_morebuttons_menu() {
  $items['node/%node/calendario-corsi'] = array(
    'title' => 'Calendario corsi',
    'page callback' => 'custom_node_calendario_corsi_page',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

  return $items;
}

function custom_node_calendario_corsi_page($node) {
  $node = node_load($arg);
  if (($node->type == 'centro') || ($node->type == 'sede')) {
    // I assume you will add some behaviour code for this, next make no sense.
    return $node;
  }
  return false;
}


Recursion when reading field in hook_entity_load Is there a preferred approach modifying values?

I need to modify a value when a node loads, but must use other values from the node.  The code below causes recursion errors.

function zzzmodule_entity_load(array $entities, $entity_type_id) {

  foreach ($entities as $entity) {

    if ($entity_type_id === "node" && $entity->hasField('other_field')) {

      $t = $entity->title->value;
      $o = $entity->other_field->value;

      if (empty($o)) {

        $o2 = json_encode($t);

        $entity->set('other_field', $o2);
        $entity->save();
      }

    }

  }

}

Your code works just remove the $entity->save(); and it works i have tested it:

function zzzmodule_entity_load(array $entities, $entity_type_id) {
  foreach ($entities as $entity) {
    if ($entity_type_id === "node" && $entity->hasField('other_field')) {
      $t = $entity->title->value;
      $o = $entity->other_field->value;
      if (empty($o)) {
        $o2 = json_encode($t);
        $entity->set('other_field', $o2);
      }
    }
  }
}


how to open drupal login and signup form on modal form. I just want to open login form in modal box as per semantic ui framework http://semantic-ui.com/modules/modal.html. I just want to use this framework. Is this possible with theming or custom module is require for this.

Any help would be appreciated.

You should include the necessary javascript in your theme .info file or template or module with drupal_add_js() , then you should use the code defined in the link you provide to target the element that you want to apply the functionality too. This elememnt may be generated by a module that specifies a theme function and uses a template (tpl.php) file in which you would put your markup.


Add extra custom permissions to Field Permissions I'm using Field Permissions module to restrict access to each field.
If you choose custom permission on /admin/structure/types/manage/CONTENT_TYPE/fields/FIELD_NAME, you'll see these permissions are available:

Enter own value for field [FIELD_NAME]
Edit own value for field [FIELD_NAME]
Edit any value for field [FIELD_NAME]
View own value for field [FIELD_NAME]
View any value for field [FIELD_NAME]

I would like to add some permissions with extra conditions like 'Edit any value for field [FIELD_NAME] if the field is empty'.
For D7 version of the module there was a hook called hook_field_permissions_list_alter but there's no such thing in D8 version.
Is there any way to modify the list?

With Drupal 8, the module implemented the permission type plugins. To add more permissions, you implement a new permission type plugin, using one of the existing plugin classes as example, such as Drupal\field_permissions\Plugin\FieldPermissionType\CustomAccess or Drupal\field_permissions\Plugin\FieldPermissionType\PrivateAccess.  Drupal\field_permissions\Plugin\FieldPermissionType\Base is used as base class, and simplifies the creation of new permission type plugins.
Note that the module invokes the hook_field_permission_type_plugin_alter() implementations, as described in the field_permissions.api.php file. That hook can just be used to remove a permission type plugin, or change the plugin properties given in its annotation (which doesn't include the permissions exposed from the plugin, for what I can see).


Where does field help text get filtered? Drupal 7 fields, by default, have a nice text box beneath them for Help Text.  This is set up with field_ui_field_edit_form():

$form['instance']['description'] = array(
  '#type' => 'textarea',
  '#title' => t('Help text'),
  '#default_value' => !empty($instance['description']) ? $instance['description'] : '',
  '#rows' => 5,
  '#description' => t('Instructions to present to the user below this field on the editing form.
Allowed HTML tags: @tags', array('@tags' => _field_filter_xss_display_allowed_tags())),
'#weight' => -5,
);

Widget forms then can use this when they actually get used, such as from file_field_widget_form():

if (empty($element['#default_value']['fid'])) {
  $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
}

Which then get themed, such as with theme_file_upload_help()

if (strlen($description)) {
  $descriptions[] = $description;
}
if (isset($upload_validators['file_validate_size'])) {
  $descriptions[] = t('Files must be less than !size.', array('!size' => '' . format_size($upload_validators['file_validate_size'][0]) . ''));
}
if (isset($upload_validators['file_validate_extensions'])) {
  $descriptions[] = t('Allowed file types: !extensions.', array('!extensions' => '' . check_plain($upload_validators['file_validate_extensions'][0]) . ''));
}

The trusty eye will notice that this is user supplied text and it is not being filtered (oh noes!).  Don't worry, it gets filtered somewhere (I actually tested this to be sure).

Where / how does this filtering happen?

In function field_default_form in field.form.inc
line 107

'#description' => field_filter_xss($instance['description']),


How to hide the "trimmed version" from the preview page? When I "preview" a node add/edit form it shows a "trimmed version" and a "full version". I don't want to show the trimmed version.

The fix suggested for D6 doesn't work for D7. Any ideas?

You tried CSS?

.preview h3 , .preview .node.node-article.node-teaser {display: none}

In my case the content type is an article and worked.


Implement Twig format in view exposed filter I have search view UI with two filter criteria.

Basically, to output contents in the page we write {{ page.content }}, which I currently used.

What I want is to slice the page.content in divs. Search filter will be displayed in, say

 and its result will be on

.

I found this: Twig Field Value, but confused how to implement it the right way.

In the image below, they are in called in {{ page.content }}, so I want to separate the search filter and its result.

Anyone knows how to properly write search UI and its specific fields(as an output) with twig format?

For example if you use the preinstalled view Search Content, then put the file views-view--search-content.html.twig in the template folder of your theme and add the div containers:

{%
  set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id,
  ]
%}

  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}

      {{ header }}

  {% endif %}

    {{ exposed }}
    {{ attachment_before }}

    {{ rows }}
    {{ empty }}
    {{ pager }}

  {{ attachment_after }}
  {{ more }}

  {% if footer %}

      {{ footer }}

  {% endif %}

  {{ feed_icons }}


How to make possible to flag only one node I have a view with lists of 10 nodes with a node display type (not rows). Every node has a flag. How to make possible to flag ONLY one node of these 10 nodes, for example if you have flagged one node - you cannot flag another one untill you unflag flagged one. Just like a best answer functionality on this site. Thanks :)

You're looking for the Flag trim action, which you can implement with Rules.

If you make a rule that is activated on the event "Node is flagged" with "Trim the flag" for the relevant user to "1", then the other flags will be cancelled and only the most recent flag will remain.


Drupal as a 3-tier system model We are planning to create an 'agency' site on drupal. The 'agency' site will serve as 3-tiered system model composed of the following levels:
1. Agents (users)
2. Agency (agent users will belong to a specific agency)
3. Super Administrator (controls everything, permissions etc)

The idea behind the site is to have the ability to register an 'agency' (only by the super admin), that will in-turn have the ability to create their own users (Agents).

If Agency1 logs in, he should be able to register their own sets of users. So goes with other agencies. New users created should belong exclusively to their respective agencies, automatically upon registration.

Are there any modules out there that can be configured to do this? I have 'Profile 2' Module but I don't think this fits the bill. I am looking at the Groups Module but not sure if this is really the right one.

You could use Organic groups.

In that case, every agency would be a group with a group administrator that could set the users that are part of that agency. Every agency could have its own content, which would be created from the users that are associated with the agency. A user of another agency would not be able to create content for another agency, if not in the case the user is member of both the agencies.


Image Styles not creating on one custom style only I've run into this issue where we have created a custom style (emailthumb) which is to be used when sending out email newsletters via simplenews. The thumbnail is based on 'thumbnail' style but is slightly bigger. It works fine when the image is being rendered as thumbnail or any other style but not the one custom style.
The permissions of the folders are all exactly the same (I've even tried 777 for emailthumb->public) as in thumbnail but there is no pictures folder being created. I then get a log error of access denied as the URL to the image as the folder doesn't exist.
http://example.com/sites/default/files/styles/emailthumb/public/pictures/image.jpg
I have tried changing the theme as per
image style (imagecache) images are not being created
but this has not worked.
Does anyone have any suggestions?
Current Permissions
sites/default 555

The problem was that the image style was never being called to save the image in the first place. The following code forces the image to save for this use case.

function MODULE_node_presave($node){
  // Get some field items from a field called 'field_image.
  if ($image_items = field_get_items('node', $node, 'field_image')) {
    $image_item = array_shift($image_items);

    // Load the associated file.
    $file = file_load($image_item['fid']);

    // An array of image styles to create.
    $image_styles = array('emailthumb');

    foreach ($image_styles as $style_name) {
      // Get the location of the new image.
      $derivative_uri = image_style_path($style_name, $file->uri);
      $style = image_style_load($style_name);
      // Create the image.
      image_style_create_derivative($style, $file->uri, $derivative_uri);
    }
  }
}

credit here force image style generation on save node


Can error messages be avoided for custom modules in the Update manager? On my "Available updates" page I get error messages when there are custom modules in use:

  Failed to get available update data for one project.

Is there any way to avoid this?  Either by setting up some sort of feed for custom modules (probably not practical in most situations!) or by excluding custom modules from the list?

(As an aside, it seems like a design flaw in the Update manager module to give an error for custom modules.  If they are in the custom directory inside modules then it can easily determine that they are custom, and clearly should not expect to receive update data for them from the same source as contributed modules.)

Is there any solution to this other than filing a bug report and hoping the maintainer agrees with my perspective?  (Or hacking the module myself.)

Using the tip that junedkazi gave (please up-vote his answer too if this helps you!), I add this line to the .module file for my feature module:

include_once('<my_module>.exclude_from_update_list.inc');

And in the file <my_module>.exclude_from_update_list.inc:

<?php
/**
 * @file
 * <my_module>.exclude_from_update_list.inc
 */

/**
 * Implements hook_update_projects_alter().
 */

function <my_module>_update_projects_alter(&$projects) {
  unset($projects['<my_module>']);
}

And it worked perfectly.  I took the precaution of backing up the database first, and of course I did this in a non-production environment.

This is all pretty obvious once you know about that hook, but I'm putting the code here for sake of a more complete reference, hoping it speeds things up for someone else.


Place to put patched module under contrib or custom I am using a contrib module which has a patch in queue to be reviewed, the patch solves my issue. Where should I keep the patched module, keep it inside contrib module or should I move it under custom module directory and keep a watch on issue till it approved and then move it again to contrib? What is the preferable place to keep such module.

You may leave it in place (a good reason for doing this is given in the reply from alexkb).

However, this is not all there is to working with patches.  Sometimes the maintainer is reluctant to include the patch in the official branch.  This means that there may be new releases (security fixes!, bug fixes, feature enhancements) of the module without the patch.   You need to think about how you deal with that.

Here is what I do: I set up staging area for where I keep all my custom modules.  For the patched contrib modules, I connect those to the origin repo using git. I also setup a Makefile (or some other script file) to pull from the origin repo and semi-automate the reapplication of outstanding patches. Then, when a new release of the module is issued, the Makefile will pull and patch, and then send an email to me with the result.  If the patch applies succesfully, I test and if the test turns out OK, I manually copy from staging to production.  If the patch fails to apply due to some conflict, I try to resolve conflicts and try again.

This has two advantages:

Even when you're using a patched module, you're able keep up with the official branch.
You don't have to watch the issue queue, just set up your local repo to sync with origin at regular intervals (using CLI cron or similar).

The above workflow assumes some familiarity with the CLI and tools such as git, cron and make.  It also takes some times setting this up to run semi-automatically.  But if you need to work with patches, it is - IMHO - well worth doing.


How to print URL arguments in headers VIEWS I have a blog with URL http:/node/add/blog and I am using a view discussion board to display the content of blog using VIEWS.

I want to add this URL http:/node/add/blog to  Header view. Any idea? How to do it?

You can use arg() function to access the url parameters.

Returns a component of the current Drupal path.

When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".


How do I add menu-entry to the admin menu with node reference? Task:
I want to add an edit option in the admin menu that would only appear while viewing a node while logged in as admin.
The link of the edit item can be like node\%\edit so that clicking on the link would take the user to its edit page.

You could use the Menu Token module to achieve the same:

Install the module and its dependency, i.e. the Token module.
Create a new menu item with path node/[node:nid]/edit.
Place the menu block which contains the menu item in any region of your choice.
Drupal menu system takes care of showing the menus as per the access; which means that only users which have permission to edit the node should see it.

The image below is an example shown on the project page. You could use it as a guide.


Hide a row from view display I have a view which presents values of specific content type, nothing special, just a normal regular view with a table display. Later on I added to it a field from views field view module. Everythink works as expected. Now I need to hide every row which has an empty value of this views field view field?

Any ideas how can I do it?

I tried to use hook_views_pre_render but in this case I can only get an access to values of fields from parent view not from the one which comes from views field view.

Any help will be appreciated!

P.S. The question applies to Drupal 8

You can do it in a preprocess template function.
e.g.

/**
 * Implements template_preprocess_views_view_table()
 * @param $variables
 */
function TEMPLATE_preprocess_views_view_table(&$variables){
  /** @var ViewExecutable $view */
  $view = $variables['view'];

  //Do no alter other views
  if ($view->id() !== 'YOUR_VIEW_ID') return;

  $rows = $variables['rows'];
  foreach ($rows as $key => $row){
    if (empty($row['columns']['VIEWS_FIELD_VIEW_FIELD_NAME']['content'])){
      unset($variables['rows'][$key]);
    }
  }
}

Replace
TEMPLATE with your module name or theme name.
YOUR_VIEW_ID with your view id
VIEWS_FIELD_VIEW_FIELD_NAME with the name of your field

Hope that helps


Facet API: grouping indexed values into several drop-down facets I have an indexed field which contains values in such a form:

CPU: Intel Core i5
CPU: Intel Core i7
...
Memory: 4 GB
Memory: 8 GB
...
Video card type: Integrated
Video card type: Nvidia
...

I would like to display these as several drop-down lists, e.g:

Title: CPU  with values: Intel Core i5, Intel Core i7, ...
Title: Memory with values: 4 GB, 8 GB, ...
Title: Video card type  with values: Integrated, Nvidia, ...

Any suggestions would be welcome on how to implement this.
Thank you very much in advance.

Best regards,
Laszlo

If possible, I'd use a vocabulary for each of the facets ('dropdowns'). Add a term referenece field to your node for each of those as well. Then add these fields to your search index and add the facets for them.

E.g.,
Vocabulary:
CPU

Terms:
Core i5
Core i7
...

Vocabulary:
Memory

Terms:
4 GB
8 GB
..


How to submit a node form with AJAX Drupal 7 How can I set up a node form to submit via ajax. I can't find examples that show how to do this explicitly.

Check out this article.

http://drupal.org/node/752056

It should get you started.


How to programmatically submit the file system settings form? I am trying to enable private files via features, in code, or with drush but am getting errors.

With drush:

drush vset file_private_path sites/default/files/private

In code:

variable_set('file_private_path','sites/default/files/private');

The problem is that when you set this configuration manually, the file system settings form gets saved and it creates an .htaccess file in that location. When you set it in code, it doesn't create the .htaccess file until you visit the admin/config/media/file-system page, which it returns an error the first time:

Warning: file_put_contents(private:///.htaccess) [function.file-put-contents]: failed to open stream: "DrupalPrivateStreamWrapper::stream_open" call failed in file_create_htaccess() (line 502 of /sandbox/d7/includes/file.inc).

Is there a correct way to be doing this programmatically? Thanks in advance.

I would not re-create what the form does by hand as @Ayesh does. There is a small chance this form will do more things in a future minor drupal release date (maybe that should never happen, i'm not 100% sure).

What you want to do is look at drupal_form_submit() to programmatically submit a form -- its like visiting the form in a webpage and submitting it without ever opening a browser window. Whatever logic that form does upon submission -- will still happen, eg. create an .htaccess file for you.

You would put the following code into your module install() hook, or you could drush ev this code or make a small php script and run drush php-script myscript.php

Code:

$form_state = array();
$form_state['values']['file_private_path'] = 'sites/default/files/private';
$form_state['values']['op'] = t('Save configuration');
drupal_form_submit('system_file_system_settings', $form_state);

You can then re-submit the form and set the default file serve mode from public to private. Or I would use drush vset or just variable_set somewhere in PHP to set the default file serving mode in drpual. My point is that this is the correct way to programmatically submit a form.


Is it possible to create an auto-increment field in a content type? If I am creating a database in MySQL, I can create an auto-increment field for a table.

But is it also possible to create an auto-increment field in a content type in Drupal 8?

There is A module called Serial, for drupal 8 it is in development version but can be downloaded and used, This module provides the same functionality as you desire.

You also can write your own module, you can set a configuration value in your module, set it to zero by default, and using hook_ENTITY_TYPE_presave, increase its value and set it to your entity.


Using '/profiles' in a URL alias The path '/profiles' exists as a physical folder in the root of a Drupal install, which means adding a URL alias for a piece of content to '/profiles' will not work - a 403 error is the result.

Lucky 'ol me, for a particular project I have an SEO partner telling me that using that particular path is an absolute, categorical must; not having this would be proof that the Myan's doomsday prediction is in fact accurate, we'll all die slowly, etc., etc.

So I'm going to go ahead and throw this slightly ridiculous question out to the masses to see if anyone's found a creative way to solve this problem before...

How can I use '/profiles' (and '/profiles/*', etc.) as URL aliases, while maintaining a fully functional, update-able Drupal instance?

Importantly, we're using the Global Redirect module, with the 'De-slash' and 'Non-clean to clean' options enabled (and they need to stay that way).

1) .htaccess (before line 100):

RewriteRule ^profiles($|/(.*)) /index.php [L]

2) VirtualHost (for de-slash setting):

<Location /profiles>
     DirectorySlash Off
</Location>

Second part is needed only if you use Global Redirect "de-slash".


Zen sub-theme block page problems I have just began re-themeing a client website with a Zen STARTERKIT.

I noticed the drag'n'drop handle for grabbing and moving blocks is not showing up.
This of course means I can't reposition blocks.

I scrapped the theme and started again with a fresh install of Zen but I got the same problem.

Can anyone help me?

It is likely that something in the sub theme is wrong. There are several steps to go through. They are detailed in  starter kit readme.


Override Theme table function used in contributed module? There is function used in Ubercart module :

function theme_uc_recurring_user_table($variables) {
    ........
}

I want to override result of this function and did by below method in template.php file of my theme:

function MYTHEME_preprocess_table(&$variables) {
  global $user;
  if ($user->uid) {
    if (current_path() == "user/me/recurring-fees") {
      if(!$variables['header'][7]) {
        $variables['header'][7] = "Donation";
      }
      if(!$variables['rows'][0]['data'][7]) {
        $variables['rows'][0]['data'][7] = l('Update Donation', '/donation');
      }
    }
  }
}

I just added table column header and data below that. But I did this by current path but I think there must be some right approach.

I am trying to find but not able to figure out how exactly we can achieve this.

Please suggest !! Thanks

theme_uc_recurring_user_table() is a theme hook (not a table function), and its preprocess function is hook_preprocess_uc_recurring_user_table().
From the preprocess function you can just change the content of $variables which, in the case of theme_theme_uc_recurring_user_table() just contains $variables['uid'].

What you need to do is overriding the theme hook implemented from the module, which is quite easy, since you are doing it from a theme.

function MYTHEME_uc_recurring_user_table($variables) {
  $uid = $variables['uid'];
  drupal_add_css(drupal_get_path('module', 'uc_recurring') . '/uc_recurring.css');

  // Set up a header array for the table.
  $header = array(t('Order'), t('Amount'), t('Interval'), t('Next charge'), t('Status'), t('Remaining'), t('Options'));

  if ($GLOBALS['user']->uid) {
    $header[] = t('Donations');
  }

  $recurring_states = uc_recurring_fee_status_label();

  // Build an array of rows representing the user's fees.
  $rows = array();

  foreach (uc_recurring_get_user_fees($uid) as $fee) {
    // Get the user operations links for the current fee.
    $ops = uc_recurring_get_fee_ops('user', $fee);

    // Add the row to the table for display.
    $rows[] = array(
      'data' => array(
        l($fee->order_id, 'user/' . $uid . '/order/' . $fee->order_id),
        theme('uc_price', $fee->fee_amount),
        array(
          'data' => check_plain($fee->regular_interval),
          'nowrap' => 'nowrap',
        ),
        format_date($fee->next_charge, 'short'),
        'status) . '">' . $recurring_states[$fee->status] . '',
        $fee->remaining_intervals < 0 ? t('Until cancelled') : $fee->remaining_intervals,
        array(
          'data' => implode(' | ', $ops),
          'nowrap' => 'nowrap',
        ),
      ),
    );
  }

  if (empty($rows)) {
    $rows[] = array(array(
        'data' => t('Your account has no recurring fees.'),
        'colspan' => 7,
      ));
  }
  elseif ($GLOBALS['user']->uid) {
    $rows[0]['data'][] = l('Update Donation', '/donation');
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}


Drupal 8 dropping session variables on password reset. Gives 403 Access Denied I have a fresh install of Drupal 8.6.13, default everything with no custom themes or modules. It was created via:

drupal-composer/drupal-project:8.x-dev with the drupal site:new command.

When I use a one time login link I get a 403 access denied error because the session data (timestamp and hash) gets lost on the redirect from UserController::resetPass to UserController::getResetPassForm.

Here is the source code for reference: https://api.drupal.org/api/drupal/core%21modules%21user%21src%21Controller%21UserController.php/8.6.x

When I log the session variables when they are created in resetPass they are stored and show correctly.

When I then log the session variables on getResetPassForm they are no longer there. This causes the following code to execute which returns the 403:

if (!$hash || !$timestamp) {
  throw new AccessDeniedHttpException();
}

I'm not sure if this is a Drupal problem or Symfony problem or what.

Everything has worked fine on previous versions of Drupal 8.6.x. I noticed the issue when upgrading from 8.6.8 to 8.6.13. I have now tested with just a fresh install of 8.6.13 and am seeing this issue.

Server is Nginx.

Any ideas?

This is an issue with symfony/http-foundation v3.4.24. See https://www.drupal.org/project/drupal/issues/3045844.


Different suffix for multiple field value I have multiple field value -3 value-, each value have a defferent suffix. For exemple there is a field vessel consumption with 3 value, each value have a unit of measure: HFO or MGO, MDO.
Is there a way to show every value with a suffix or I have to use text field type?

You could use field collection and create two fields, one for the value and one for the suffix.


How do I create separate node/add forms for different uses and for the same content type? I am using the agreservation module for a room reservation system/events calendar. As a result, the reservation content type has a large number of fields to accommodate info on speakers, contact info for participants, etc.

I have two uses for creating reservations: events, where more information is needed; and room reservations for maintenance issues, which require less info. However, having all of this info on one content type is essential: both uses require the room reservation and resource conflict functionality.

Restricting fields by role isn't an option as I have users who will need access to all fields; but when doing their work, both uses will be easier and quicker by having separate forms. It's more of a usability thing: people don't have to see fields they don't need for a particular use. Mainly, if someone needs to reserve a room for maintenance, the person making the reservation doesn't need to scroll through all of the fields for the event.

So, if a reservation node has fields a-j, how can I create separate node add forms so that fields a,b,c,d,e and f needed for creating registering an event are on one instance of the form and e,f,g,h,i and j are on another instance for the room reservation? There is overlap because the event involves the reservation of a room.

I thought about doing this via theming, but can a template be tied to a menu item?

You can use panels to create different a different views of the node add/edit forms. I've done something similar before but I had to add a query string to the URL and show the different view that I had setup. I will try to update with more information later.

Update with Instructions of how this can be done

Here is an overview of how I achieved this before. I used panels Panels and Context modules to set up this and show two different views for the node edit forms (Keep in mind your required fields will need to be present but this is just an overview of how you can achieve something like this.) First, some knowledge of both of these modules will be needed but you can learn as you go. First thing that I knew I needed was exactly what you said, two different node edit/add views where different fields showed at different times depending on the job being accomplished. I am going to run through a simple scenario that probably won't make much sense but it will show that it can be done with using these two powerful modules together.

First, I set up a context based on a query string. Go add a context in the context UI and add a condition based on query string. Then place your query string (mine is "view=maintenance") and not sure if you have to but I went ahead and added a body class by theme HTML in what the context does (you will see that in the context UI but you are going to really use this context in panels so just save it to use later).

Next go to Page manager and there is a page that you can use called Node Edit, you will need to turn this on and create your variant. You will want to choose node type in the context and restrict this to only the content type you want this to work with since it is specific to just that node edit form. For one of my views I wanted the whole form was needed. Use add content, Forms, and add general form. Now you have the form you had before just being controlled by panels. You will want to add a visibility rule and choose PHP code for the visibility rule. Then you can use the code below to find out if your context is present (Use Not if you want the full form to show without the query string).

$contexts_module = context_active_contexts();
if (array_key_exists('machine_name_of_context', $contexts_module)) {
  return TRUE;
}

So now you have the full form showing with or without the query string. At this point the form should not show on the other context. This is the only part that I don't really like but it works and its been the only way without writing a whole bunch of code that I have found can be flexible enough for others to change after I hand a site off to a client. You will have to add the fields that you want to show when the query string is present or not present (depending on what you chose earlier) and copy the code from above and either choose NOT or not choose NOT and also add the node submit buttons and choose that as well. (You of course can set each field up and hide the fields you want according to the query string or some other way, just play around with it until you learn it and understand what it can do).

I'm not really great at writing these instructions but hopefully you understood what it can do and how to do this. I will try to revise them over time to help future viewers. I am also including some screenshots below that will show this in action.

Context UI Query String setup

Panel variant for clarity

This shows the whole form when the query string is present

This is the not code, so when query string isn't present show this

Shows url query string but (a partial screen shot) full form is shown to user

Shows form trimmed down for normal use


How to check that cache is working on current page? Some modules silently turn off caching on certain pages. How is the easiest way to check that this is the case and also identify problematic module?

The easiest way is probably to inspect the HTTP response headers.

For example, with your browser DOM inspector tool ( e.g Chrome's "Network" tab )

Cache Miss

Here's some sample response headers from drupal.org showing a cache miss. In this case, using Varnish however core Drupal cache also sets similar headers.

Cache Hit

Here's one showing a standard Drupal cache hit:


hook_theme() to twig template of eform I have an eform printing out some fields. I want to create a module to change layout of the eform using hook_theme(). So, I have hook_theme() in my mymodule.module file and mymodule-form.html.twig file in template folder. Since I'm testing it, I only want to print out one field. But it prints out all of the field which seems like hook_theme() or twig is not working. Here's my code.

mymodule.module

<?php

/**
  * Implements hook_theme()
  */
function gq_theme($existing, $type, $theme, $path) {
 return array(
    'gq_form' => array(
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

/**
 * Prepares variables for the gq form template.
 *
 * Default template: gq-form.html.twig.
 */
function template_preprocess_gq_form(&$variables) {
  $variables['first_name_field'] = $form['field_first_name'];
}

mymodule.html.twig

{{ first_name_field }}

Also, I only have two files, mymodule.module, mymodule.info,yml, templates/mymodule-form.html.twig in module directory. Are there some necessary files?

Assuming that your template file is in a subfolder of your module folder (it looks like it's in templates), then your hook_theme needs to define the path. So it should look some thing like:

function gq_theme($existing, $type, $theme, $path) {
  return array(
    'gq_form' => array(
      'path' => $module_path . '/templates',
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

where $module_path is the path to your module.


How to add Wishlist button field in views in drupal 7? I am working on commerce site. In my site I have 3 views & each view have display 3 products. If user can first visit the product then user get the wishlist button but I want to show "add to cart" or "wishlist" or "buy" button with all the products so user can directly purchase, no need to visit.

I already created Relation : "Content: Referenced products" & add Field : "Commerce Product: Add to Cart form". But no button show below product. Please help to solve. Thanks

Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display_suite or panels to get more advanced control over what your products look like when rendered.

Sidenote, there's a great video I created that shows you how to use hook_form_alter to move the wishlist button around.


Multiple Arguments with Views I created a views page displaying "full posts" of any content type.

Next I gave the page URL to be "test/%"

Next I added a contextual filter for Nid

Check "Specify validation criteria" below
"validator" set to content
and "Filter value format" i set to "node IDs separated by , or +"

Now in my preview I put "1+2+3" and I only get node 1. Node 2 and 3 dont show up.

site.com/test/1+2+3 also only gets node 1

How can I get multiple nodes on 1 page?

Did you check the 'Allow multiple values' checkbox in the 'More' section of the contextual filter setup?  The 'More' section is collapsed by default, so it's easy to miss...

You have to check that box:


Display Suite and Views - how to troubleshoot why a View content pane is not being applied? I have a site that uses Entity Reference to link exercises with guitar lessons (these are two content types). I created a view (both content pane and block, identically configured), of display type Display Suite, which filters on exercises, uses a relationship with referenced entity, and contextual filter of content node id which corresponds to the lesson node id. In preview all looks fine,a lesson is displayed as well as its associated exercises, and I saved the view.

In Display Suite I managed the display for exercises and lessons and added the view I created to be managed by Display Suite.

So I thought all would be fine on my site, but when a guitar lesson page is loaded, it only displays the lesson fields as managed by Display Suite, but it does not display the exercises associated with the lesson, which I thought would work based on the view.

Now if under Structure->Blocks I attach the block view to Content, then the exercises display with lessons. But I thought Display Suite allows one to not think about blocks and instead use views and content panes to control display. Since the view has a content display type, and since the lesson and exercise content types are configured to display fields in DS-arranged content layouts, why on earth would the content pane view not be displaying?

I am new to drupal and I have no idea how clear I have described this issue, but I can clarify as needed.

Any troubleshooting tips to figure out what is going on?

I also have Page Manager and Panels installed, but I disabled the panels I had created previously and I don't see how Page Manager would be interfering since I don't have it managing any of my pages.

Regards

Unless I'm missing something I think you might be confusing the functionality of Display Suite with that of Panels.  Views content pane displays can be accessed from the Panels UI and added to a page but I've never seen that functionality within Display Suite.  Are you using any additional modules to add this functionality?

There's various ways you can do this but a really quick and easy approach is to use EVA.  Here is it's project page description.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

  The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

  In addition, the unique ID of the entity the view is attached to -- as well as any tokens generated from that entity -- can be passed in as arguments to the view. For example, you might make a View that displays posts with an 'Author ID' argument, then use Eva to attach the view to the User entity type. When a user profile is displayed, the User's ID will be passed in as the argument to the view magically.

  That's right: magically.

Basically, create an EVA variant of your view, there's a couple of settings to say what entity type (node) and bundle (Guitar lesson) to attache it to.  save this and go to the manage display page of your content type and the view will be there.

It will work with Display suite turned on or off.


How do I use Bootstrap theme's modal.jquery.ui.bridge's mapped events? I am using a Bootstrap subtheme, and would like to trigger an event when a modal is closed.

Reviewing the main theme's modal.jquery.ui.bridge.js file, I see that the bridge is intending to map jQuery UI events (beforeClose, close) to framework events (hide.bs.modal, hidden.bs.modal).

I'm struggling with figuring out how to properly declare the data-dialog-options attribute of the triggering link to pass this event through the bridge.

In the JS file, this.options.jQueryUiBridge is true when typeof options === 'object'. My guess is that my options are not typeof object.

My attributes array on the Url object is

  $attributes = [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => Json::encode([
      'dialogClass' => 'modal-content--special-class',
      'beforeClose' => 'function() {console.log("closed");}',
    ]),
  ];

which results in the rendered link

My Link Text

What am I missing?

The technical reason it's not doing anything is that the value is retrieved as a string and not as a Function object.

You shouldn't pass anonymous functions in data attributes.

This would require whatever implements the callback (jQuery UI/Bootstrap) property to use eval() or some other sort of method to evaluate the callback.

This, of course, has major security implications and why it doesn't work.

All callbacks should be added via JavaScript.

If you don't have control over specific implementation, you can always set a global listening event and then use some sort of unique identifier on the modal to trigger a custom callback.

Example:

(function ($){
  var $document = $(document);

  // Create a custom beforeClose handler.
  var customBeforeCloseHandler = function (e) {
    console.log('closed');

    // Optionally, you should be able to stop it from closing
    // if that is the desired outcome by using the following:
    // e.preventDefault();
  };

  // jQuery UI Dialog Events.
  // @see http://api.jqueryui.com/dialog/#events
  $document.on('dialogbeforeclose', '.ui-dialog', function(e) {
    var $dialog = $(e.target);

    // Check if this dialog is ours.
    if ($dialog.is('.modal-content--special-class')) {
      // Proxy this event to our custom handler.
      customBeforeCloseHandler(e, ui);
    }
  });

  // Bootstrap Modal Events.
  // @see https://getbootstrap.com/docs/3.4/javascript/#modals-events
  $document.on('hide.bs.modal', '.modal', function (e) {
    var $modal = $(e.target);

    // Check if this modal is ours.
    if ($modal.find('.modal-content').is('.modal-content--special-class')) {
      // Proxy this event to our custom handler.
      customBeforeCloseHandler(e);
    }
  });

})(jQuery);

Given that the Drupal Bootstrap base theme has the jQuery UI Dialog bridge, I would recommend binding using jQuery UI Dialog events so it will work even without Bootstrap. That being said, if you can't seem to get that to work... using Bootstrap's events should work just as well.

However, don't use both as that would likely trigger your custom handler for both events.


Drush not fully installed I have installed Drush 8.2.3 globally on a Lubuntu 18.04 image. This was done without Composer (I used the default install instructions here)

However, if I run drush topic and select any topic number from the list I get

phar:///usr/local/bin/drush/examples/sync_via_http.drush.inc: No such file or directory
more: stat of phar:///usr/local/bin/drush/examples/sync_via_http.drush.inc failed: No such file or directory

What gives?

This is a known issue - Topic command does not work when using Phar. Searching the issue queue is always recommended. Since the current version is Drush 9, I don't expect this to be fixed.


How to render a node with absolute URL to use in a mail? I have to send node content by mail using an API. I manage to load and render the content to use it with my API class, and to send it.
But when Drupal render the node, all URLs and image SRC are relatives, and it can't be used in a mail.

Here is the code I got so far

$node = \Drupal::entityTypeManager()->getStorage('node')->load($test_node); // $test_node is a (integer) NID
$renderBuilder = \Drupal::entityTypeManager()->getViewBuilder('node');
$node_view = $renderBuilder->view($node, $view_mode); // $view_mode is define in my admin settings
$html = \Drupal::service('renderer')->render($node_view); // I also tried renderRoot and renderPlain
dump($html); // URLs are relatives
exit;

I really search for days now, and I cannot figure how to tell Drupal Renderer to use absolute URL to generate the HTML string.

Two possible approaches:

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

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

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

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


How to provide the “Privacy policy link” correctly on EU COOKIE COMPLIANCE module? After this recent update of the module, when I run a Status Report, it warns me that: “Privacy policy link not provided”, but I actually think I did it by filling up the field “Privacy policy link”, am I missing any additional configuration on the module set up (Drupal 8.5.5)?

Note that, despite this warning the message abouts the cookies is displayed on the website and the respective button “MORE INFO” links to a page I created with additional info on the cookie compliance.

Actually it's better you'd report issues like that on drupal.org and not here on Drupal Answers.

The recent EU Cookie Compliance updates happened in a rush when during the ongoing development a security hole was found. Because of that a lot of half-ready new features got released.

It happens I just released a patch which may be related to your problem, see https://www.drupal.org/project/eu_cookie_compliance/issues/2985543.

But you may not necessarily need the patch. All you need to do is to update to the latest version, then go to the module's config page and choose a method (default, opt_in etc.). Choose default to turn back to the initial method before the most recent updates added additional methods.

If that doesn't work try to follow the steps from https://www.drupal.org/project/eu_cookie_compliance/issues/2985613#comment-12685609 which was a fix for the 7.x branch but may apply for D8 as well.

Last but not least, double-check that the link you provided either goes to an existing internal route or is an external link.


Confirm drush is reading policy file Drush newbie question: I've copied the policy.drush.inc file from drush examples and saved into my local drush folder, then cleared drush's cache - how do I confirm Drush is using that file (other than attempting to overwrite a production database with a local one!!)

The file examples/policy.drush.inc contains a drush_policy_pm_update_validate hook. If drush pm-update, gives you the message "This codebase is assembled with Composer instead of Drush. [...]" you know that Drush uses the file.


Where does Drupal store its content? I have been currently learning Drupal while trying to duplicate a Drupal application into CakePHP.

I have been looking at the  database tables to know where data is being stored so I can safely migrate any data or study how it is working.

I have researched and have come across questions like:

Where does Drupal store the content of a node's body?
Where does Drupal store NODE data?

So far, I have only seen the title in my Drupal (7) installation.

What I have seen in my node revisions table for a recipe content type, which includes fields like, field_ingredients, field_instructions, field_description, field_preptime, field_cookingtime, just the title of the recipe. This is a sample record on my node_revision table.

nid   |  vid  |  title         |  log   | timestamp  | status | comment | promote  | sticky
-------------------------------------------------------------------------------------------
1     |  1    |  Awesome Sauce |        | 1369998600 | 1      | 2       | 1        | 0

As you can see I can only see the title. Where are the other field contents?

Drupal 6 stored it's content in one table per content type. CCK will adhere to that unless you share a field among several nodes, in which case the fields will be broken out to a separate table.

Drupal 7 creates a new table for every field, so you'll see a lot of tables named field_data_[name_of_field], and field_revision_[name_of_field], the former for the active data, and the latter for tracking any other revisions of the same data. You might be interested in this discussion How to disable the revision feature completely? if you don't need the revision functionality.

Use the entity_cache module to alleviate some of the performance hit from all the joins this causes on complex content types.

If you need an entity that is complex enough to make the D7 approach unusable, consider creating a custom entity where you make properties of your fields. That costs a bit of flexibility, but will make Drupal store the content like the title, which is a property, in the types table.


Keep Footer at the Bottom of the Page w/ Andromeda Theme I recently setup a site using the Andromeda theme and love it! However the only issue I have is that when a page doesn't have much content in it the footer does not stick to the bottom of the page. I have tried to implement some of the css answers I have seen on this site with no luck. Does anyone else know how to implement this?

You should be able to do this with CSS using

position: fixed;

On the footer and placing it on the bottom of the screen.


How to change the value of a row in views I've views formatted as table with a pager of 10 items pr page, in which I've a field called type, depending on that type, I need to modify the other field, show text.

I've tried using PHP global field, but when I put that it is not showing the checkboxes from the second page.

I've tried hook_views_pre_render, but did'nt see any good example to change the field.

You could try using Views Conditional

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the
  condition.

As per the readme.txt

  How to use Views Conditional:

  Create a view. Add some fields under "FIELDS".
  Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
  Add and configure fields...
  Choose a field to run a condition against, and provide values accordingly.
  Save, views conditional handles the logic and returns as specified.


I want to override results of an autocomplete field (Entity reference in a content) I have a content type Intertainment and i made a reference of a view(entity referene).

I used inline entity form complex widget in manage form display the entity reference and i checked "Allow users to add existing jeux".

When i add/edit the entity reference field of type Intertainment ,  when i click "ajouter une jeu existant - or add jeu existant."

=> Results of autocomplete are when i taped something its give all titles of references entities like this :
test taxo 1

My need is to override the array results of autocomplete of inline entity form module and i don't want to add a new widget.

Example add type of content in the key of result array of autocomplete.

=> What i want to make :

It's pretty much the same as Show node IDs along with titles in Entity reference Autocomplete list except you use content type name instead of node id.

Currently there is a bug in Drupal 8 where this does not work properly. Here is the issue: Views Filter by an entity reference view not working as expected you could try the patch in comment #26 or the module in comment #13. I have not tried them yet.


Easiest way to add an existing site to a Drupal 6 multisite setup? I have an existing Drupal 6 site. We've completed development but we're told it needs to be added to a multisite setup which involves moving key files and modules to different directories. Can someone please give me a few tips on how to do this or point me to a tutorial?

EDIT: would it be easier to rebuild the site from scratch (ouch) or to make the changes to the existing site? Any help would be appreciated!

Not a complete guide, but here are some hints.

In general, modules aren't a problem, Drupal can deal with it if you move them around. Just do a cache clear after moving them and Drupal will go out and look for the enabled modules in all possible places (mainly sites/all/modules and sites/yoursite/modules). Make sure that you have no hardcoded path in your modules (contrib modules probably don't, but maybe custom ones), always use drupal_get_path() and similar functions.
You can do a big part of the multi-site conversion in your existing site, just rename the default folder to yoursite.com. Note that you need to execute drush commands within that order or use the -l argument from then on, if you use drush.
You probably want to move modules from sites/all/modules to sites/yoursite.com/modules in a first step (see first point). The existing site will probably have modules in sites/all/modules, you can then download them to your local site. Note that modules in sites/yoursite.com/modules override those in sites/all/modules. Then, figure out which modules are common, note that downgrades aren't possible, if you used a newer version of a module, you either need to keep it or upgrade the one in sites/all/modules. Make sure to properly test the changes (your site and the existing multi-sites, if you change anything in  sites/all/modules). Same game for themes.
The main issue will probably be file links in the files table, which you will need to change if your previous public path was in sites/default/files. If you already do the multi-site switch locally, you can again do and test this locally. Luckily, this has improved in D7, which doesnt't store the actual file path but something like public://the_file.jpg.
It is possible to share some tables, for example the users table, by having a single database for all sites and use a common prefix for some tables and a different one for others. If that's the case, you're in for some work (as you will need to rename all separated tables and merge the content of the shared ones). But it should be doable.
If you have hardcoded path's in your nodes and other content, you'll probably need to update them manually. You might be able to write a script that does it, but that could be tricky, dependin on how the path looks exactly.


Users unable to view order history I have drupal 6 with ubercart
When a user clicks on View order history, it takes them to a please register or login page.
Admin can see order history just fine.

I've checked the options for
Allow customers to view order invoices from their order history in Order settings and it's set to true.
I've checked permissions and its set to allow authorized and even anonymous users to view own orders.
Yet they keep getting this strange redirect to register or login.

I'm wondering if anyone has any suggestions where else to check for the problem.
I haven't been able to find the solutions yet.

Thanks!!

UPDATE:
I just noticed what when the Admin account tries to look at another users order history
mysite.com/user/105718/orders
even admin gets please login or register.
I've triple checked permissions and its set for admin to have access to everything and for users to view their own order history. Still not working.

Have you looked at the view permissions?  They override drupal core permissions.

Also, is there an order content type, or entity type?  You have to grant anon and auth users access to view their own order content type in drupal core permissions.


Call Google CDN from info file This describes way to include another version of JQuery file:

scripts[] = [...]
scripts[] = scripts/jquery-132.js
scripts[] = scripts/jquery.foo.js
scripts[] = scripts/jquery-noconflict.js

Then how to include Google JQuery CDN?

I think that this module is what you want to use, jquerycdn.
It allows you to change the default jquery to e.g google cdn.


Template not being picked up? I added a node-product.tpl.php file to my theme and it is completely ignored.

I reset the caches, multiple times, and tested with devel + devel_themer to see that the name was correct and it is. It says it searches for:

node-product.tpl.php
node-product.tpl.php
node.tpl.php

Why would the core theme() function not find that template?

My only answer would be that somehow the theme path is not yet available in the theme() function at the time the product is being generated.

(Assuming you are on Drupal 6, as it seems) you also need to copy the default node.tpl.php (e.g. the one from your base theme) in the same theme directory you are putting the override file (node-product.tpl.php) in order for the theme engine to pick it up:

  If you are implementing a suggestion, rename the file to the
  suggestion name it should have. Note that some suggestion files will
  not be recognized unless their base file is also present -- for
  instance, if you want to make a node content type suggestion file for
  your content type, you need to have node.tpl.php present in your theme
  directory order for your node-my_content_type.tpl.php file to be
  recognized.  (Beginners guide to overriding themable output)


How to render entity referenced nodes field inside node.tpl.php? I have 2 content types: book and author.
This is the structure:

I want to use (print) some fields of author content type inside the node-book-tpl.php.
How can I do that? Is there a method to print referenced entity's fields like <?php print render($content['field_author']); ?> etc.?
Note: I tried the Inline Entity Display module but because I want to do this with custom node-book.tpl.php it doesn't work for me.

If there is no compelling reason to render the fields from within the template, you could simply:

choose a certain view mode for your author content type, say: Token, and make it show only those fields you want to be visible in the book node;
set the display of the field referencing the author node from the book node to "Rendered entity" / "Rendered as Token".


Unable to render menu in theme I'm creating a custom theme in Drupal 7 but I'm having trouble getting it to render the menu

I'm using the following code in page-front.tpl.php

<?php if ($page['main_menu']): ?>

<?php print render($page['main_menu']); ?>

But it does not render anything. I have double checked that a menu exists.

$page['main_menu'] is not menu. It's the region with name main_menu. You can put there any block what you want. You can configure blocks on this page admin/structure/block

But in the basic drupal themes the main menu can be available in this variable $main_menu in the template page.tpl.php


form submitted value as token I have created a form by extending FormBase class. In form, I'm having a field called "name" where user can input his name. While submitting form, I want that submitted name convert into token so that I can use that token sending emails.

example.com/admin/config/people/accounts, here is the Drupal default configuration email forms.

What I want is to use custom form field value to be appear as a token inside drupal default email config forms.How can this be achieved?

Any help is appreciated. Thanks.

Tokens are just a representation of some other data structure that exists.

You can not convert an arbitrary value into a token. What you need to do is store the value and then define a token for that stored value using hook_token_info()/hook_tokens().

I understand it's a per-user value, so the simplest option seems to define a field on the user entity, I don't quite understand why you don't just show that in the profile. Then you can easily access it as a token when using the token module.


Commerce multiple stores and multiple carts for B2B customers i have a problem with multiple stores.
i set up 2 stores of the same type. store B2B for B2B customers and store B2C for B2C.

all products are sold in store B2B and just a few also in store B2C.

when i add to cart products from B2B store, in cart page i have only one commerce_cart_form view.
when i add a product sold also in B2C store, i have 2 commerce_cart_form view.

the first one with products sold in B2B store and the second one with products sold in B2C store.

why are there 2 carts?

it seems that built multiple stores to manage B2B and B2C is not the right choice.
thanks

According to the Commerce 2 documentation, stores are optimized for two use cases:

  We optimize for the two use cases:

  One business that has one or more locations or 2. The marketplace
  model (where you have sellers)

  One or more locations This is the most common eCommerce situation where we have a single person, company, or organization that is taking
  payments online.

  Marketplace model The marketplace model is where you have many sellers who are taking payment for unique products.

Each store can have a different currency, payment method, order flow, and so on.  So, each store also has a separate, unique cart.

It seems there are two ways to do what you want.

Keep two different stores, one for B2B and one for B2C.  If the configuration is mostly the same, you will have to duplicate a lot of config between the two stores.  You will also need to keep the two stores separate so that B2B customers see the B2B store and B2C customers see the B2C store.
Just have one store.  Add a select field to the products for admin to indicate whether it is a B2B product, B2C product, or both.  Then, modify the views that show the products so that B2B customers see B2B products and B2C customers see B2C products.  This way, you don't have to duplicate the config for the payment flow and so on.


a little clarification about contextual filter When we say "Content: Has taxonomy term ID" or "Content: Nid", what do we mean by content? Is it the element which is being viewed currently or the element that is about to be fetched from view(output of view).

When "Content: Has taxonomy term ID" is added to a view, will it  compare with the currently viewing node whether it has term id or compare with the view's data that is being fetched, whether it has taxonomy terms?

1) Content refers to Node in Views 3.x

2) Contextual filters are filters. That means that any filter you add here is a dynamic filter fetched from context (page path arguments, node data etc). So they are filtering all the results (views data if you prefer it).

A good idea is to enable the display of the database queries (admin/structure/views/settings) so you can inspect what are you doing with every views settings.


Drupal Database or MySQL Databse I want to create a dynamic website.
Where does Drupal store its data?
Is a MySQL database required to store the data?
If Drupal has its own database, does it have any limitation? I am pretty new to Drupal.

Any help would be appreciated.

As of Drupal 7, MySQL, PostgreSQL, and SQLite data types are supported in Drupal core.

Any web hosting company will offer at least one database server.

Basically:

you will copy the drupal files to your server via an FTP client
you will create a database from your web hosting company admin panel
you will go to www.yourwebsite.com/install.php and while installing Drupal you will provide the database credentials
done

You can find more info about creating your database here:

https://www.drupal.org/docs/7/installing-drupal-7/step-2-create-the-database


Re-order file attachments I am using tcpdf to generate a PDF. The PDF generation adds images that have been uploaded. The order of the images matters. After I upload files in Drupal 6 using the upload module, Drupal 6 randomly orders the images (or attachments).

The uploaded images are draggable. But when I drag them to re-order and hit save, the order goes back to what Drupal thinks is best.

How can I change this behaviour to let Drupal recognise my re-ordering?

Thanks

It looks like your re-ordering script is buggy. Make sure it saves the state of the ordering. There should be something in your re-ordering script that tracks the order. Make sure it works. This can be fixed if you have access to the re-ordering script.


How does one keep a session alive across two different URLs? I have the same drupal 7 installation running on www.mysite1.com and www.mysite2.com.

Most people redirect mysite.com to www.mysite.com, but doing so users logged in on a site aren't kept logged-in in the other site.

Since mysite1.com is running the same code as mysite2.com, I want the users to remain logged-in when switching from a site to the other one.

I assume Drupal stores the user's session ID, and when switching to the other site, the users get a new session ID, but surely there must be a way to make the two sites aware of each other, so that users are kept logged-in across two sites.

You can use Bakery Single Sign-On System module.
https://www.drupal.org/project/bakery


How to set roles of drupal "and" with each other? I need to show a block to users who have multiple roles. For example: accountant and employee.
I do not want to use permissions. I need a simple solution.

is there anyone who can direct me?

You could use hook_block_view_alter() in your theme's template.php

function MYTHEME_block_view_alter(&$data, $block) {
  global $user;

  $roles = array('accountant', 'employee');
  $required_roles = array_diff($roles, $user->roles);

  if ($block->delta == 'YOUR-BLOCK-DELTA' && !empty($required_roles)) {
    $data['content'] = $data['subject'] = NULL;
  }
}

The array_diff() here will check that the roles the user needs to have appear in the user's roles array. If either accountant or employee do not appear in $user->roles it will set the block's content/subject to NULL and Drupal will not display it.


How can i make my comments field allow images as part of the comment? (drupal 7) I would like to allow users to put images into their comments but I can't seem to find a module or anyone who has done such a thing.

Install CKEditor module. Using this module you can use pictures in comments also

  This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.


Why should the Hacked! module not be used on a production server? In the source code of the Hacked! module, it says it should never be used on a production server.

/**
 * @file
 * The Hacked! module, shows which project have been changed since download.
 *
 * We download the original project file, and hash all the files contained
 * within, then we hash our local copies and compare.
 * This module should never be used on a production server.
 */

Why not?  How would it compromise security?

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

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

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

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

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


LinkItem: how to create a disabled / null link How do I create a LinkItem that will render into

Do nothing

or another form of unclickable link?

Motivation:

I am implementing a computed field of type link, which under some circumstances should become disabled. The HTML attribute disabled is not sufficient.

Code:

if ($disabled) {
  $url = 'internal:#'; # want: 'javascript:void(0)';
  $attributes = ['class' => 'btn btn-danger', 'disabled' => ''];
  $title = t('Disabled');
}

$field_item_list->createItem(0, array(
  'uri' => $url,
  'title' => $title,
  'options' => ['attributes' => $attributes],
));

A different option:

Add a class to your disabled links.
Create a JS behavior that targets a.your-class and uses preventDefault() on the click event.
Add to libraries file for your module and add library as needed.

...
  $('a.your-class').click( function (e) {
    e.preventDefault();
  });
...


How do you get a node ID from an order in ubercart? How do you get a node ID from any of the products in an ubercart order?

I'm trying to get the product author's (uid) from the order as shown below

The order will only contain nodes/products by the same author so a node ID from any of the products in the order will do.

$sid = db_query("SELECT uid FROM {node} WHERE nid = :nid", array(':nid' => $product->nid))->fetchField();

$seller = user_load($sid);

I should have been clearer, its ubercart marketplace.

I got it to work this way:

$items = uc_cart_get_contents();
foreach ($items as $item) {
$product = node_load($item->nid);
      }


Is inheritance between content types possible? I just read Should I use a seperate content type?, and it's got me thinking.

Say I had a site with twenty-five content types, with some of the content types sharing enough of the features of some of the other content types to make some kind of "inheritance" worthwhile: I'm thinking in terms of object-oriented PHP here. Is content type inheritance possible in Drupal 6? Is it possible in Drupal 7? Or 8? Could a module be written to make it possible?

For Drupal 7 there's the Bundle Inherit module.


Notice: Object of class stdClass could not be converted to int in drupal_write_record() I'm building a new Drupal 7 and brought over the user table at the beginning of the project from another Drupal 7 site. All has been good with that except that when users save their profile, they get the following error, which I believe is related to our custom Avatar builder module. I am wondering what I can do to suspend the error message so that it doesn't show for now during our testing phase.

  Notice: Object of class stdClass could not be converted to int in
  drupal_write_record() (line 7340

Here is the section of code from the .module that I believe that relates to this error:

/**
 * Implements hook_user_insert().
 */
function my_avatar_selection_user_insert(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture;
    drupal_write_record('my_avatar_selection_usage', $usage);
  }
}

/**
 * Implements hook_user_update().
 */
function my_avatar_selection_user_update(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture;
    $has_rows = (bool) db_query_range('SELECT 1 FROM {my_avatar_selection_usage} WHERE uid = :uid', 0, 1, array(':uid' => $account->uid))->fetchField();
    if ($has_rows) {
      drupal_write_record('my_avatar_selection_usage', $usage, 'uid');
    }
    else {
      drupal_write_record('my_avatar_selection_usage', $usage);
    }
  }
}

The module works by saving the data from jcarousel into the data field of the user table and when the profile is saved, it creates a graphic that looks like the options the users selected. As far as I can tell, there are no issues with saving the avatar, it just generates this error. I took this module from the old website 7.50 so maybe there is a component I don't need on the new site 7.54.

The error is caused from the fact $account->picture is an object, and drupal_write_record() is trying to convert it to an integer, since the my_avatar_selection_usage defines fid as an integer value. See the following code used from user_save(), which the function invoking hook_user_insert().

  // Process picture uploads.
  if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
    $picture = $account->picture;

    // Omissis

  }

As you see from that code, the correct code you should be using is the following one.

/**
 * Implements hook_user_insert().
 */
function my_avatar_selection_user_insert(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture->fid;
    drupal_write_record('my_avatar_selection_usage', $usage);
  }
}

/**
 * Implements hook_user_update().
 */
function my_avatar_selection_user_update(&$edit, $account, $category) {
  if (isset($account->picture)) {
    $usage = new stdClass;
    $usage->uid = $account->uid;
    $usage->fid = $account->picture->fid;
    $has_rows = (bool) db_query_range('SELECT 1 FROM {my_avatar_selection_usage} WHERE uid = :uid', 0, 1, array(':uid' => $account->uid))->fetchField();
    if ($has_rows) {
      drupal_write_record('my_avatar_selection_usage', $usage, 'uid');
    }
    else {
      drupal_write_record('my_avatar_selection_usage', $usage);
    }
  }
}


How to query for a list of tables in a secondary database I'm working on some Functional tests on a secondary database. Part of the tear down process is to drop tables in the secondary database. How do a make a query like 'show tables' where I can iterate through them and conditionally drop a table when I want to? I've got a connection to the database, like this:

$conn = Database::getConnection('default', 'civicrm_test');
$database = $conn->getConnectionOptions()['database'];

I was looking at Connection->query() but it doesn't seem to return the results? Is there a different way to get the list of tables so I can return them and act on them individually?

$conn = Database::getConnection('default', 'civicrm_test');
$database = $conn->getConnectionOptions()['database'];
$conn->query("SET FOREIGN_KEY_CHECKS = 0");
$tables = $conn->query('SHOW TABLES')->fetchAll();
foreach ($tables as $table_result) {
  $table = $table_result->{"Tables_in_$database"};
  $conn->query("DROP TABLE $table");
}
$conn->query("SET FOREIGN_KEY_CHECKS = 1");
$conn->destroy();

I only needed to disable/enable foreign key checks, because I needed to. Others may not need to.