When creating a custom form, how does one store the data in drupal db and then retrieve for display? I'm new to Drupal and things that seem easy are apparently abstracted to oblivion.

I've created a module that displays a survey form. I would like to collect the data and store it in the database, and then allow the admin of the site to view the data that has been collected.

What is the "Drupal way" to do this?

Thank you in advance!

<?php

function member_survey_menu() {

  $items['member_survey'] = array(
    'title' => t('Member Survey'),
    'page callback' => 'member_survey_form',
    'access arguments' => array('access content'),
  );
  return $items;

}

function member_survey_form(){

    $output = drupal_get_form('member_survey_my_form');
    return $output;
}

function member_survey_my_form($form_state){
    # the options to display in our form radio buttons
    $options1 = array(
      'Strongly Agree' => t('Strongly Agree'),
      'Agree' => t('Agree'),
      'Neutral' => t('Neutral'),
      'Disagree' => t('Disagree'),
      'Strongly Disagree' => t('Strongly Disagree'),
    );

    # the options to display in our form radio buttons
    $options2 = array(
      'Very Satisfied ' => t('Very Satisfied '),
      'Satisfied' => t('Satisfied '),
      'Neither Satisfied or Dissatisfied' => t('Neither Satisfied or Dissatisfied'),
      'Dissatisfied ' => t('Dissatisfied '),
      'Very Dissatisfied ' => t('Very Dissatisfied '),
    );

    $form['knowledgable'] = array(
      '#type' => 'radios',
      '#title' => t('Question 1'),
      '#options' => $options1,
      //'#default_value' => $options['Neutral'],
    );

    $form['satisfied'] = array(
      '#type' => 'radios',
      '#title' => t('Question 4'),
      '#options' => $options2,
      //'#default_value' => $options['Neutral'],
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );

  return $form;
}

// Validate the form submission
function member_survey_my_form_validate($form, &$form_state){
    if(empty($form_state['values']['knowledgable']) ||
        empty($form_state['values']['satisfied'])
    ){
        form_set_error('knowledgable',t('Please respond to all questions, thank you!'));
    }

}

?>

A specific answer: you can use sumbit hook to store data. see Submitting Forms: http://drupal.org/node/751826

A general answer: follow this guide related with creating, theming, validating, submitting, storing data, and understanding the flow in Drupal 6 forms: Form API Quickstart Guide http://drupal.org/node/751826

to retrieve data you can use these guidances:

db_query documentation http://api.drupal.org/api/drupal/includes--database.pgsql.inc/function/db_query/6

Database abstraction layer http://api.drupal.org/api/drupal/includes--database.inc/group/database/6

also you can review Examples module http://drupal.org/project/examples specifically the module dbtng_example to database examples or page_example to build a static page add your retrieved information. please note that dbtng_example module is only for Drupal 7, but reviewing this module you will have more ideas about what to review in Drupal 6.

also could be useful the "Module developer's guide" to dive in tutorials/examples about how build forms and retrieve data using modules http://drupal.org/developing/modules


how to find image style url from themed image I've a code which theme & print the original image to specific image style.

print theme('image_style', array(
  'path' => $node->field_theme_image[$node->language][0]['uri'],
  'style_name' => 'home_theme',
));

I don't figure out how to get url of this new theme. I don't need to print the image but I need just url. Please suggest.

You need to use the image_style_url function instead of theme.

$path = image_style_url('home_theme', $node->field_theme_image[$node->language][0]['uri']);


Get config variable value in hook_block_list_alter works I have added a new field to block configuration settings by using the function  hook_form_FORM_ID_alter. I used submit handler to save the variable $form['#submit'][] = mymodule_submit (as block_save function was not called). Its all done till here
Now I am trying to alter the block list based on the condition set in the config field enable_conectivity
function mymodule_block_list_alter(&$blocks) {

    foreach ($blocks as $key => $block) {
       $enable_conectivity =??//How to get the varibale value
        if($enable_conectivity) {
            $blocks[$key]->visibility = BLOCK_CUSTOM_DISABLED;
        }
    }
}

I tried to call function hook_block_view it is not called instead hook_block_view_alter works.

Issue:Saving is affecting all the blocks
function mymodule_submit($form, &$form_state) {
     variable_set('url_to_check', $form_state['values']['url_to_check']);
     variable_set('enable_check', $form_state['values']['enable_check']);
}

hook_form_FORM_ID_alter()
$form['visibility']['mycustom'] = array(
  '#type' => 'fieldset',
  '#title' => t('ConnectCheck'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#group' => 'visibility',
 '#weight' => 20,
);
$form['visibility']['mycustom']['enable_check'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show block only when user can connect to internet'),
  '#default_value' => variable_get('enable_check', FALSE),
);
$form['visibility']['mycustom']['url_to_check'] = array(
   '#type' => 'textfield',
   '#title' => t('Url to check'),
   '#maxlength' => 90,
   '#default_value' => variable_get('url_to_check', 'www.google.com'),
   '#states' => array(
     'visible' => array(
        'input[name="enable_check"]' => array('checked' => TRUE),
    ),
  ),
);

I am trying to disable the block which requires to connect internet.
It should disable to only those user who do not have internet access.

Assuming you've set the variable using the variable_set() function, you can get the value using the variable_get() function.
From the docs:

Returns a persistent variable.
Case-sensitivity of the variable_* functions depends on the database collation used. To avoid problems, always use lower case for persistent variable names.

In your case the foreach loop would become :
foreach ($blocks as $key => $block) {
  $enable_conectivity = variable_get('enable_conectivity', TRUE); // Default value of `TRUE` is returned if the variable is not set.
  if($enable_conectivity) {
    $blocks[$key]->visibility = BLOCK_CUSTOM_DISABLED;
  }
}


How to manage editing and publication of content The scenario is this:

Content is created or edited:

At that point, the content should be marked or moved to a state of "edited" If the content is new, it should not be published.
If it is an existing node, it the ORIGINAL version should REMAIN published until it is "approved".

Content is approved:

If the approved node is preexisting, the edited version replaces the old version.
Otherwise, it is new content and it is moved from not published to published.

I'm looking for suggestions on how to accomplish this. My hope was to use the module Workflow and integrate it with Triggers.

So far, I'm not seeing an obvious path to making this work as described above.

I think you're looking for the Workbench Moderation module.  From the project page:

  Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.


Date with an option for end date being either a date or "ongoing" I have a content type that contains relevant information of a project. It should hold the projects start date and the end date OR the status "ongoing". How do I make this happen? With the date field type I can only specify the starting and ending dates.

You can create an additional field named Project status with 2 options Done and ongoing. Then using the Conditional fields module, show the date field when Done is selected and hide it when ongoing is selected.


How to display the status of the user? I created a TWIG template for the "Teaser" view of the user account.

I want to display a logo and change its color according to the status of the user :

When the user is logged in  Online
When the user is logged in and the last access is less than 30 minutes  Absent
When the user is offline  Offline

How to display the status of the user ?

I think it must be possible to create conditions in TWIG

you can use template_preprocess_user  like

 /**
 * Implements hook_entity_presave().
 */
function mytemplate_preprocess_user(&$variables) {
  // get user object
  $user = $variables['elements']['#user'];
  //- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'offline';
  }
  $variables['status'] = $status;
}

/**
 * @param $uid
 *
 * @return bool
 */
function account_is_logged_in_less_then_thirty_minutes($uid) {
  $connection = Database::getConnection();
  $query = $connection->select('sessions', 'sessions')
    ->fields('sessions', ['sid', 'uid', 'timestamp'])
    ->condition('sessions.uid', $uid, '=')
    //- chef if the user was online in 30 minutes (60 * 30)
    ->condition('sessions.timestamp', \Drupal::time()
        ->getRequestTime() - (60 * 30), '>')
    ->execute();
  //- Get result.
  $results = $query->fetchAll(\PDO::FETCH_OBJ);
  return (count($results) > 0) ? TRUE : FALSE;
}

In you template check on status variable like the following:

{% if status == 'Online' %}
   Online
{% elseif status == 'Absent' %}
   Absent
{% else %}
   Offline
{% endif %}

Add use Drupal\Core\Database\Database; to the top of your file.


How to add term description to view? I have a list of nodes (ubercart products) filtered by taxonomy term. How can I attach a term description to the view?

You can extract the tid used in the view in a preprocess hook, and use it to get the description and render it where you want.

Another solution would be to create an area handler that displays the description. This could then be used to render the term description in the header or footer section of the view.

To create an area handler you need to subclass views_handler_area and add your area handler to the term using hook_views_data_alter

hook_views_data_alter(&$data) {
  $data['taxonomy_term_data']['your_area_handler'] = array(
    'title' => t('Title'),
    'help' => t('Help text.'),
    'area' => array(
      'handler' => 'your_views_area_handler_class',
    ),
  );
}

The area handler doesn't need much more than a render function which acts as it's theming function, so it's not that tricky.


Flush cache only for changed pages I'm working on a site with Varnish enabled, but I notice that the system clear cache pages, according to the expire configuration, also if pages are not changed.
Is it possibile to clear cache only if a page is changed?

Thanks,
Sergej

You can achieve this by setting a very high default TTL (expire time) and then invalidating the cache only for modified content. The Varnish module and the Cache Actions module are useful tools for that purpose.

Fabian Sörqist, maintainer of the Cache Actions module, has written a detailed article about it here: http://dev.nodeone.se/en/caching-with-varnish-drupal-7-and-cache-actions


How to add time element to open date and close date when adding a quiz I am using the following modules.

Quiz, Version 7.x-4.0-rc2
Date, Version 7.x-2.9

When adding a quiz, in the availability options tab, I want to be able to set the time as well.

In the open date and close date, there should be an hour and minute option as well.

I did the following things.
1. In the hook_form_alter(), added the below code

if($form_id == 'quiz_node_form'){
  $form['quiz_availability']['quiz_open']['#type'] = 'date_select';
}

This gave a warning on the node/add/quizpage.

  Warning: strlen() expects parameter 1 to be string, array given in
  date_default_date()

2.So added a patch in date_api_elements.inc
https://www.drupal.org/files/date-element-default-value-2038057-1.patch
This removed the warning but upon adding the date and time in the availability options and saving the form, it throws the huge error below.

  Please supply a valid date. PDOException: SQLSTATE[01000]:

  Warning: 1265 Data truncated for column 'quiz_open' at row 1: INSERT INTO {quiz_node_properties} (vid, nid, aid, number_of_random_questions,
   max_score_for_random, randomization, backwards_navigation,
  repeat_until_correct, quiz_open, quiz_close, takes,
  show_attempt_stats, keep_results, time_limit, pass_rate, summary_pass,
   summary_pass_format, summary_default, summary_default_format,
   quiz_always, feedback_time, display_feedback, tid, has_userpoints,
  userpoints_tid, allow_skipping, allow_resume, allow_jumping,
   show_passed, mark_doubtful, max_score) VALUES ....

3.In the hook_node_presave, printed the $node.

It stores the date as below.

  [quiz_open] => 2016-05-12 21:17

but it expects the date to be stored like this.

 [quiz_close] => Array(
      [month] => 6
      [day] => 11
      [year] => 2016
    )

How to store the date as an array or is there an alternative solution to the problem.

You can convert it to an array using the php function substr

// lets assume $date = Array ('quiz_open' => '2016-05-12 21:17');

$year = substr($date['quiz_open'], 0, 4); // grabs 2016
$month = substr($date['quiz_open'], 5, 2); // grabs 05
$day = substr($date['quiz_open'], 8, 2); // grabs 12

$date = array ('quiz_close' => array (
                                'day' => $day,
                                'month' => $month,
                                'year' => $year,
                                     )
              );


Show page content on another page using views I have a 'presentation' page where I would like an image gallery where all the uploaded images that users upload to the site are displayed.

So far these images are being displayed only on the 'upload' page as default.
(users are effectively modifying the same page when adding content)

I want to keep the 'upload' only as means to upload the images but I want all the images to be displayed ONLY on the 'presentation' page!

How do I do it with views?

Not sure if I'm understanding you correctly, but you can create two view modes for the node that contains all the images that users upload, one for 'presentation' and one for 'upload' using Display Suite (see tutorial on view modes). If you don't want the upload version to show the images, simply hide the Image field in the 'upload' view mode.

Additionally, you can use a module like Juicebox to create a nice-looking and easy to navigate Javascript gallery in the 'presentation' view mode - just select "Juicebox Gallery" as the formatter for the Image field (instead of the default Image formatter) in your 'presentation' view mode.


How to debug page caching? I've got a page which returns X-Drupal-Dynamic-Cache: UNCACHEABLE, I've got a suspicion that this is related to a view that is embedded in the page. Though, this made me wonder; is there any way to see what invalidated actually the page cache?

The X-Drupal-Cache-Tags header should help with this.  Here's how to enable it from this doc:

  You can debug cacheable responses (responses that implement this
  interface, which may be cached by Page Cache or Dynamic Page Cache) by
  setting the http.response.debug_cacheability_headers container
  parameter to true, in your services.yml. Followed by a container
  rebuild, which is necessary when changing a container parameter.

  That will cause Drupal to send X-Drupal-Cache-Tags and
  X-Drupal-Cache-Contexts headers.


Get taxonomy term field from where is attached I have a taxonomy vocabulary like this:

A
|--B(branch_field)
   |-- C(branch_field)

X
|--Y(branch_field)
   |-- Z(branch_field)

Each user has a reference to a taxonomy term.
I need to create a view where I pass taxonomy term attached to user for filtering data, but I need also to use the taxonomy term field "branch" in the view but I don't manage it.

This is what I see using Devel about user fields:

[field_category_user] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 39
                            )

                    )

            )

Can I expose term field and target id?

You can implement hook_views_query_alter()

In your view create a filter (not exposed) to field_category_user, with default value -1. If field_category_user is not aviable you need create a realation to taxonomy.
Create a hook_views_query_alter() in file [module_name].views_execution.inc with some like this:

// Implements hook_views_query_alter().

function [module_name]_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
$id = $view->id();

switch ($id) {
    case '[your_view_id]':
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $field_category_user = !$user->field_category_user->isEmpty() ? $user->field_category_user->value : null;

        if(!$field_category_user){
            return;
        }

        //Set field_category_user id to where condition
        foreach ($query->where as $key => $item) {
            foreach($item['conditions'] as $items){
                if ($items['field'] == 'field_category_user') { //Verify if field_category_user is the id of filter
                    $query->where[$key]['conditions'][0]['value'] = $field_category_user->id();
                }
            }
        }
    break;
}}


Configure Videojs to use the local library Videojs in Drupal 8 gives the following error:

  Missing the Video.js library. Please download Video.js and extract it into the //vjs.zencdn.net/5.0 directory.

How can I configure Videojs to use local files? Where should I put Videojs files?

I think Videojs has not configuration interface.

The README.md included with the downloaded module says:

  Download the Video.js library from http://videojs.com. Extract the module to sites/all/libraries/video-js and make sure that sites/all/libraries/video-js/video.js exists. NOTE: you can skip this step and use the Video.js version from the Video.js Content Delivery Network (CDN).

A comment in the documentation block in the module file suggests that the Libraries API determines where to places libraries.

  Defaults to videojs_directory when using the local file path location
  or whatever location the Libraries API determines.

This location is also set by the videojs_directory configuration variable, which could be set by importing a YAML file via Configuration Management interface or with a tool such as Drush or Drupal Console despite the Video.JS module not having a specific configuration page.


How to use the right menu_tree and menu_link depending on region How can I have specific menu_tree and menu_link for specific region?

Example:

left region will have his own menu_tree menu_link which will be different from the right region.

How can I achieve this?

Do I need to build a custom module?

If I use template_preprocess_region() , how can I call menu_tree and menu_link?

Thanks in advance

----------- UPDATE ----------------------

I've seen that preprocess_block gives back "region" and "module". Is there anyway to use the different menu_link() and menu_tree() depending on the region and module?

To theme only specific regions within your drupal page simply filter your css by prefixing your class with the class or id of the region in question. You can find the region by inspecting HTML output. I use chromes inspector which is accessed via inspect element within contextual menu.

#region-sidebar-first .menu_tree menu_link_my_class { css }

and if you want a different style for the right hand sidebar

#region-sidebar-second .menu_tree menu_link_my_class { css }


Admin Approval for Webform Submitted data I am new to drupal , and need functionality like , When any Users submit Webform then i am displaying that submitted data in another page . but in between i need Admin Approval so for that how to change code in Webform module.

I have used all modules like MODR8 , RULES , VBO , Moderation etc.

if anyone knows plz help me becoz i am trying to solve this problem from last 2 weeks.

Thanks in advance.

You can try something like this for admin approval:
 1. create custom content type;
 2. create fields just like your webform has;
 3. copy copy webform-confirmation.tpl.php and change the name webform-confirmation-NID.tpl.php
4. there write something like this:

include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1);
$sid = $_GET['sid'];

$submission = webform_get_submission($nid, $sid);

$otzyv_text = $submission->data[1]['value'][0];
$name = $submission->data[2]['value'][0];
$email = $submission->data[3]['value'][0];
$title = mb_substr($otzyv_text, 0, 10);

$node = new stdClass();
$node->type = 'response';
$node->title = $title;
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = $otzyv_text;
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'filtered_html';
$node->field_name[$node->language][0]['value'] = $name;
$node->field_e_mail[$node->language][0]['value'] = $email;
$node->uid = 1;
$node->status = 0;
$node->promote = 0;

node_object_prepare($node);
node_save($node);

(this is what i've done when my customer wanted to have an ability admin approval). By this way you will have unpublished nodes when someone submits your form (administrator can publish them whenever he wants).  After that in IF statement you can write something like:

$node = menu_get_object();
if($node->type == 'YOUR TYPE' && $node->status == 1) {
  // Display submitted data... You can fetch them from node object
}

or with Views module you can create block or anything you want by that content type...


D7 - Get Path Alias (URL) from referenced Taxonomy Value I'm trying to avoid using the PHP filter due to security concerns.

I have a CCK type I already created called Slide that I am dumping out in a view. The Block dumps out all of the items with content type Slide which are then used in a homepage slider.

Within the CCK type, I have an Entity Reference field called Prog Reference that references a taxonomy value.

What I need is the URL that is associated with that Taxonomy value so I can link up the actual slide.

They click the slide -- takes them to that taxonomy term page.

Current setup:

Referenced entity: Prog Reference -- http://d.pr/i/10bX

 Entity Reference: Prog Reference

Fields: d.pr/i/oa3z (wouldn't let me post as link)

(Taxonomy term entity referenced from field_prog_reference) Taxonomy term: Term ID
Content: Slider Image

No Taxonomy term: Path :( -- d.pr/i/FtcC (wouldn't let me post as link)

Taxonomy term: Name
  The taxonomy term name.
Taxonomy term: Programming Image
  Appears in: taxonomy_term:programming_type.
Taxonomy term: Rendered Taxonomy term
  The Taxonomy term of the current relationship rendered using a view mode.
Taxonomy term: Term description
  The description associated with a taxonomy term.
Taxonomy term: Term edit link
  Provide a simple link to edit the term.
Taxonomy term: Term ID
  The tid of a taxonomy term.
Taxonomy term: Weight
  The term weight field

Typically you would just use the Content: Path field to get the referenced entity's path, but for some reason this isn't an option Taxonomy values?

Any ideas? All help welcome!! Appreciate in advance!

Ok then, here are a two options.

Option 1)

Include your entity reference field.
Use the 'Label' formatter.
Rewrite it's output and to /taxonomy/term/[field_entity_reference-target_id], see screenshot.

This will output the path to the term page as plain text for you to use as you will. You could output this field as a link and attempt the same pattern.

Option 2)
+ Add a relationship to the referenced entity. See screenshots.

Once you add the relationship, add the Taxonomy term: Name field using the relationship. See screenshot.

<> Then configure to use link and rewrite output if desired.


How to show entityQuery results as block I use entityQuery to retrieve nodes related to actual content. Now I don't know how to add them to template and show them in my theme.

In Drupal 7 I used Bean module to create blocks as entities. The module states the following, which I don't fully understand:

  As Drupal 8 supports fields on its block entities, this module is not
  needed for new sites.

So how do I get the results of my entityQuery into blocks to afterwords use them twig templates?

Try the above suggestion:
Create Custom Block for example MyBlock.

In the your src/Plugin/Block/MyBlock.php File.
implement build method and getNodesBuild method to get the nodes build:

  public function build() {
    return array(
      '#theme' => 'mymodule_my_block',
      '#nodes_build' => $this->getNodesBuild(),
    );
  }

NB: Change the $nids array by the result of your Query.

  /**
   * This function return view_builder of list of nodes.
   * @return array
   */
  protected  function  getNodesBuild(){
    //- Replace this by the result of your Query
    $nids = [38, 39];
    //- Get the current lang
    $language_manager = \Drupal::service('language_manager');
    $language = $language_manager->getCurrentLanguage()->getId();
    //- Get view_builder for node entity type
    $entity_type_manager = \Drupal::service('entity_type.manager');
    $view_builder = $entity_type_manager->getViewBuilder('node');
    //- Load nodes
    $nodes = Node::loadMultiple($nids);
    return $view_builder->viewMultiple($nodes, 'teaser', $language);
  }

Implement hook_theme in your mymodule.module

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mymodule_my_block' => [
      'variables' => [
        'nodes_build' => [],
      ],
      'template'  => 'mymodule-my-block',
    ],
  ];
}

templates/mymodule-my-block.html.twig

  {{ nodes_build }}


Custom module stopped executing after 30 seconds I've written a custom module that adds many users from a database to drupal database. So, it has many database queries to take care of the drupal tables: users, user_roles, url_alias, profile and field_data_field_$fieldname and field_revision_field_$fieldname where $fieldname is the profile2 field and has many such fields.

The problem is when I execute this module (the trigger is user selects an option in the form which is specific for this module), it executed for only 30 seconds and inserted some 20+ users where I have to insert 500+ users. After 30 seconds, it didn't display any error. It stayed on the same form.

How can I clear this?

You need write batch operation:

  Functions allowing forms processing to be spread out over several page
  requests, thus ensuring that the processing does not get interrupted
  because of a PHP timeout, while allowing the user to receive feedback
  on the progress of the ongoing operations.

http://api.drupal.org/api/drupal/includes%21form.inc/group/batch/7


"Content: ID" versus "Content: Nid" I'm just getting to know Drupal. I've been manually recreating current Drupal 7 Views from a production installation into a new development install of Drupal 8.85. I've run into some differences between Drupal 7 and Drupal 8, as you might imagine.

In Drupal 7, many views are using Content: Nid (for the node ID), which doesn't exist in Drupal 8. I've read here and elsewhere it has been replaced by Content: ID, in Drupal 8.

That said, the dialog boxes for each look different when it comes to setting options and parameters. For example, Content: Nid has an option/checkbox for Link this field to the original piece of content. Content: ID doesn't have that option, as I can see.

Additionally, the Content:ID dialog has options not seen in the Content: Nid dialog, such as the options for Formatter, Thousand marker, and Display prefix and suffix.

Is Content: ID really the Drupal 8 equivalent of Content: Nid? Where are the options missing in Content: ID?

Is Content: ID really the Drupal 8 equivalent of Content: Nid?

Yes

  Additionally, the Content:ID dialog has options not seen in the
  Content: Nid dialog, such as the options for Formatter, Thousand
  marker, and Display prefix and suffix.

Thousand marker makes sense. The other two not so much, bug maybe?

  In Drupal 7, many views are using Content: Nid (for the node ID),
  which doesn't exist in Drupal 8. I've read here and elsewhere it has
  been replaced by Content: ID, in Drupal 8.

I could see them thinking when developing the D8 version, who links to a Node/Entity using the ID? Using something descriptive like a Title, or "view/edit/delete" text makes a ton more sense, don't really need this feature for ID. Plus having to hover over single digits is not user friendly.

But, if you still want to link using the ID

Add the ID field and checkmark hide from display.

Then either add field:

Link to content OR Link to edit content

Under rewrite results:

Checkmark override the output of this field with custom text

Example:


Page always takes at least 30 seconds to load I have a site set up on Godaddy and a constant frustration is that it always takes at least 30 seconds to load. Total time for queries was under 200ms. I decided to write the following script:

function getmillisecs() {
   list($usec, $sec) = explode (' ', microtime());
   return (double) $sec + $usec;
}

$start = getmillisecs();

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$end = getmillisecs();

$result = $end - $start;

echo round($result * 1000, 3);

All it does is output how much time passes between the start and end of the script. The time I got was 30521.649ms. Taking out everything related to Drupal dropped the time to 0.089ms. What is causing the huge delay? Thanks.

It could be several things:

Views executing sql queries that have performance problems.
Cache problems (Do you have enabled the Drupal's cache?).
(If you have a VPS) maybe the server that you are sharing is under heavy load.
(If your site is integrated with web services) maybe the web service is having performance problems or connection problems.

Try to check the logs of the site to see is there are errors or anything that could be related to this problem.

Another alternative is to use a profiler like Xhprof (there is a module for drupal) or XDebug.

Could you share with us the url of the website?


jQuery not functioning in Chrome regardless of core/custom code For whatever reason jQuery is refusing to function in Chrome for us.  It works in all other browsers.  This is the case regardless of the theme, page (aka: core admin pages like blocks have no jquery like drag), custom jquery, or core jquery.

In the firebug console $ correctly returns function() and the javascript is present in the html.  Its basically like Chrome is just ignoring it.  There have been no changes to core files and thus you would imagine at least the core admin pages would be functioning properly.

Scratching my head on this one here, any suggestions are appreciated.

This is an issue with CloudFlare and Chrome:

https://support.cloudflare.com/hc/en-us/articles/200169456-Why-is-JavaScript-or-jQuery-not-working-on-my-site-


How to delete all parent references of a taxonomy term? How to delete references to parent terms?

I tried this:

$term->get('parent')->setValue(NULL);
$term->save();

Additional question: how to delete reference to a specific parent term?

Answering to myself. Taxonomy hierarchy is known to be detached from terms. For example when loading term you don't get its parents. This was confusing to me and I thought setValue() just doesn't work. But the truth is that it works perfectly.

To get the code from above working, only a minor edit is required - it's using 0, not NULL:

$term->get('parent')->setValue(0);

This deletes all the hierarchy the term has and writes one record to the taxonomy_term_hierarchy table - with zero parent.

If you need to delete the hierarchy manually you can use deleteTermHierarchy():

\Drupal::entityTypeManager()->getStorage('taxonomy_term');->deleteTermHierarchy($tid);

but be warned that the term will disappear from the lists on /admin/structure/taxonomy/manage/<vocabulary>/overview page since it's missing any hierarchy now. To fix this you need to add a record to the taxonomy_term_hierarchy table with zero parent. And that's exactly what setValue(0) does - deletes hierarchy and adds that record.


SMS for login to website Is there any way for sending code by SMS when the user login to the website "OTP", I want my website more security for login, the users have to type Username,password, SMS code.

Thanks for your support,

You Can go for Twilio Module

The Twilio module provides integration with the Twilio cloud communication platform
allowing for your Drupal site to integration Voice and SMS functionality.

What you can do using this module

Ability to store and access TwiML
Rules event to act on incoming SMS message
Rules action to send an SMS message
Rules event to execute TwiML scripts
Hook for incoming SMS messages
Hook for incoming voice calls
User object phone number storage and validation
Uses libraries api to manage the Twilio php library
Support for international texting
Support for MMS


How to programmatically disable Global Theme Settings? I am trying to programmatically disable logo and site name. I have seen some variables for these set in modules/system/system.admin.inc but haven't been able to disable them through my profile installer settings.

What is the proper way to disable them? I looked around the internet but found no one has really looked into this issue.

See here for a related question.

The theme settings are not individually saved as variables. They are all in a single variable, whose name depends on your theme. For example, if your theme name is mytheme, the variable name will be theme_mytheme_settings.

You can disable the logo and name like this:

$my_settings = variable_get('theme_mytheme_settings', array());
$my_settings['toggle_logo'] = 0;
$my_settings['toggle_name'] = 0;
variable_set('theme_mytheme_settings', $my_settings);

You can also disable settings by means of the features key in the .info file for your theme. The defaults are:

features[] = logo
features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

If you don't specify any of these, all are enabled. If you specify some, only the ones you specify are enabled. So if you wanted to hide logo and site name, you would put this in your .info file:

; features[] = logo
; features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

See the theme settings documentation for more info. You need to be careful with this depending on what theme you are using. If you're overriding a base theme, these are the keys, but a contributed or custom theme might have different keys.


Features_extra: after enabling fe_block, no Machine Name field appears on block edit form I installed and enabled fe_block 6.x-1.x-dev, but when I reload one of my blocks' edit form, no machine name field appears. I tried clearing the cache; no dice.

What's missing? Thanks.

The fe_block module only allows exporting blocks represented in the boxes table — those created via the admin/build/block/add user interface.

Exportable blocks will have block as the second-to-last component of the admin URL:

Blocks created using, say, Views, or a module's hook_block() implementation, however, are not exportable using fe_block — it doesn't make sense to export blocks such as those, since Views provides its own export mechanism, and other module-owned blocks are already in code to begin with.


How do I add a filter to a checkbox list in a content editing form I have a taxonomy select field within a node form (7). I've chosen checkboxes and it is hard to scan them. I'd like to be able to add a filter so that the user can enter text to limit the number of choices in the list. How?

You can change the Reference method option in your Field settings to Views: Filter by an entity reference view.
You first have to build the Views listing taxonomy terms, Display of type Entity Reference. Add the exposed filter there for the term name. Save the View.
Then you'll be able to select that ER Views Display in your Field settings.


Drupal 8 password retention I am currently reviewing Drupal 8's security features and was wondering about how Drupal stores user passwords. I know Drupal uses salted hashes to store the password in the database, but does Drupal also store a user's previously used passwords so that they can't reuse them again? If it does, does that list have a hard limit to it (i.e. does it only store the last twenty used passwords before recycling the list)?

I am only interested in the out of the box experience with Drupal 8. I know there are modules that you can use to add extra functionality/security to user passwords but that isn't part of this question.

Thanks.

Out of the box, Drupal only stores the salted hash for the current password. No previous passwords are stored without the help of a contrib module such as Password Policy.


Accessing taxonomy custom field values (Drupal 7)? I've added a new vocabulary to Taxonomy, and then proceeded to add several custom fields to that new vocabulary. In the taxonomy_term_data table, I see the values for the tid, vid, name, description, format, and weight fields. It also looks like there are now a couple of new tables in the database that are related to the new custom fields that I created for the new vocabulary (i.e. field_data_field_taxonomy_cip_code). The values in the new table are entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_taxonomy_cip_code_value, and field_taxonomy_cip_code_format. There's nothing that I can see on the surface that would allow me to relate the two tables together.

How would I go about pulling the additional custom field values along with the new vocabulary values?

If you load the taxonomy term with taxonomy_term_load(), you will get any custom field you added to the vocabulary.

I created a vocabulary to which I add a boolean field (field_test_boolean); I added a taxonomy term to that vocabulary, and then executed the following code. (22 is the taxonomy term ID for the taxonomy term I created.)

$taxonomy_term = taxonomy_term_load(22);
dsm($taxonomy_term);

The output shown by dsm() is the following one.

If you want to get the field value for the language currently set for the field, you should use the following code.

$values = field_get_items('taxonomy_term', $taxonomy_term, 'field_test_boolean');

If you need to find the taxonomy terms for which the custom field contains specific values, you should use the EntityFieldQuery class.

  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', 'fields_test')
    ->fieldCondition('field_test_boolean', 'value', 1, '=')
    ->execute();

  if (!empty($entities['taxonomy_term'])) {
    $taxonomy_terms = taxonomy_term_load_multiple(array_keys($entities['taxonomy_term']));
  }

Note

As noticed in a comment, there is a bug that doesn't allow to use the EntityFieldQuery class for taxonomy terms. The code seems fixed in the Drupal 7 development snapshot, but Drupal 7.14 is affected by the bug.


How to display an image field next to the title on the profile pages? My users have an image field, called 'Avatar', that's displayed as an icon. I can easily add it to the users' profile page in the content section, but now I'd like to show it next to the title (the default one prints the username).

As I didn't try to do this before, I surfed around the internet for a while. It seems that lots of similar requests were solved by a template file. Therefore, my plan was to add a user-profile.tpl.php, copy all the code from page.tpl.php to it and add

<?php
print render($user_profile['field_avatar']);
?>

before the title.

I'm not sure whether this might work. Is this a good approach?

The use of the template is solid guess. However, you're using the wrong template. The template you suggesting isn't based on the page.tpl.php page. The output of the user-profile.tpl.php page, will end up in the $content section of your page template.
You should try to use a different approach.

How about a preprocess function? It will intercept the rendering of the variables and by so, you can alter them. If you want to change the title of your user-profile page, I'ld go with something like this:

/**
 * Implements hook_process_page().
 */
function mymodule_process_page(&$vars, $hook) {
  // Load the global user object
  global $user;

  // Check if it's the userpage and the current user, depending on URL
  if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] .= ' ' . $user->avatar[LANGUAGE_NONE][0]['value'];
  }
}

Above preprocess function should be placed in your preprocess folder of your theme or the template.php.
It will extend the existing title with your extra fieldvalue.

There is only one drawback on this implementation. If you have a page with a path like /user/overview, the title will change too. Every URL with user as first argument and a UID as second, will be altered...

Goodluck!

EDIT:
Try this please and let me know how it went:

/**
  * Implements hook_process_page().
  */
function mymodule_process_page(&$vars, $hook) {
    // Load the global user object
    global $user;

    $image = array(
      '#theme'  => 'image',
      '#path'   => file_create_url($user->field_avatar[LANGUAGE_NONE][0]['uri']),
      '#width'  => 20,
      '#height' => 20,
    );

    if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] = render($image) . $vars['title'];
    }
}


Can you make the hook_menu() item title different from the page title? I'm building a menu with hook_menu().

When you're building the array for this you specify a title, which is then passed to the page you call and becomes the page title. It's also the menu item's displayed name.

$items['somewhere/something'] = array(
 'title' => 'Something',
 'description' => 'something else',
);

This would generate a menu link called "Something", and the page title would be the same.
Is there a way to make the menu item's name one thing, but pass along a different title for the page?

I know I can use drupal_set_title() in the actual hook_page() function, but I'd have to perform an additional database pull to make that happen in this case, and I'd rather not do that.

No there's no way to do it with hook_menu().

The simplest way is what you suggested, using drupal_set_title() and the most efficient is what dobeerman suggested above: use phptemplate_preprocess_page() and alter $vars accordingly.

Honestly though, I would just use drupal_set_title() even if there is that extra db call you mentioned (unconfirmed). This is a tiny optimization and if performance is important to you, you should have some caching mechanism in place (Varnish, Boost, etc) and this extra call won't make a difference!


How to render a node on behalf of another user (as an admin or without accessCheck) Context : I use the following code to replace a token by a rendered node.
The resulted text is sent by email
$renderable = $view_builder->view($node, 'token', $langcode);
$replacements[$original] = \Drupal::service('renderer')->renderPlain($renderable);

This is working fine except when I am queuing the mails to be sent
Because, in this case, the upper code runs in a queue and NodeAccessControlHandler::checkAccess and NodeAccessControlHandler::checkFieldAccess are called with an anonymous account (id=0).
This leads to an AccessRessult::forbidden() (because in my setup, anonymous can't see those fields and/or this node) and the rendered node is empty...
Thus my question is:
How to render a node (in a queue) "in behalf of" an admin user?
or
How to explain to my overrided NodeAccessControlHandler that we are in a queue and that it can safely give access (without security concerns)

Thanks to the comment of @No Sssweat I could find a solution:
Summary: the problem appeared when emails were sent via a queue in a cron. The cron is running as an anonymous user, and, in this case, the drupal viewBuilder/Rendering system doesn't have enough permission to display some fields/nodes.
Solution: Adapt the processItem function of the QueueWorker in order to switch the current user into an admin user at the beginning of the process and switch back at the end.
I my use case, I overrode the QueueWorker provided by another module. Here is my code with the injection of the switcher service: (feel free to comment)
/**
 * The account switcher service.
 *
 * @var \Drupal\Core\Session\AccountSwitcherInterface
 */
protected $accountSwitcher;

public function __construct(array $configuration, $plugin_id, $plugin_definition, SubscribersInterface $subscribers, AccountSwitcherInterface $account_switcher)
{
    parent::__construct($configuration, $plugin_id, $plugin_definition, $subscribers);
    $this->accountSwitcher = $account_switcher;
}

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
{
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('message_subscribe.subscribers'), $container->get('account_switcher'));
}

public function processItem($data)
{
    $this->accountSwitcher->switchTo(new UserSession([
        'uid' => 1,
        'name' => 'cron_admin',
        'roles' => ['administrator'],
    ]));
    parent::processItem($data);
    $this->accountSwitcher->switchBack();
}


order by weight ASC - D7 This piece of code:

->orderBy('weight', 'ASC');

orders the column by the weight ascending. However, the rows are sorted like: 15 - 2 - 20
of course this should be: 2 - 15 - 20

How can I achieve this, specifically for drupal(7)?

It seems that the database is using lexicographic ordering, while your intention is to use numeric ordering. Numeric ordering is only used when the type of the field is a numeric type. Check whether the field is of a numeric type.


Group nodes by terms How do you group a list of nodes by the taxonomy term?

e.g.

Term 1
--- Node 1
--- Node 3
--- Node 7

Term 2
--- Node 6
--- Node 9
--- Node 12

I have tried creating a view with "Node" and "Taxonomy Term" as fields. I then enabled grouping, and grouped by the taxonomy term. Doing this outputs the following:

Term 1
--- Node 1
Term 1
--- Node 3
Term 1
--- Node 7
Term 2
--- Node 6
Term 2
--- Node 9
Term 2
--- Node 12

There is a Drupal 6 tutorial here that explains how to fix it, but it doesn't work under Drupal 7.

It seems like such a simple task, yet after many days of trying, I can't get it to work! I've found many threads of people asking the question, but no solutions (at lease a solution which doesn't involve installing taxonews).

In your view add two fields:
- Node title
- Taxonomy Term

You are right up to here.

Now:

Set the "Taxonomy Term" field to "Exclude from display"
Select your views' format as unformatted list; use "Edit settings" for the format
Set "Grouping Field" as "Taxonomy Term"

For details, view my views' export data in pastebin.


how to make unsortable header colmn in theme_table drupal 6 I m using Drupal 6
I m using pager_query and theme_table
How can I make any column unsortable, by default it is making all columns sortable

$tableHeader = array(
        array('data' => ''),
        array('data' => 'Article','field' => 'a.title'),
        array('data' => 'From date','field' => ''),
        array('data' => 'To date','field' => ''),
        array('data' => 'Perpetual','field' => ''),
        array('data' => 'Access type ','field' => ''),

        );

here first column shows check boxes along each row so don't want this column sortable
Thanks

Looking at the code for tablesort_header the sortable stuff is only added if the particular header item is an array. So you can cancel off certain columns by just setting the header to a string, e.g.:

$tableHeader = array(
  'This colum header is not sortable.',
  array('data' => 'Article','field' => 'a.title'),
  array('data' => 'From date','field' => ''),
  array('data' => 'To date','field' => ''),
  array('data' => 'Perpetual','field' => ''),
  array('data' => 'Access type ','field' => ''),
);


Approve public organic group Our organic groups is set up so that any authenticated user can create a group. What we need is for any group created to be private (accessible only to group members), but if the creator requests it be public, then the group is initially created as private and be in a published usable state, but a request will be sent to a groups admin for the group to be public (which will then list it in a group directory and anyone can request to join).

I'm using Drupal 7 and the latest version of OG. I have it set up so the group visibility defaults to private right now.

Any way to do this with rules? I've tried creating a "list in public directory field" associated with the group content type and then I figured when a group was added, a rule could check if that field was checked and do some event to notify an admin. But I'm not sure where to start with the "React on event" drop down as it doesn't seem anything suits what I'm trying to do.

I'm open to other ideas.

After having lots of fun with rules, I have found a solution. Whew!

I created a rule:

Events:
Before saving content

Conditions:

Content is of type - Parameter: Content: [node], Content types: Community Group

AND

Data comparison - Parameter: Data to compare: [node:group-access], Data value: Public - listed in the...

Elements:

Set a data value - Parameter: Data: [node:group-access], Value: Private - accessible only...

I also send an email and show a message on the site, but that's not to important to the nitty gritty of the rule.

The purpose of my rule is that when a user selects "public" for a group, that the group is created as "private" but a request is sent to a Group Admin to review and change to public once approved. In the meantime, the user can still add members and use the group in a private state.


Are there conditions where invalidated cache items are returned? Why do we invalidate cache tags instead of clear cached items with those tags?  Under what conditions would the invalidated cache be returned?

See my presentation on Drupal 8 Caching about that topic: https://md-systems.github.io/drupal-8-caching/#/6/6 for how you can still get invalid items. And https://md-systems.github.io/drupal-8-caching/#/6/5 on how cache tag invalidation works.

The reason why cache tags invalidate instead of delete is scalability. Invalidating a cache tag does not require us to touch each single cache entry, we just need a single update query to increase the invalidation counter that is checked when cache entries are loaded. Common cache tags like renderered, image style cache tags and other frequently used cache tags could be on tens or hundreds of thousands of cache entries, deleting them all at once would take a very long time on MySQL and other cache backends like Memcache have no API to do do something like that at all.


How can I update the length of a base field definition in an update hook? I'm struggling with writing an update hook that will simply update the length of a text base field attached to an entity of mine.

Here's my update hook:

function my_module_update_8001() {
  // Collect all existing story run data.
  $database = \Drupal::database();

  // Gather all the existing story run data.
  $tables = [
    'content_tile_field_data',
    'content_tile_field_revision',
  ];
  $existing_data = [];
  foreach ($tables as $table) {
    $existing_data[$table] = $database->select($table)
      ->fields($table)
      ->execute()
      ->fetchAll(PDO::FETCH_ASSOC);
    $database->truncate($table)->execute();
  }

  // Update the "name" base field definition to a new max length
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $name_field = $update_manager->getFieldStorageDefinition('name', 'content_tile');
  $name_field->setSetting('max_length', 100);
  $update_manager->updateFieldStorageDefinition($name_field);

  // Restore the data.
  foreach ($tables as $table) {
    $insert_query = $database
      ->insert($table)
      ->fields(array_keys(end($existing_data[$table])));
    foreach ($existing_data[$table] as $row) {
      $insert_query->values(array_values($row));
    }
    $insert_query->execute();
  }
}

After running this, the name field is clearly dropped and re-added (I know because it now appears at the end of the list of columns in the table), but the length is still set to 50, the old value.

I've narrowed this down to BaseFieldDefinition::getSchema():

  public function getSchema() {
    if (!isset($this->schema)) {
      // Get the schema from the field item class.
      $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($this->getType());
      $class = $definition['class'];
      $schema = $class::schema($this);
      // Fill in default values.
      $schema += array(
        'columns' => array(),
        'unique keys' => array(),
        'indexes' => array(),
        'foreign keys' => array(),
      );

      // Merge custom indexes with those specified by the field type. Custom
      // indexes prevail.
      $schema['indexes'] = $this->indexes + $schema['indexes'];

      $this->schema = $schema;
    }

    return $this->schema;
  }

The schema definition is cached, so the update process gets the old schema data instead of regenerating it. There appears to be no way to clear this internal cache.

If I comment out the code related to the caching, it works as expected.

Is there another approach to this that I'm missing?

EDIT: The approach I took instead is to just load the current definition and pass that through to the update manager, like this:

  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $definitions = \Drupal::entityManager()->getFieldStorageDefinitions('content_tile');
  $name_field_definition = $definitions['name'];
  $update_manager->updateFieldStorageDefinition($name_field_definition);

I guess this is not recommended normally, but it worked just fine.

I was having the exact same issue, trying to update the "max_length" of the name field of a custom entity.
I did a hook_update like that :

function mymodule_update_8005() {
  $entity_definition_update_manager = \Drupal::service('entity.definition_update_manager');
  $field_definition = $entity_definition_update_manager->getFieldStorageDefinition('name', 'myentityid');
  $field_definition->setSetting('max_length', 255);
  $entity_definition_update_manager->updateFieldStorageDefinition($field_definition);
}

But then, even if the fieldDefinition had correctly changed, I was still having the old length limitation.

Finally, what I had forgotten to do was changing this max_length in my entity definition itself, here :

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields['name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Title'))
  ->setSettings(array(
    'max_length' => 255,
    'text_processing' => 0,
  ));
  ...

After that, it worked as desired.


Calling a JS function after managed file has completed uploading How can I call a JavaScript function after a file has completed uploading using the Drupal Form API (FAPI) managed_file element?

This is tricky in D8, as the ajax code does not offer any hooks or callbacks after the function has run. The solution is to override the ajax callback function that the managed_file element uses, adding an additional custom command that is triggered when the file upload is complete.
First, we create a custom AJAX command, that will be used to trigger the code we want to execute. Details on creating custom ajax commands can be found here.
First, the Ajax command on the PHP side. This will go into [MODULE]/src/Ajax:
<?php

namespace Drupal\[MODULE]\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * Command to trigger an event when managed file upload is complete.
 */
class ManagedFileUploadCompleteEventCommand implements CommandInterface {

  /**
   * Implements Drupal\Core\Ajax\CommandInterface:render().
   */
  public function render() {
    return [
      'command' => 'triggerManagedFileUploadComplete',
    ];
  }

}

Next, the triggerManagedFileUploadComplete() command needs to be created on the JavaScript side. This is done in [MODULE]/js/managed_file_upload_complete_event_command.js.
(function (Drupal) {

  "use strict";

  /**
   * Add new custom command.
   */
  Drupal.AjaxCommands.prototype.triggerManagedFileUploadComplete = function () {
    // Do stuff here after file upload is complete.
    alert(Drupal.t("File upload complete!"));
  };

}(Drupal));

Now the new JavaScript file needs to be registered in MODULE.libraries.yml:
command.managed_file_upload_complete_event_command:
  js:
    js/managed_file_upload_complete_event_command.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

With this, the custom command can be attached using the library: [MODULE]/command.managed_file_upload_complete_event_command
Now that the custom command and it's related JS callback have been completed, the next thing is to add the new command onto the end of the ajax callback, so it is executed when the upload is complete.
The default ajax callback for managed_file elements is \Drupal\file\Element\ManagedFile::uploadAjaxCallback(). This needs to be overridden, adding the command created above to be run after all other ajax commands.
The #ajax property of the managed_file element is added in \Drupal\file\Element\ManagedFile::processManagedFile(). As such, if we want to alter the ajax, it has to happen after the above #process handler has been run. So we add another #process callback to be called after the default #process callback. In our process callback, we can change the #ajax callback to a function of our own. The #process callbacks are declared in \Drupal\file\Element\ManagedFile::getInfo(). Adding another #process handler can therefore be done in hook_element_info_alter().
/**
 * Implements hook_element_info_alter().
 */
function MODULE_element_info_alter(array &$info) {
  // Add a custom #process hook to the managed_file element:
  $info['managed_file']['#process'][] = 'MODULE_managed_file_process';
  // Add the custom command to managed_file elements, so that it is
  // available when called:
  $info['managed_file']['#attached']['library'][] = '[MODULE]/command.managed_file_upload_complete_event_command';
}

Now the command has been created and attached to all managed_file elements. The next step is to override the #ajax callback with our own, adding the custom command to it. Let's look at the overridden function (should be put in the .module file):
/**
 * Custom ajax callback for managed files.
 *
 * Overrides \Drupal\file\Element\ManagedFile::uploadAjaxCallback()
 *
 * @see \Drupal\file\Element\ManagedFile::uploadAjaxCallback
 */
function MODULE_managed_file_ajax_callback(array &$form, FormStateInterface $form_state) {
  // Retrieve the original response.
  $response = \Drupal\file\Element\ManagedFile::uploadAjaxCallback($form, $form_state, \Drupal::request());

  // Add our own command to the end, so our command is run last:
  $response->addCommand(new \Drupal\[MODULE]\Ajax\ManagedFileUploadCompleteEventCommand());

  return $response;
}

The last thing to do is to replace the original ajax command with our own. This is done in the process callback we registered in hook_widget_info_alter():
/**
 * Custom process callback added to managed_file elements.
 *
 * Replaces the original #ajax callback with a custom one.
 */
function MODULE_managed_file_process(array &$element, FormStateInterface $form_state) {
  $element['upload_button']['#ajax']['callback'] = 'MODULE_managed_file_ajax_callback';

  return $element;
}

This tells Drupal to replace the original ajax callback with MODULE_managed_file_ajax_callback(). This callback retrieves the response from the original callback, and adds our custom command to the end of it. The custom command is called when the file has been uploaded, allowing us to run whatever JS we need on the server side after files have completed uploading.


Render Panels Overridden user profile template I have overridden the user profile template using Panels module and want to render this overridden user profile in one of my custom module.

Actually I wanted to show "About Author", tab besides the "View" tab of article, which when clicked, will show overridden user profile.

For that I have created menu entry as follows:

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

    $items['node/%node/author'] = array(
        'title' => 'About Author',
        'page callback' => 'get_node_author',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

My function is as follows:

function get_node_author($node = NULL) {
    $account = user_load($node->uid);
    $account_view = user_view($account);
    return drupal_render($account_view);
}

But it is loading user profile in normal format and not the one which is customized using panels.

Any suggestion how can I achieve this?

I suggest you don't create a menu hook at all.

Just implement your desired layout in a custom panels page instead, and you can control the menu from there.


Local moved to Server all nodes 404 My homepage works perfectly fine on the live server but when I use any of the links they give me a 404 Page not Found.

I tried a couple things which was:

Made sure .htaccess was there
Tried a copy/paste of an .htaccess that someone provided
Tried setting $base_url
Tried setting Rewritebase /

Tried making sure this was in .htaccess

 Options +FollowSymLinks
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

I did go from an xampp local testing environment on Windows to a nginx setup on Ubuntu 14.04 so I figure it has something to do with that. I'm just not sure what to try next I've done most everything that googling brings me to.

Ok so it was a bit weird how it all came together, I restarted the nginx and that didn't do anythig.

I opened the default config file for nginx and just saved it without making changes and restarted the service.

After than I went from a 404 error to a 500 error.

To fix the 500 error I changed a line in my default from this:

 try_files $uri $uri/ /index.html;

To this:

 try_files $uri/ $uri /index.php?$query_string;

I saved the config file and restarted nginx and it worked!


install modules with custom module Is there any way to install all modules a in specific folder with a custom module? I need to install my custom module and have all modules in a specific folder installed automatically.

If you define the modules in the subdirectory as dependencies of your main module, then they'll be enabled once your "controller" module is.

i.e.

name = Really Neat Widget
description = Provides a really neat widget for your site's sidebar.
core = 7.x
package = Views
dependencies[] = MODULE_ONE
dependencies[] = MODULE_TWO

Source

Alternatively, you could take a look at the Master module.


subject and body of mail messages empty using drupal 8 mail api - hook_mail I'm trying to send messages using Drupal 8's Mail API, but the messages always have an empty subject and body.  Do you see anything wrong with the code?

In my module file:

function mymodule_mail($key, &$message, $params) {
    $options = array(
        'langcode' => 'en'
    );

    switch ($key) {
      case 'contact':
        $from = \Drupal::config('system.site')->get('mail');  //I'm not sure this is actually doing anything.
        $message['subject'] = 'Inquiry from Web Site';
        $message['body'][] = 'TEST BODY';
        break;
}

And within the submit method of my form:

 $langcode = 'en';
 $to = 'my@email.com';

 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = 'mymodule';
 $key = 'contact';

 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

I am getting the messages - and they are coming from the right email address (which may just be the default).  But the subject and body are empty and I can't figure out why.  Any suggestions would be appreciated!

Ok, I found the problem.  You're gonna laugh!

My code for hook_mail was within the code block for the function above it!  D'oh!  All good now. Sorry for the false alarm.


How can I display latest post in another menu tab? I want my latest post to appear in another Menu tab. For example, in this website www.drupal.stackexchange.com, you have the following menus QUESTIONS, TAGS, USERS, BADGES, UNANSWERED, if I want my post to appear in BADGES, how can I archive this?

You could use taxonomies.  First, navigate to admin/structure/taxonomy and create a taxonomy with the terms you want to have tabs for (e.g. QUESTIONS, TAGS, USERS, BADGES, UNANSWERED).  Hover over each of the terms in the list terms to discover their default paths.  Let's say you note that "BADGES" has been assigned the path "taxonomy/term/7"

Now, all you need to do is to create an item in your main menu to display tagged articles. So navigate to admin/structure/menus and add the following link to the main menu. Set Menu link title to "BADGES", and Path to "taxonomy/term/7".  Repeat for other taxonomy terms you want to access via a main menu tab.

Now, you have tabs in your main menu called "BADGES", etc.  Under each tab content tagged with its taxonomy term will appear automatically, so to make content show up under the BADGES tab, tag it with "BADGES".  If you're using Drupal 7, the default article content type already has a taxonomy field.  But you can add a taxonomy field to any content type if it is missing.

You can now refine this by customizing how things are listed using Views to create customized listings. You can also hide the numeric paths with the use of URL aliases if you want (so the path appear to the user as badges instead of taxonomy/term/7.)


Is it possible to publish/unpublish content by language? I have enabled the the "multilingual with translation" option for the content type.

I have created the node and translate it in 2nd language. In 2nd language I want to unpublish the content but when I unpublished it, it also unpublished the content in the 1st language.

Is it possible to publish/unpublish content by language?

I found the solution.

In your Content type settings
Synchronize Translations --> Status should be unchecked.


%1 doesn't get converted to taxonomy name when overriding title When using Content: Nid as a contextual filter for "Content" (node) type views, I can check "Override title" and use %1, and the node id will be converted to the real node title when displaying this title. (For example, I can type "Gallery of %1", and it will be converted to "Gallery of Blablabla".)

When I create a view for showing "Taxonomy Terms", set "Taxonomy term: Term ID" as a contextual filter, check "Override title", and use %1 the same way I did for "Content", the taxonomy id doesn't get converted to the real name of the term! (so for example "term is %1" gets converted to "term is 261", which is not the expected result)

Why, and how can I get around this problem? I'd like to override the title and use the taxonomy term name.

It works for me with Drupal 7.

What I did was enabling the validation criteria, set the validator to Taxonomy term, and the type of the filter value to Term ID.

When I visit http://example.com/programming-languages I get the list of all the taxonomy terms terms for the "Programming languages" vocabulary.

When I visit http://example.com/programming-languages/20, I get a page using the overridden title.


Simple calculator with predefined coeficient I would like to have very simple calculator on my page - user should input any number x (days) and the result should be x times y where y is any preddefined coeficient that I define.
Is it possible to do in drupal. 6 or 7 version?
Thank you

Yes - this is possible, but its not really related to Drupal (at least the way you define it). Its either going to be a javascript calculator that you embed in a page (where the result wouldn't get saved) or a PHP function that processes the results from a form and returns the result on the next page.

Either way, both are beyond the scope of this site but tutorials like this one should give you a start on writing your calculator embed.


Cannot Uninstall Purchased Theme, Porto I purchased a theme called "Porto" which is quite good.  With that said, for troubleshooting purposes, I need to turn that theme off.

I can uninstall every theme on the site except "seven" and this purchased theme.

When we installed the theme, we had to do a whole install using SQL rather than just dragging over the theme file.  I BELIEVE that there is something in these files that is preventing them from being uninstalled but I'm not sure where to look.

Can someone tell me where I might look to find this setting and override it? In the theme file? Setting file?

You can't uninstall the default theme, because there wouldn't be a theme left for the site. Similarly you can't uninstall the Seven theme when it's selected as the admin theme.

You need to change the default to another theme, then under normal circumstances the "Uninstall" link will appear where you'd expect it.

If it doesn't, consult the documentation or contact support for the theme seller, because they've done something non-standard, and it's not likely to be possible to guess what that might have been from afar (especially if it was done as part of the initial SQL import)


How can I direct the user to a different page on a multisite installation based on which subdomain they go to? I have a site, let's call it www.example.com, and I'm going to create subdomains for it with the same Drupal installation on every subdomain. I can do that. However, when someone goes to a subdomain, I would like them to see a different page depending on which subdomain that they go to. Say for example they go to user1.example.com, can I make that somehow redirect them to an arbitrary page within the Drupal installation? I hope that's clear.

This is one of the things that you can do with the Domain Access module.  Essentially, it allows you to have different behaviors for a site with subdomains, but running from the same database.  This is different from multisite, which uses a different database for each site.


Recommend nodes based on current node field value in view block I have made a view block to show on each node for recommending other node of similar interest type.

Every node have a field called Main Category, which is taxonomy.

I want to show those node title which has similar category where view block is attached(I mean at node page).

Note - I have attached view block into node by EVA field.

There is a module for that: Similar by Terms

However, it's possible with views as well: Creating list of similar nodes in Drupal 7/Views 3

Alternatively, you can use my configuration:

An example of view block with related nodes based on 'tags'.

Create a block (take a look at screenshots below)
Add a relationship: Taxonomy term: Content using: Tags
Add contextual filter: (field_tags) Content: Nid
When the filter value is NOT available
Provide default value -> Content ID from URL
MORE
check: Exclude
this contextual filter will remove current node from the view
Add contextual filter: Taxonomy term: Term ID
When the filter value is NOT available
Provide default value -> Taxonomy term ID from URL
check: Load default filter from term page
check: Load default filter from node page, that's good for related taxonomy blocks
choose the vocabulary (tags in this case)
Multiple-value handling -> Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria  -> Basic validation
MORE
check:  Allow multiple values
Define the fields (only titles in this case)
Make the view display only distinct items
Other -> Query settings:
check: Distinct
check: Pure distinct

Screenshots:


How to fix a white screen of death? I am dealing with a white screen of death I feel like I've pin pointed the issue, but have no way of knowing how to fix it.

This is my first time using Drupal, and my first time running into this issue. Are these errors that are in my log, related to problem? How would I go about fixing it?

Any and all help is appreciated as I have already consulted the handbook and have not found the solution to this issue by doing so.

running drush core-requirementsfrom your drupal site's directory more info and tail /var/logs/[httpd | apache2]/foobar_error.log will be your friends here.


Generate image styles with a rule on "node save"? This QA has some discussion about the lazy image loading.  Imageinfo_cache is D6 only at the moment, and rules_image_styles apparently runs on every node view which isn't great for performance.

Wouldn't it be possible to just create a rule that fires "on node save" and for all types that include images you'll execute PHP code to generate all image styles?

There seems to be a third module that has this ability already, however it doesn't seem to be compatible with Rules just yet. It is compatible with Trigger however (I don't know if this allows it to be automatically compatible with Rules...let me know if you find out how). Here is the module: http://drupal.org/project/ispreg


How to print taxonomy id of the current taxonomy term I have custom taxonomy term pages which I'm using to override forum pages and I want to emulate advanced forum node/add/forum/tid button so I have to get tid but don't know how, I can only find examples on how to print tid of the current node.

You can use below code to get Taxonomy id by Taxonomy Name

 $taxonomy_term = taxonomy_get_term_by_name('Taxonomy Term Name');
 $tid = $taxonomy_term>tid;


Drush restore to proper folder level Before working on a site, I take a quick dump of a site via drush arb --destination=/var/backup/latest.tgz --overwrite from the root level /var/www/html.

However, on the rare occasion that I need to restore via drush arr ../backup/latest.rgz --overwrite, I end up with a restored database but the file structure is written to /var/www/html/html.

Would drush arr ../backup/latest.rgz --overwrite --destination=/var/www/ solve this issue? Do I just continue to muddle through withmv /var/www/html/html* /var/www/html?

How can I get drush to write to the actual root level for the default drupal site?

the --destination flag surely works to say where. I'm not quite sure if the outcome would be a mix of the former and the latter system though. Probably the writing does not delete the old files. It would be safer to delete them manually prior to archive recover.


How to find the origin of variable in Drupal Maybe this a compound question, please bear with me: I need to find out why the meta tags are not being printed on the homepage of a theme. The problem is that in html.tpl.php I've got this line: <?php print $head; ?>.

In other pages, the meta tags are being printed ok, but not on the homepage. When I look at the page--front.tpl.php it doesn't include any header info or markup (only the markup from the menu downwards and I can't figure out:

Why the difference and;
Where is the $head being defined.

And yes, the content of the homepage does have tags added to it.

Can anyone point me in the right direction?

Looks like you should debug the code not in theme but in the module.

I assume you use the metatag module. It adds all the metatags in metatag_html_head_alter().

Check what is your front page. If it is a View of a Panel, metatags are handled in a different way.

In the metatag module you can specify separate tags for the front page - check this setting. It might override your content metatags.


How can I hook into an entityform? So that i could create a custom dropdown which is populated from a database I am trying to create a custom Dropdown which is populated form a database but I'm not getting which hook to use and how to use it.
My module name is "entityform" Plzz Help Thanks :)

You can write a hook_form_alter()

function hook_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

After you cleared the cache you can print the form ID or just alter the form right away.

I suggest to check what the form ID is and then add:

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

To alter it. (Make sure to clear cache again)

in both instances hook is to be replaced by your module name. When you want to use the dpm() function you'll have to install the Devel module.

I hope this helps!


entity_metadata_wrapper file load I'm trying to load and get the file using entity_metadata_wrapper. this is my code

$wrapper = entity_metadata_wrapper('node',$variables['node']);
$file_field= $wrapper->field_library_file->value();
$variables['file'] = theme('file_link', array('file' => file_load($file_field['fid'])));

and <?php print $file;?> outputs nothing. I've found this in this address . how can I get set of files that belongs to a node.

thanks.

UPDATE:

this is the code I use for theme hook suggestion, this code is on top of the the above code.

$suggest = "page__node__library";
$variables['theme_hook_suggestions'][] = $suggest;

I created a page and renamed it to page--node--library.tpl.php and <?php print $file;?> is in this page.

Some corrections after, can you put the context of the execution? Like the function where you call this code and where you output $file variable?

$wrapper = entity_metadata_wrapper('node',$variables['node']);
// raw() should give you file object in your case
$file_field= $wrapper->field_library_file->raw();
// theme_file_link 'file' parameters have to be a file object
$variables['file'] = theme('file_link', array('file' => $file_field ));

Docs :

theme('file_link') OR theme_file_link
Raw() Method

Note :

@clive comment : no need to value() because he have already used that function below, if we follow the source code given... In that case, value() and raw() methods should return the same file object.

theme('file_link', array('file' => $file_field))

Edit : Can you dump your $file_field variable? You can do it via this snippet

drupal_set_message('<pre>'.print_r($file_field, true).'</pre>');


Different bar colors for each poll choice? I know how to change ALL of the bar colors - but how do I code it so each choice bar is a different color?  I basically just need code to append the number to the "bar" class, so it would read "bar-1" , "bar-2" etc.

jQuery can help you in this regard if you not going to edit templates.

(function(){
   var i=0;
   jQuery('div.poll .bar .foreground').each(function(){
        i++;
        switch(i){
            case 1:
                $(this).css('background-color', '#color')
            break;
             ...
         }

    });
})();


Changing commerce_line item quantity to 3 decimal places I need to change the precision of Drupal commerce quantities to 3 decimal places.

To do this I edited drupal_commerce_line_item and changed the quantity field from decimal(10,2) to decimal(11,3).

Is this OK? (don't want repercussions) and is there anything else I need to do?

In theory, changing the commerce_line_item field's SQL (schema) definition ought to be enough. However, a cursory review of a few modules shows that some of them will round the value to 2 decimal places before using it, negating the change. You'll probably need to change it and then test it to ensure that every module you're using it with will work as you intend.


Get rendered content of one block created as derivative block I have created derivative blocks using a method such as this and want to get the contents of a specific derivative block.

I can see all the available blocks (even derivative blocks) that have been assigned to a region with

 $ids = \Drupal::entityQuery('block')->execute();

but can't see unassigned blocks

I have a feeling that I need to use the code from berdir's answer b)

$variables['block_output'] = \Drupal::service('plugin.manager.block')
   ->createInstance($plugin, $configuration)
   ->build();

but don't know what to use for $plugin or $configuration

any help example will be appreciated

It sems this will do the trick:

  $blockManager = \Drupal::service('plugin.manager.block');
  //see all available block plugins (even not instantiated)
  $contextRepository = \Drupal::service('context.repository');
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

Here is how I used this info:

function TEMPLATE_preprocess_node(&$vars) {
  $blockManager = \Drupal::service('plugin.manager.block');
  $vars['content']['derivative_block'] = $blockManager->createInstance('module_name:block_derivative_id')->build();
}

If you enable the commented lines $definitions will get you all available blocks

Credit goes out to enzo for this solution.

More info about programmatic block placement.


Modify user profile page, not login page I'm trying to edit the user profile page, not the login page.

However, with Drupal 7, the template for the profile and the login page is the same.

I tried to modify page--user.tpl.php, but it also modifies the login page. And modify user--profile.tpl allow to modify the order of the fields but not the entire page.

Do you know how to do it ?

For theming user profile page use page--user--%.tpl.php template file.

To see all possible template suggestions right in your code you can enable Theme debug mode in sites/default/settings.php:

$conf['theme_debug'] = TRUE;


Move a taxonomy page field to a different region I currently have taxonomy pages using a custom image field, field_icon, which by default displays in my content region.

How would I go about moving this field display to a different region (in my case the header region)?

You can approach this in UI, Twig or PHP:

UI

You can create a View (show Taxonomy Terms) with display "block" and add "Term ID" as Context Filter, see this example for Users: How to move the user account/Profile 2 information from the content region to a sidebar region

Twig

Install Twig Tweak and place the field in a twig template:

{{ drupal_field('field_name', 'taxonomy_term') }}

PHP

Prepare the taxonomy term entity in a preprocess hook, see print custom image field for taxonomy page (page--taxonomy.html.twig) template


what are the implications of installing APC on a VPS running multiple Drupal sites? I have a single VPS running a number of independent Drupal sites. What considerations do I need to make (if any) when installing APC?

One thing to keep in mind is that APC will require quite a bit of memory if you have multiple sites because each file will be kept in memory, even if it is in fact exactly the same file, just with a different path.

So you need to watch and tune the amount of memory that apc uses/can use. By default, it's 32MB, that's often too less for even a single Drupal site if you have many contrib modules. The problem is that if APC has not enough memory, it will always have to delete files from the cache. If it has much to less (e.g. not even enough for all files in a single page request), it will make your site slower than if you hadn't used APC at all.

VPS often don't have a lot of memory, make sure that you have enough for your sites. You could consider merging them into multi-sites to save memory.


CKeditor and Input Formats confusion Why is there a 'Security Filters' section within the CKEditor configuration settings?

My understanding is that this is all set within the normal Drupal input formats section (admin/settings/filters). Do the CKEditor input configs replace this when the editor is present in a field?

:-/

Sorry for posting link answer but, there is a complete tutorial here.


Altering checkboxes rendering in a form I've a drupal website with a custom theme based on Zen.

In a specific page of my website, I've a form rendered by the Finder module (which uses the Drupal Form API).

I want to modify the way Drupal render the checkboxes of this particular form.

Let's say Drupal render my checkboxes like this :

<input type="checkbox"> Choice 1

I want to modify the html into something like :

<input type="checkbox">
    Choice 1

This could allow me to better adjust the layout using CSS.

Can someone point me the right direction to achieve this ?

Solution :

Since the finder outputs Checkboxes (and not many Checkbox), using #field_suffix didn't solve my problem.
Why ?
Because applying the following code :

$form['finder_form']['type']['#field_suffix'] = "
field suffix
";

Results in this :

        <input>

        <input>

So I ended up doing :

foreach ($form['finder_form']['type']['#options'] as $key => $value) {
    $form['finder_form']['type']['#options'][$key] = $value."

";
}

If a better approach is found, I will edit this.

The input element has no close tag, so this is not really a well-formed question.

That said, what you are probably looking for is hook_form_alter() which you would implement in your own custom module to alter this particular form element.

Have a look at the #field_suffix propery for how you could append some arbitrary markup to your element.


How can I remove emoji from all user input? It looks like iPhone emoji are not currently supported in Drupal 7 on MySQL.

When I try to save a node containing an emoji (I  U!) in the database, I get an SQL error:

  PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string
  value: '\xF0\x9F\x92\x9BRi...' for column 'body_value' at row
  ...

So, to avoid this very unpleasant user-unfriendly error, I would like to automatically clean all user input, including all node textfields and private message module messages.

I found several functions for removing emoji, but which hook can I use to clean all user input?

All user input is a bit much. Only common ground I can see is that all user input goes thorough some kind of forms. And the only thing that for sure happens before anything tries to save, is validation*.

Functions listed in #validate can alter form state. Example definition shows they take form state by reference:

function test_form_validate($form, &$form_state) {

So the "only" thing you would have to do is to recursively iterate over all $form_state['values'], and apply your removal function. It should be pretty safe, because by the very nature your function will not affect numerical inputs in any way.

Other approach might be a bit faster. You can use #element_validate - prepend your removal function to validation array of each and every text field. Sadly, form element types may be added by modules, so you would have to prepend it to every element anyway (forgetting any significant boost due to validation only data that needs it, and paying a price of more function calls), or carefully inspect your modules and make sure you know what else, except textfield and textarea can accept text data (machine_name element is already safe, I omitted it on purpose).

All in all, I would prefer to just switch my MySQL to utf8mb4 charset, that supports all utf8 as it ought to be supported. You need MySQL 5.5.3 or greater to do this.

make a backup (obvious, but hey)
upgrade if needed
for each database, table and column that has it set already, change to CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci
Set default-character-set = utf8mb4 for [client] and [mysql] in my.cnf
Set (in the same file)

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

Hack Drupal to use it. What you want is around line 53 of /includes/database/mysql/database.inc

Hacking Drupal is usually not encouraged, but in this particular case we cannot expect a patch, so this is the only way to give users what they want. Also, it's method way less CPU consuming that altering all inputs.

* Of course you may create your own submit handler and make it a first one, but making sure it's always first is hard. Other module developers may try to have their handlers first, too. And if they decide to, for example, log something to MySQL, your fix becomes futile. Using validation is a bit of abuse, but it's an only way I would trust in this scenario.


Add attribute to all textboxes in the site The question is simple , in my theme I want to apply an attribute to all textboxes in whole forms . I know how to add an attribute to an specific element in drupal using hook_form_alter , but it is too time consuming for lots of elements , so I'm eager to see if there is an easier way to do that.Any suggestion?

You'll want to use hook_field_widget_WIDGET_TYPE_form_alter() for this. The following will add the "my-class" class to all textfields:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function test_field_widget_text_textfield_form_alter(&$element, &$form_state, $context) {
  $element['value']['#attributes']['class'][] = 'my-class';
}


People page redirect to the homepage I am having a peculiar error where whenever I click on the People tab on the admin bar it is redirecting me to the homepage.

Could someone please shed some light on this? This is on the live server for a while now, but this issue just recently started occurring.

Cheers.

P.S. I am superadmin, so I should have all the privileges.

No idea what was causing this but clearing the browser and site caches seemed to have fixed this issue.

Thanks to all those that replied.


Call a function in one of the modules from a custom PHP file on my Drupal site I need to run a function in one of my module. This function is perfectly visible throughout my drupal site.

For one of my option, I have to run this function when colorbox loads. I have no idea which PHP file is called when the colorbox opens. I do know where the JS code is when colorbox opens, so what I did was this:-

...
...
inline:function(){
        $.get("sites/all/themes/my_theme/set_session2.php");
        return $.urlParam('inline', $(this).attr('href'));
      },
...
...

In this way, I can run a php file where I placed that function. Problem is that function is not visible in this PHP file.

Is there any way, I can get through this problem?

Best.

All php files inside drupal cannot be directly accessed by incoming request. You should create a endpoint for $.get which can be done by hook_menu

function mymodule_menu() {
  $items['mymodule/endpoint'] = array(
    'page callback' => 'mymodule_page_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

function mymodule_page_callback() {
  module_load_includes('php', 'mymodule', 'set_session2');
  // call function here.
}

module_load_includes can include the php file you want from the module. So please place the php file inside the module folder.

In javascript, just update the url to the one you just defined.

...
...
inline:function(){
    $.get("/mymodule/endpoint");
    return $.urlParam('inline', $(this).attr('href'));
},
...
...


How to Print and style Profile2 fields? I created a profiles type called: Game Player Profile (Machine name: game_player_profile). This contains : field_firstname, field_lastname, field_profilephoto, field_zipcode.....

How do I print and style these fields to create a page with a list of the 'Game Players' First Names + Last Names + Photo.....

Thanks

J.

Take a look at the Views Module.  It is the primary module used to select fields and display them. You can find out just about everything you need to know about using the module in this Video series


How to put multiple fields in an index operation on a GET HTTP request with services? I'm working with the module "services" everything's ok with a get request, note that i've create my own custom resource with CRUD operations, the "retrieve","update" are ok but the problem is with the index operation. With only one field it works and show all records with the default field I declared on resource. Now how to put an array of $fields ?

This is the resource declaration (the "fields" part of the code) :

array(
        'name' => 'fields',
        'optional' => TRUE,
        'type' => 'string',
        'description' => 'The fields to get.',
        'default value' => 'field_title_value',
        'source' => array('param' => 'fields'),
      ),

now here is the function index (callback) :

function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t');

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}

The doc of services said that $fields is an array of fields i want to return, when i make :
$fields = array('field 1','field 2','field 3');
It return an error. If I make a "classic" :

$query = db_select('my table')
->fields('my table', array('field 1','field 2','field 3')

Same error.

Any help please ?

Thank you all.

The simple db_select with fields make it work easy as that :

function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t')
->fields('t', array('field_title_value','entity_id','delta'));//<+++++ whatever you want

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}


How to setup session sharing for language subdomains (URL language detection set to domain prefix) I would like to use domain prefix for language selection, like en.example.com and de.example.com. I've set up language detection to Domain here admin/config/regional/language/configure/url.

In theory everything works fine, except that session data is not shared between subdomains. If I log into the main site example.com and then visit en.example.com I have to log in again. Is this behaviour by design? Can I setup drupal to share session data between subdomains? It's the same site after all - only subdomain is different.

You need to set the variable $cookie_domain in your settings.php file to your base (default language) domain.

Just search the settings.php file for that variable, uncomment the line and replace '.example.com' with your default language domain preceded with a dot.

Source


Panels template files: Inheriting a tpl file in a sub theme In my Drupal custom parent theme, I have included a file called panels-pane.tpl.php.
This is the main panel pane template. By including this tpl file in my theme, I can override the one in the Panels module folder, which allows me to control its mark-up.

It all works fine. However, when I enable a sub theme that is based on the parent theme, this particular file is ignored. All the other files are inherited.

How can I get this file to be inherited as well?

Would it be possible to force this to be always loaded regardless of the theme?

Please note: I am talking about overriding the panels-pane.tpl.php that comes from the original Panels module. I am not talking about creating a custom Panels layout.

Steps I have tried:

Copying the panels-pane.tpl.php into the sub themes template directory.
Clearing the caches
Uninstalling and then re-enable the parent and sub themes

UPDATED
Panels has a file called panels.module. In it has a function called panels_theme(), which contains the following:

  $theme['panels_pane'] = array(
    'variables' => array('output' => array(), 'pane' => array(), 'display' => array()),
    'path' => drupal_get_path('module', 'panels') . '/templates',
    'template' => 'panels-pane',
  );

Can I use this to control panels-pane.tpl.php from inside a module by using theme_registry_alter?

I have tried the following code, but it doesn't work:

function legendary_theme_registry_alter(&$theme_registry) {
 $theme['panels_pane'] = array(
    'variables' => array('output' => array(), 'pane' => array(), 'display' => array()),
    'path' => drupal_get_path('theme', 'legendary') . '/templates',
    'template' => 'panels-pane',
  );
}

Here's the weird news, just having a panels-pane.tpl.php in a parent theme should work. It's working for me in a highly used parent theme. So I'm guessing any theme suggestions or other steps aren't going to cut it...

I would check for typos, in this case I would look at the file name (sounds like that's fine), then I would check the sub-theme info file to make sure that's set correctly (although it sounds like that may also be right)

base theme = base_theme_name

Then I would check file permissions on tpl/theme folder. 664 tends to work for me, and apache needs access to it and the folder it's in.

If that seems fine my two steps before I panic with drupal are:

drush rr

restart apache

Hope that helps.


How to delete Ghost Menu Link in Main Menu? I added a menu link in main menu: user/%/notifications/subscription. The menu is never visible except that when a user goes to his subscription page via 'My Account'. The menu link is not available when I try to edit the main menu links. It is not there. This problem surfaced up after I installed Menu Token module. However, I committed the sin before installing the Menu Token] module. I have uninstalled this module.

Additionally, user gets the following error when visiting user/%/notifications/subscription.

  "Notice: Undefined index: localized_options in menu_navigation_links() (line 1858 of /home/carrotjo/public_html/includes/menu.inc)."

After some search on the Internet, I commented out $l = $item['link']['localized_options']; (line 1857 in menu.inc). The error is gone. But the ghost appears in the main menu link.

I think the easiest way is to manually delete this item from the table menu_links search for value user/%/notifications/subscription in link_path column. Delete that row and clear your cache.