How to show a user's age at the time of creating a node in a View? My users have a Date of birth field (I am using the Date module). Every node page contains a View with some information about the node. I would like to add the author's age at the time of publication to it. How can I do that, assuming that Date of birth is available as a Views field?

I first tried to use Time Ago, but unfortunately it is not possible to select a time range. Next, I computed the difference between the time of publication and the date of birth in Unix seconds with a mathematical expression, but I am not sure how to convert this value to a year.

it can be done by rules, here is a rule that calculate in DAYS the difference between two dates. my rules does the following, make necesary changes to fit your needs:
First convert both dates to an integer value, then substract them (date1-date2= diff-value in seconds), for days value divide diff-value by 86400 (24*60*60), this new variable convert it to an integer, this last value is the diference in days between those 2 dates. react on after saving(updating) your node, store this value by rules in a node hidden field, last add this field to your view.

rule's code:

{ "rules_parcialidad_calculate_dias_de_retraso" : {
"LABEL" : "parcialidad calculate dias de retraso",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "calculate retraso pago" ],
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--parcialidad" : { "bundle" : "parcialidad" } },
"DO" : [
  { "data_convert" : {
      "USING" : {
        "type" : "integer",
        "value" : [ "node-unchanged:field-fecha-de-parcialidad" ]
      },
      "PROVIDE" : { "conversion_result" : { "fecha_parcialidad_converted" : "fecha_parcialidad_converted" } }
    }
  },
  { "data_convert" : {
      "USING" : { "type" : "integer", "value" : [ "node:field-fecha-de-pago" ] },
      "PROVIDE" : { "conversion_result" : { "fecha_pago_converted" : "fecha_pago_converted" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "fecha-pago-converted" ],
        "op" : "-",
        "input_2" : [ "fecha-parcialidad-converted" ]
      },
      "PROVIDE" : { "result" : { "diferencia_en_segundos" : "direfencia_en_segundos" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "diferencia-en-segundos" ],
        "op" : "\/",
        "input_2" : "86400"
      },
      "PROVIDE" : { "result" : { "diferencia_en_dias" : "diferencia_en_dias" } }
    }
  },
  { "data_convert" : {
      "USING" : { "type" : "integer", "value" : [ "diferencia-en-dias" ] },
      "PROVIDE" : { "conversion_result" : { "retraso_dias_round" : "retraso_dias_round" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-parcialidades-dias-retraso" ],
      "value" : [ "retraso-dias-round" ]
    }
  }
]

}
}


How to rearrange the user registration form fields I want to Rearrange and Rename the default fields with added fields on user registration form in drupal7 site, I could rearrange only the fields which is added by me but i want to rearrange combining both the default and added one. can anyone help on this.!

Fields can be rearrange by changing '#weight' attribute of field in hook_form_alter(). You will have to create a custom module and have to alter the form and its element. The associative array would be something like this

$form['account']['name']['#weight'] = 7;


EVA field: file entities filtered by taxonomy term of attaching node I have a node type 'XY' with a reference to a taxonomy vocabular 'country'. Also I have a reference to this vocabular in file entities.

I have a view with an EVA display. This EVA field is attached to the node type 'XY'. This view displays file entities. These entities should be filtered by the taxonomy term of the attaching node.

When a node has the taxonomy term 'America', all file entities with taxonomy term 'America' as well should be displayed in the view (and in the node via the EVA field).

Without any filter it works with displaying all file entities.

I set a contextual filter File:

Country (field_file_image_country), Provide default value->Field value from current node/term->field_gallery_country (the taxonomy reference in node type)->TID

Specify validation criteria->Taxonomy Term->Vocabular 'Country'->Filter value type 'Term ID'

But it doesn't work. Nothing's displaying.

I have a similar case of two Content types that share the same Taxonomy vocabulary referenced, and the need to show all nodes of Content type B that are tagged with a certain term to show on the node type A that is also tagged with the same term.

I created EVA views display that lists nodes of type B, under Bundles chose Content type A, under Arguments chose token (Use tokens from the entity the view is attached to) and chose

[node:field-myvocabulary:tid]

for token replacement (I selected it from the list below the textfield).

Then under Contextual filters I added

Content: Has taxonomy term ID

and set it up like this:

When the filter value is NOT available

Provide default value Taxonomy term ID from URL
Load default filter from term page
Load default filter from node page, that's good for related taxonomy blocks
Limit terms by vocabulary (myvocabulary)
Filter to items that share any term

When the filter value IS available or a default is provided

Specify validation criteria
Taxonomy term:
(myvocabulary)
Filter value type:
Term ID
Transform dashes in URL to spaces in term name filter values
Action to take if filter value does not validate:
Display "Access denied" (this hasn't been triggered for me)


Change autocomplete path with hook_form_alter() I'm trying to change the autocomplete path of a node reference field (References module) with a custom module using hook_form_alter().
I have no problem changing any property of the field except the ["#autocomplete_path']. when I set another value for this, the field loses its autocomplete feature. (The hidden autocomplete field isn't there anymore as well) I find this totally weird, and haven't found anything about this in issue queues or anything like that.

Just FYI, I've setup a new MENU_CALLBACK path with hook_menu() and a callback function, so I'll be able to return JSON suggestions depending on some custom parameters and the value of another field.

On a stock installation of Drupal 7 and references 7.x-2.0-beta3 I was able to use the following form alter to successfully change the autocomplete path for a node reference field on the article content type:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_node_ref'][LANGUAGE_NONE][0]['nid']['#autocomplete_path'] = 'another/url';
  }
}

Another option is to ignore the form and use hook_menu_alter to change the callback for node_reference/autocomplete/%/%/%. Your callback should accept $entity_type, $bundle, $field_name which you can use to filter out which requests you want to respond to.


How to output all taxonomy field values on a node in views? How can I display all field values that are on the taxonomy terms that are applied to a given node?

So say I have the following Vocab defined:

Vocab name:Fruit Description:Fruit Categories w/ codes Field: fruit_code

And I add the following terms:

tname:Apple fruit_code:appl
tname:Orange fruit_code:orng
tname:Pine Apple fruit_code:pin_appl

Now.. I can apply a field to my view that will output all the tax termnames associated with the nodes that are returned: ie. "Apple, Orange, Pine Apple"..

But when I add the relationship for tid to the view and then try outputting the fruit_code field.. I get duplicate nodes returned, one for each term applied to the node.  How can I get the fruit_code to oupt in the same manner as the termnames in my view w/o having duplicate nodes displayed??

You can use the views distinct mode.

Drupal 7: Query Settings > distinct
Drupal 6: Distinct

Either that or hook into the view and do some extra processing through a custom module.


Notice: Undefined index: node-readmore in theme_preprocess_node() I am using this code on D7 for my themes template.php to replace default 'Read More' title with 'Read More →' (it just adds arrow):

function theme_preprocess_node(&$vars){
  $vars['content']['links']['node']['#links']['node-readmore']['title'] = str_replace("Read more","Read more →",$vars['content']['links']['node']['#links']['node-readmore']['title']);
}

It all works, but when clearing cache I get this error message:

Notice: Undefined index: node-readmore in theme_preprocess_node()

Probably the page view of the node not including the read more link.

e.g

function theme_preprocess_node(&$vars){
  if(!$vars['page']){
    $vars['content']['links']['node']['#links']['node-readmore']['title'] = t('Read more →');
  }
}

or perhaps

function theme_preprocess_node(&$vars){
  if(isset($vars['content']['links']['node']['#links']['node-readmore'])){
    $vars['content']['links']['node']['#links']['node-readmore']['title'] = t('Read more →');
  }
}

No need for the str_replace either if just setting the full text string.

Note, an alternative is to translate that text,

e.g with stringoverrides or in settings.php

$conf['locale_custom_strings_en'][''] = array(
  'Read more'      => 'Read more  →',
  'Old text 2'      => 'New text 2',
);


after updating 7.12 to 7.14 can't update modules I guess I should have updated the CKEditor (currently 7.x-1.8), Date (7.x-2.3) & Webform (7.x-3.17) modules before updating Drupal 7 core. Now, I am unable to update the three modules. When I go to Home » Administration » Reports » Available updates, and then check any one or all three modules, I click Download the Update. Then, I see "Ready to update" and then after clicking "Continue", the site goes directly back to the home page. Any suggestions of how I might be able to update my three modules?

This is probably a problem with folder/file permissions. You can try changing the permissions of the sites/all/modules folder, and of the problematic modules' folders. You can read more about changing permissions here (follow the links there to see what's recommended; basically 755 should do). Possibly these modules cannot be removed by Drupal because of the ownership settings of the files/folders in question.

You can also do a manual update, as explained in the answers to this question.


Newly created node type is always disabled I have created a new node type using a custom module on Drupal 7. However when I check the content type under the structure menu item it isn't listed. Looking in the node_type table, I see that it is listed as disabled. My question is how do I get the content type to be enabled?

Here is my content type creation function located in mymodule.install file:

// define the node type
  $type = array(
    'type' => $machine_name,
    'name' => $t($parameters['name']),
    'base' => 'room_reservations',
    'module' => 'room_reservations',
    'description' => $t($parameters['description']),
    'has_title' => TRUE,
    'title_label' => $t($parameters['title_label']),
    'custom' => FALSE,
    'locked' => TRUE,
    'disabled' => FALSE,
  );

// set other node defaults not declared above
  $content_type = node_type_set_defaults($type);

// add the body field
  node_add_body_field($content_type, $t($parameters['body_label']));

// save the content type
  node_type_save($content_type);

I believe this is correct but it obviously doesn't work. Any ideas

Drupal base install uses this configuration to create the basic page content type. Try to modify the custom value just like the example underneath:

$type = array(
    'type' => 'page',
    'name' => st('Basic page'),
    'base' => 'node_content',
    'description' => st("Use basic pages for your static content, such as an 'About us' page."),
    'custom' => true,
    'locked' => true,
    'modified' => true,
    'disabled' => false,
);

Edit

I've just checked the code of some Drupal core modules how they manage the creation of content types within code.

The Blog module defines the content type within the HOOK_node_info (just like you did). This to notify Drupal about the new type. The HOOK_install only add fields to the content type. The module also implement the HOOK_form for the content creation form and HOOK_view for the rendering.

// blog.install
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

// blog.module
function blog_node_info() {
  return array(
    'blog' => array(
      'name' => t('Blog entry'),
      'base' => 'blog',
      'description' => t('Use for multi-user blogs. Every user gets a personal blog.'),
    )
  );
}

}


Help with Pagination I used this code to get a pager.

   if (isset($_GET['tid'])) {
     $id=($_GET['tid']);
     $query = new EntityFieldQuery();
     $query->entityCondition('entity_type', 'node');
     $query->entityCondition('bundle', 'escorts_product');
     $query->pager(2,1);
     $query->propertyCondition('status', 1);
     $query->fieldCondition('field_product_sub_cat', 'tid', $id,'=');
     $result = $query->execute();
    //print "<pre>";print_r($result);
    }

When I used print "<pre>";print_r($result), it gave me 2 results on y page, whereas I added more than 2; this is right.

How should I get links for next page and also previous, next? Is there any other way to get a pager?

To get the links for the next/previous pages you need to use theme('pager').

On this post you can find an example of that implementation.


How to docreate a function to do if conditions dependign on content type name {% if logged_in == false %}

Heading

some text.

something here

    <buttonLearn
    more</button>

{% else %}

 {% endif %}

Hi Folks, in the code example above I have tried do doing some twig foo. It works greate if th user is looged out.

But what if I like to seperate contnet types by machine name?

So for example you have two names lets say article and block

How to make shure that the field is visible on block but not on artivle for logged out users? in short what is the required functioon to get false or true bi a string containing the content type machine name to do something like

 {% if logged_in == false || somefunction= 'content_type_machine_name' %}

Is that possible?

You can set a variable in hook_preprocess_Hook function which has the content type and then use that variable in twig file.

$node = \Drupal::routeMatch()->getParameter('node');
  $nids = $node->nid->value;
  if($nids){
    $variables['content_type'] = $node->bundle();
  }


Display Suite ignores hook_preprocess_node() It seems like the Display Suite module completely ignores hook_preprocess_node() and hook_process_node(). Is this the case?

If it is so, what is the way to make minor changes to the final rendering with access to all the node variables?

Display Suite does indeed hijack the node rendering to a point where the default preprocess functions may not be used.

The module comes with a set of its own preprocess functions that are documented in ds.api.php.

In this case, hook_ds_pre_render_alter() can be used instead of the hook_preprocess_node() to modify the output via the complete render array. Also, the $entity object is available with all values.


Drupal 8, entityQuery with operand "AND" for a multiple values field I have 2 contents who contains a field 'field-test'. The 'field-test' contains an array of taxonomies (its a simple multiple values taxonomy field) :

Node A :

  field_test : '1','2','3,'4' // where 1,2,3 and 4 are tids

Node B :

  field_test : '4','5','6,'7'

With the entityQuery api, I can get nodes who contains the taxonomy '4' OR '5' with :

$test = \Drupal::entityQuery('node')
  ->condition('field_test', array('4','5'),'IN')
  ->execute();
// get nodes A and B in an array

But I want get only the node B (only the node who contains taxonomies 4 AND 5)
How can I do that ?

Thank you :)

I'm not sure if you can do that using an entity query.

You could specify the delta explicitly:

\Drupal::entityQuery('node')
  ->condition('field_tags.0.target_id', 1)
  ->condition('field_tags.1.target_id', 2)
  ->execute();

But of course that would only match if the ids are used in those specific deltas.

You probably need to use raw SQL for this, see https://stackoverflow.com/questions/3918351/sql-query-ensure-a-row-exists-for-each-value-in for the basic approach on how to do this.


Load node entity from external script with image URI I'm attempting to grab a node from a node ID in an external php script.
With Drupal 7 I used the bootstrap.inc but with Drupal 8 this are a bit different.

I've called Drupal with:

define('DRUPAL_DIR', $webroot);

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\file\Plugin\Field\FieldType;

$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

I'm then successfully loading the node with:

$node = \Drupal\node\Entity\Node::load($nid);

I'm able to grab values with:

$node->get('field_test_field')->value

but I'm unable to get a uri for images. If I try and get the target_id with:

$node->get('field_image_field')->value

I get an error and the following in the error log:

Error: Call to undefined function Drupal\\file\\Plugin\\Field\\FieldType\\file_default_scheme() in /var/www/vhosts/rootpath/webroot/core/modules/file/src/Plugin/Field/FieldType/FileItem.php on line 39

Any idea how I get get the image path? The returned node object includes:

[field_image_field] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 44595
                                [alt] =>
                                [title] =>
                                [width] => 250
                                [height] => 89
                            )

                    )

            )

Not sure what I missing, perhaps I need to include a namespace or something?
Thanks in advance!

you can try:

$image_uri  = $node->field_image_field->entity->getFileUri();

echo $image_uri;

$image_url= file_create_url($image_uri);

echo $image_url;

in the variable "$ image_uri" contains the uri of the image.

in the variable "$ image_url" contains the complete url of the image.

Note: please, change field_image_field for your machine name field


Categorized view for an entity reference content I am trying to implement a Magazine in Drupal 9. I am confused about whether to use taxonomy term or content type since the data I want to handle is used for both categorizations and storing of content.
I have the following content structure.
A Magazine will have a number of articles, which are categorized under Topics.

Magazine 1

Topic 1

Article 1
Article 2

Topic 2

Article 3

Magazine 2

Topic 2

Article 4
Article 5

Topic 1

Article 6

At present, I am trying the following:

Magazine - content type
Article - content type
Topic - Taxonomy term

Should I use taxonomy term or content type for Magazine? The Magazine content type is used for storing content (for example, cover image, description, and date) and also can be thought of as categorizing the articles and topics.
Please note: A topic can be used in multiple magazines.
I have already gone through the following:

Difference between nodes and terms
Creating content hierarchy

I hope someone can guide me through the correct path.

Drupal 8 taxonomies are entities so you can add custom fields, images (magazine covers), icons, as well as using for classification.
It doesn't sound like the Magazine "content type" is that complex, more of a catch-all for a listing of all your various articles and content related to each magazine, so that (Magazine as a taxonomy) would be my inclination in this situation.
The classification features of taxonomy work better out of the box than if you were do something custom with your content type.
I'd have 2 taxonomies for organising topics by:
(1) Magazine
(2) Topic
If you are doing - or envisage possibly doing - something more complex with your Magazine type at a later stage then content type rather taxonomy may be the way to go.
As always with Drupal, there's more than one way to do it and you have to weigh up the pros and cons taking into account: ease-of-use, navigation, theming, scaleability, overhead, etc.


What is "alias" in db_select() function? Beginner Drupal Developer. The drupal API didn't provide info for what purpose the $alias must be used in db_select? And what is that anyway?

In Drupal database API alias means exactly the same thing it means in SQL world - short name assigned to table or field to simplify further referencing it during this one query. Some table names are pretty long, and you can't always count on Drupal to be able to resolve prefixes, so aliasing mystupidlongprefix_field_revision_field_some_pretty_long_name_for_field_containing_a_gallery with something simple, like frg (field revision gallery), or something other you will recognize when you will read this query, both make it way easier and faster to write and understand code, and also allows you to use this table for example in conditions, where using {table_name} syntax for automatic prefixes is not always feasible.


How to use Vertical Tabs on ConfigEntity Form how are you?
I've created a ConfigEntity and there a Configuration Form with Fieldsets and Fields.
Example:

But now I want to change this form to Vertical Tabs, like that:

Do you know how can I do this?
P.s. It is for the Contrib project if you want to test it is:
https://www.drupal.org/project/modal_page

Use the vertical_tabs form element. There is an example shown in the API documentation for this form element: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21VerticalTabs.php/class/VerticalTabs
In short, instead of using nested fieldsets, create a 'vertical_tabs' form element as the container then put multiple 'details' form elements inside it. Each of the 'details' elements will serve as the container for one vertical tab. See the example in the API documentation for the exact syntax.


Add nofollow to quicktabs I have set up quicktabs programmatically - all working fine. Code is as follows:

    $tabs['overview'] = array(
        'title' => 'Title of tab',
        'contents' => $content,
        'weight' => 2,
    );

.. etc

    $qt_options = array(
        'style' => 'nostyle',
        'ajax' => FALSE,
        'default_tab'=> 'overview',
    );

    $qt_name = 'project-tabs';
    $qt_project = quicktabs_build_quicktabs($qt_name,$qt_options,$tabs_project);

Issue: I need to add a rel='nofollow' to the quicktabs.  Are there any attributes option I can pass to the $tabs array? Similar to using the l() function?  I've looked and tried a few things, but nothing seems to work.

Unless you want or can modify $qt_project and add in the rel to the attributes array of the links, the only way I see is to add in a custom renderer in your module.

This would entail some ctools integration implementing hook_ctools_plugin_type(), some quicktabs integration implementing hook_quicktabs_renderers() and then basically copying QuickQuicktabs.inc from the quicktabs module to your module's directory structure, changing the name to something appropriate, and then inside, also changing the name of the QuickQuicktabs class to something similar, and then in the guts of that, changing

/**
 * Helper function to construct link options for tab links.
 */
protected function construct_link_options($tabkey) {
  $qt_name = $this->quickset->getName();
  $id = 'quicktabs-tab-' . implode('-', array($qt_name, $tabkey));

  // Need to construct the correct querystring for the tab links.
  $query = drupal_get_query_parameters(NULL, array("qt-$qt_name", 'q', 'page'));
  $query["qt-{$qt_name}"] = $tabkey;

  $link_options = array(
    'attributes' => array(
      'id' => $id,
    ),
    'query' => $query,
    'fragment' => 'qt-' . $qt_name,
  );
  return $link_options;
}

to most probably just

/**
 * Helper function to construct link options for tab links.
 */
protected function construct_link_options($tabkey) {
  $qt_name = $this->quickset->getName();
  $id = 'quicktabs-tab-' . implode('-', array($qt_name, $tabkey));

  // Need to construct the correct querystring for the tab links.
  $query = drupal_get_query_parameters(NULL, array("qt-$qt_name", 'q', 'page'));
  $query["qt-{$qt_name}"] = $tabkey;

  $link_options = array(
    'attributes' => array(
      'id' => $id,
      'rel' => 'nofollow',  // just this one little addition :)
    ),
    'query' => $query,
    'fragment' => 'qt-' . $qt_name,
  );
  return $link_options;
}

and then calling quicktabs_build_quicktabs() with 'render' pointing to your custom renderer in the $qt_options array.


How do you remove N/A from radio button groups? I have added a radio button to my content type and I have found that N/A was automatically put in as a selection.  How do I get rid of this?

If you make a list field mandatory, the N/A option automatically goes away

Also, if you allow multiple values, the radio dot elements automatically becomes checkboxes.


How to programmatically create new file/folder in Drupal 7 files directory? I tried to create new file/folder programmatically inside Drupal's sites/default/files. But I'm getting this error: "Can't Open file".

Here is what I'm doing: When my registered user visits a certain page, I will be generating a new file and I will provide them with the download link. When I tried to create a new file I am getting "can't open file" message. I'm in localhost in MS Windows.

Are there any other writable folder other than sites/default/files for doing this stuff?

Below is my code:

$ourFileName = base_path()."/sites/default/files/members-pdf/testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

Above code is written inside a views's template file.

I want to use PHP file API and not Drupal 7 file API.

To create folders you can use file_prepare_directory and pass FILE_CREATE_DIRECTORY as second parameter like so:

$new_folder = 'public://newfolder/';
file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);


How to remove the click event on an Ajaxified form's submit buttons? I've created several forms with Drupal 8 directly in admin or with Form API. I've added some client side validation with this jQuery plugin : jQuery Validation Plugin.

Everything works very well. Now my client asked me to open one of these form in a popin. So I've installed this 2 modules :
Contact Block (The Contact Block module provides contact forms in a block.) https://www.drupal.org/project/contact_block

I can open form in a popin and it works well but after validation, the page is reloaded and it is not UX friendly since we are in a popin.
So I've installed this module :
Contact ajax (implements ajax submission for core Contact form in Drupal 8.) https://www.drupal.org/project/contact_ajax

It works well but the submission is done before I can execute client side validation.

The problem seems to be the priority of execution.

I've tried to apply preventDefault on the submit button but it doesn't work.

$( "#form #submit-button" ).click(function( event ) {
  event.preventDefault();
  //validation code
});

I've found this topic but I donc know how to implement the code :
How to prevent an Ajax form from submitting

I've also found this topic :
https://www.drupal.org/project/clientside_validation

Can you help me to understand how I can  block the click event on an Ajaxified form's submit buttons ?

EDIT

I've tried this module : Clientside Validation and apply this patch 2952233-5.patch

It works, the Ajax submit button is disabled. The solution is based on that answer.

For now it has a bug : the form is validated but I don't see the confirmation message at the end.

Then, I've copied the code from this patch  in my project and it works.

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    $( "#form #submit-button" ).click(function( event ) {
      event.preventDefault();
    });
  }
};

Can you try like this. This will trigger for every AJAX call.


Can I render the same block twice on a page? I want to have <?php print render ($page['homepage_video'])?> two different places on the page. By default it can only be done once, but is there a workaround for that?

If what @Chapabu said doesnt work for you, if you have any hand-coded module on your site you can use hook_page_alter to copy the render array information for the block in question and set it into another region of the page.

This is more of a 1-off solution. But, I try to stay away from extra modules todo 1 thing on a site. Especially if you're somewhat comfortable coding a solution.

Here is a small example using hook_page_build (which runs at the beginning of page builds, hook page_alter runs at the end):

/**
 * implementation of hook_page_build().
 *
 * Depending on the path or NID or whatever, we want to
 * embed additional blocks and stuff into the page.
 *
 * I could use Context or the BlocksUI for this but I
 * give clients "Basic Page" for all of these urls and I'm
 * merely appending additional data on those pages.
 */
function ccs_core_page_build(&$page) {
  _page_build_section_header_image($page);
  _page_build_embed_course_views($page);
  _page_build_embed_faculty_views($page);
  _page_build_embed_distinguished_alumni_view($page);
}

function _page_build_embed_distinguished_alumni_view(&$page) {
  if (drupal_get_path_alias() == 'people-contacts/distinguished-alumni') {
    $view = views_get_view('distinguished_alumni_listing');
    $display = 'blocks';
    $view->set_display($display);
    $output = $view->preview($display);
  }
  if (isset($output)) {
    $page['content']['system_main']['distinguished_alumni_listing_view'] = array(
        '#weight' => 99,
        '#markup' => $output,
    );
  }
}


Why is an integer variable in PHP interpreted as a string literal when passed from Drupal to JavaScript via Drupal.settings? This is in Drupal 7.

I'm attaching some JavaScript via drupal_attach_js(), using "settings` to be able to pass the "height" parameter to a JavaScript function. The height is used in a modal dialog, and it will vary depending on the amount of data that the modal will contain.

Here is my JavaScript code:

(function ($) {

  Drupal.behaviors.designer = {
    attach: function (context, settings) {
      // ...some code to activate modal...
      height: settings.designer.jquery_modal_height,
      // ...some more code...
    }
  };

})(jQuery);

If I run console.log(settings.designer.jquery_modal_height), then the console displays the value of this variable, but the actual "height" parameter seems to take the code literally and never applies it's actual value.

Am I doing something wrong?

If you do

{
  ..
  height: settings.designer.jquery_modal_height,
  ..
}

You are doing it right, else you should do

..
var height = settings.designer.jquery_modal_height;
..

Most likely it's not the variable that's the problem but some other part of your code.


how to add cck field to a content type Programatically in drupal 7? Possible Duplicate:
  Programmatically create Fields in Drupal 7

I want to to add a cck field to a content type Programatically in drupal 7.

Any one who have some idea about this?

The main functions of the Content Creation Kit (CCK) have migrated into core in Drupal 7. Now every object used by Drupal (users, nodes, even taxonomy terms) are "fieldable entities." What does this mean? Simply that you can add fields to most objects in Drupal out of the box, no CCK required!

If you're building a module that alters pre-existing node types, you'll need to check out the Entity API. I'm not too familiar with it myself, however, it doesn't seem that hard to programmatically add fields. As Bojan Zivanovic mentioned, there are many other answers dealing with this on Drupal StackExchange, here are a few for you to peruse:

- Programmatically Creating Fields in Drupal 7

- Assign Fields Programmatically to Custom Node in Custom Module

If you're just adding fields to nodes for site building purposes, I'd just use the UI.

To do so...

Go to the "Structure" menu.
Select "Content Types."
Click on "Manage fields" next to the content type you want to add fields to.

You should then be presented with an interface to add new fields to your content type, much like you did with CCK in Drupal 6.


Adding a dropdown list to the Registration Form. Drupal 7 How would I go about adding a dropdown list to the user registration form? Also, is there a limit as to how many dropdown items you can have?

You can do this via the UI by going to (admin/config/people/accounts/fields) and then adding your new field.  There is no limit to how many fields you can have.


How do I set a custom input format for a field? After using Drupal 7 for years, I am now handed a Drupal 8 site to do some editing. I have created a custom input format (Plain HTML), and I want to print this field with this input format in a custom template. How can I achieve this?

With {{ content.field_mapka_markery }}, it prints plain text. There is no choice to select my newly created input format in the Manage display settings. Why is that? In Drupal 7 there is always a new formatter,  but not so in Drupal 8.

I also tried {{ content.field_mapka_markery|raw }} or .value. |raw doesn't  work at all, and .value does the same as without it.

Managed to create a new field with "Text - Formatted - Long" as default, which allowed me to set up my custom text format. Why is that not possible for plain text field I am not sure.


How do you check to see what your drupal site looks like as different types of users? I hope to find a way to stay logged in as admin but see what it looks like to an unauthenticated user and other types of users too, if possible.

I ask firstly because right now I am trying to make certain changes to the css file which means I need to check what the change looks like to an unauthenticated user. Sometimes it is easy to see more or less what I want in the admin pages but I do find I can get tripped up by this sometimes and also find I need to clean the cache of my browser before I can actually see how it looks. This is something that I do not really want to be taking much time over as I want to be able to correct it quickly if I made something look terrible.

Aside from that I do also have a few different kinds of users with various permission rights and when I change something I want to check that a change is doing what I want and all the users are still seeing the right things. Again, it is not an ideal situation for me to have to log out and in as each type of user for this type of thing as it can expose parts of the site if a mistake has been made or there is some bug rearing its head etc.

Aside from the aforementioned issues I have with needing to log in and out after every little change I make to the site, it makes the whole process pretty laborious. It suddenly dawned on me that someone else might have thought this too and that there is some way to work around it without compromising anything. Can anyone advise on this?

For the anonymous user you will require a second browser (not logged in) or you will have to log out to view the changes. For other roles, check out the Masquerade module. It permits you to rapidly switch user roles by masquerading as a user with that role.


Modify checkbox event on custom line item type to hide show div I have a block of custom length fields and a rule to figure them and put the correct total in the cart however I want to hide the div that contains them unless the exact lengths checkbox is checked

however currently this always shows on my test site and from how the site is set up now with a paragraph of instructions and a textbox i've found that people are lazy and don't read directions.  so I don't want to give anyone the opportunity to fill in fields without the checkbox checked

I have tried using JS_Injector to add some js to hide and show but it only seems to be able to add js to the header or footer which doesn't help me add it to the form on the checkbox change event does anyone have any other suggestions short of telling me to write a module with a hook_form_alter()?

I think the Conditional Fields module should do the job.

It allows you to create rules to hide or show fields based on another fields value - so perfect for you.


Drupal 7: Filter nodes with a date range arround an exposed date My issue is somewhat opposite of the common "List nodes within a date range".

So, I have an Event content type, with fields start_date and end_date. They show when the event starts, and when the event ends. Now I need to be able to select a date and fetch all events for which start_date < selected_date and end_date > selected_date.

The selected date should be an exposed filter to all users, or any other way that makes it possible to be fetcher from the URL.

Thanks in advance!

Have you tried adding an exposed filter in your view?  I'm assuming you're using a view already, and I'm assuming you're using Drupal 7 (it's always helpful to specify that in the question, by the way :-)).

Add the date in question to your list of filters, check the box to expose it to users and use the 'is not between' option.  Then you can either specify a hard coded date for the 'from' and 'to' or you can even use a relative date (second value type option) and specify something like '-30 minutes' and '+30 minutes' and it will re-calculate them based on the current time...

Hope this helps.  Let us know if it works.


Where should I be storing custom node-related data? There are several types of data my website generates for every node. Node's popularity score, node's comment count obtained from a 3rd party API, etc... This data is set for every node.

In the past I've used to just add hidden fields to each node, i.e. field_popularity_score, field_comment_count, etc..., and had the fields updated on hook_cron; but I've ran into an issue. Each time those fields are updated, the node's revision date would change also.

Where should I be storing this data? I'd prefer to stay away from using the standard node fields, as it would break its purpose.

Update

Apparently, per this post, Drupal 5 used to allow storage of serialized data into $node->data.

Update

Interesting enough, Node object reference page lists $node->data as part of Drupal 7. I would love to hear if there is a way to use that field to store serialized data in Drupal 7.

I would suggest making your own table in the database, it's a perfectly acceptable practice if you name the table something unique that isn't likely to collide with other modules.

The database API is an extremely useful resource for this.

[edit:] Thanks to J. Reynolds - in this instance you will definitely need to tell Views about your table.


First attempt to adding states to a custom Content type // sample code
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function demo_form_sport_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_winter_sports'] = array(
    '#states' => array(
        'visible' => array(   // action to take.
            ':input[name=field_season]' => array('value' => t('winter')),
        ),
    ),
);

}

i am trying to alter a form from a "sport" node type. my "sport" node type has 2 fields.

field_season List (text)    Check boxes/radio buttons
field_winter_sports List (text) Check boxes/radio buttons

there are two options in field_season, summer or winter.

if someone selects winter in field_season, i want to make field_winter_sports visible, otherwise remain hidden.

with my current code, when i select winter right now, nothing happens.

There are two things to consider:

The name of the input element is visible in the HTML output of the page, and that could not match with the ID used for that form element from the form API. That happens with form elements created with the field API too.
I created a field_season field, which allows just a value to be select (which means it is rendered with radio buttons); the input element name that appears in the HTML output, which is the one jQuery sees, is field_season[und], not field_season.

If I change the field to allow three choices (which means the form field is rendered as checkboxes), the input element name changes to field_season[und][1], field_season[und][2], and field_season[und][3].

When you want to tell to Drupal to alter the state of a form element when a radio buttons are used, you should not use t(), and the string to use as value in the state is not the string that appears to the users, but the value assigned to the value attribute of the <input type="radio"> tag. For example, for the form element added from the following code, those values are 0, 1, and 2.

$form['registration_cancellation']['user_register'] = array(
  '#type' => 'radios',
  '#title' => t('Who can register accounts?'),
  '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL),
  '#options' => array(
    USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
    USER_REGISTER_VISITORS => t('Visitors'),
    USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
  ),
);

Since the input element name contains und, which is the string value for the LANGUAGE_NONE constant, I suspect the input element name could change basing on the language associated with the field, even if I suspect it would always be und, for radio buttons and checkboxes.

As side note, learningxm is correct when it says that you should use `:input[name=""]' since that is what the example in the drupal_process_states() page shows.

$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);
$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);

As noted by Clive, you are overriding the form element added using the field API; to change the states associated with the form element, you should just use the following code.

$form['field_winter_sports']['#states'] = array(/** Add here your states. **/);

I assume field_winter_sports is the correct form element ID.

I would also investigate using hook_field_widget_form_alter(), which is the hook thought to alter the form elements used for a field.


Alter field value in a form I've created a module so users can insert a link.

When users will insert their link, i wish to add a suffix to the link.

For exemple : they will add a link > "www.test.com"

I want to be able to add to the link once they hit save "http://"

So the link will be http://www.test.com

When i do :

$form['attributes']['href']['#prefix'] = 'prefix';

I get :

What's the best way to do it without using $form['attributes']['href']['#default_value']

Many thanks,

As you want the suffix to be added when the save button is added you need to add a custom submit handler. In the hook_form_alter do something like       $form['actions']['submit']['#submit'][] = 'mymodule_form_submit'; and in the submit function mymodule_form_submit save the value you want.

function mymodule_form_submit(&$form, FormStateInterface $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  // Get the value of your field
  $my_val = $entity->get('field_name')->getValue();
  // Set new value
  $entity->set('field_name', 'http://' . $my_val);
  //Save the entity
  $entity->save();
}


Allow access for anonymous to custom user view mode I made a custom view mode with display suite for the user entity. It is called "user_teaser" and shows some fields that may be visible for Anonomous user. Unfortunately currently anonymous users cannot see it because of the general "View user profiles" permission which they have no access to.

Which hook should I use to bypass this permission and allow anonymous to see my custom view mode?

I tried hook_entity_view_alter() as below, but this is called already too late I think as it is not even called when the access to the user profile is blocked.

function MODULE_entity_view_alter(&$build, $type) {
  if ($build['#view_mode'] == 'user_teaser') {
    $build['#access'] = TRUE;
    $build['user_image']['#access'] = TRUE;
  }
}

So I would need a hook_entity_access_alter or hook_user_access_alter or a hook_entity_access_query_alter, but they don't exist.

(edit) I found now some lead that might have a solution: How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)

As you already guessed the permission is checked before building the content, so you will never be able to display any user data without that permission. (At lest not without some programming.)

You could try to grant the View user profiles permission to all user and then use the Field Permissions module and grant access per field. So you can show anonymous users only the fields they should have access to.

UPDATE:

As you have pointed out the above solution introduces some problems with privacy and some additional fields not being hidden on the user profile.

So another suggestion; Remove the Views access check. Views by default bypasses access checks on content (so Views without access checks are considered unsafe). Which might be of benefit to you here. As an alternative you can set a more generic permissions such as View published content to prevent errors from modules like Security Review.

Then under display choose Display Suite and your custom view mode.

You will end up with a View that shows the custom View mode with all selected fields, even for anonymous users. Yet the user profile at example.com/user/1 shows access denied for anonymous users.


content type "custom data" I have created a content type that has a "number of accepts" field. I want to add a button, "accept", to the content type. When a user clicks it, it will temporarily store their username and etc. Depending on the number of accepts field, the content type will display "1/10 Accepts" for example. How would I be able to do this and have the number of accepts displayed in realtime. thanks!!

You can create using hook_form_alter() and I get my button on the Add/Edit node form:

$form['actions']['accept_and_adduser'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Add a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_node_form_submit'), /* NEED this */
  '#weight' => 1000
);

But, clicking the button doesn't seem to hit hook_node_submit() or hook_node_insert(). I'm assuming I'm missing a hook or something in the button creation...anyone have any ideas?

Then added this function:

function mymodule_node_form_submit($form, &$form_state) {
  // Do stuff before saving the node, saving the data of users in some table and calculate it

  // Call this to save the node
  node_form_submit($form, $form_state);

  // Do stuff after saving the node
}


Want to show url like termname (parent)/[termname] (Child: referenced by node) /node (node which is referenced to particular term) Having problem to show url like termname (parent)/[termname] (Child: referenced by node) /node (node which is referenced under particular term)

i want this http://www.example.com/pets/cats/diseases/4-normal-diseases-of-kittens

here pets is parent term name
cats is child of parent 'pets' term name
diseases again sub term name of 'cats'
'4-normal-diseases-of-kittens' is article term referenced to diseases

Thanks in advance

In your URL aliases patterns, use this token : [node:YOURTAXONOMYFIELD:parents-all] (Ancestors of the term, i.e. parent of all above hierarchy levels).

Then your whole pattern for your node type will be [node:YOURTAXONOMYFIELD:parents-all]/[node:title].

If you have languages matters, I guess it might work with i18n prefix.


Is there a function to get the current user object that avoids accessing the global variable? I've always gone with this global $user;. However, I seem to remember seeing something in a contributed module that returned the current user object without using the global $user.

Does such a function exist in Drupal 7 core, or is using the global variable the de-facto recommended way to get the current user object?

The function you could use is user_uid_optional_load(); without arguments, it returns the user object for the currently logged-in user. It still uses the global $user, and loads the full object from the database, including the fields associated to users, but it avoids your code accidentally change the content of the global variable $user, as it is not referenced from your code.

function user_uid_optional_load($uid = NULL) {
  if (!isset($uid)) {
    $uid = $GLOBALS['user']->uid;
  }
  return user_load($uid);
}

If you don't need the full object, then you can use the code already reported in the other answers. If you want to be sure you don't alter the global object, you can copy the global variable into a local variable, as in the following snippet.

$account = $GLOBALS['user'];
// Use $account.

In Drupal 8, you simply use the static method \Drupal::currentUser() to get the equivalent of Drupal 7 $GLOBALS['user'] and \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()) to get a fully loaded object with all its field API fields. There isn't anymore the risk of overriding a global variable with all the consequences.
In the case you need to switch the current user with, for example, the anonymous user, the code you use in Drupal 8 is the following one.

$accountSwitcher = Drupal::service('account_switcher');
$accountSwitcher->switchTo(new Drupal\Core\Session\AnonymousUserSession());

// Your code here.

// Eventually, restore the user account.
$accountSwitcher->switchBack();


How to:Pass arguments to views and use that as contextual filter-in code I have a views created in code. I am passing arguments(for contextual filters) to this view from another view like this:

sitename/apage?ids=1,2

Q1. Is this the correct method? If not what is?

Q2. How do i retrieve 1 and 2 (above) in the view where i want to use them as filters(contextual) for products/nodes with these ids.

Please help!

Contextual filters are passed not like $_GET parameters but like part of an url (by $_GET parameters exposed filters are sent).
if you want send several values for one contextual filter - you need to separate them with comma or plus.

For example you have view with url '/product' and 2 contextual filters - 1st filter is product ids, and second one is country id.
The url of a view can look like this 'product/12,45/55'
In this example view will take 12 and 45 as product id and 55 as country id.


twitter block module I am trying to embed a timeline of tweets to my website's sidebar. I am using Drupal 8. The module "Twitter Block" requires a widget ID but Twitter has stopped providing widget ids and only generates html code but I don't know at which file should I embed this code to. Is there any other way? Any suggestions?
Thank you.

Sorry for this late reply... but here is the module you are looking for:

Twitter API Block

As explained in its README file, you need to download it and the required library with composer, as follow:

composer require drupal/twitter_api_block drupal/j7mbo/twitter-api-php

Then go create a new app in Twitter and finally, place the block in your Drupal site.

Simple :) Enjoy!


An ajax jump menu using Drupal views? I've got a Drupal view that contains a jumplist of items filtered by taxonomy (which is pulled from the current page URL).

The problem is that I need this jumplist to work without a page reload (so using AJAX).

I've tried a few different things and done a lot of Googling, but come up with nothing.

I've read that you can expose filters to users and use this for Ajax filtering, the problem with this seems to be that you can't populate a select element with values from the database when using a filter, it looks like the filter values have to be hard coded or user defined, so this looks like a no go.

Is there any way of accomplishing this? Or am I going about this in the wrong way?

I am not 100% on your desired set up but there are a couple of ways that I can think of to get the functionality that I believe you want. If you have a view with filters and displays that also includes a jumplist (the jumplist is just a part of your desired view) I would suggest adding an attachment to your view. This attachment can share contextual and exposed filters.


How can I hide menu items based on permissions? In my main menu I have a "menu item 1" that links to mynode1.

I have successfully implemented hook_permission() and hook_node_access() so that users who do not have the "access menu item 1" permission  cannot access mynode1.

I assumed that the menu item link "menu item 1" would automatically be hidden by Drupal, but this is not the case. Therefore I now would like to hide that menu item to users who do not have "access menu item 1" permission.

Does anyone have a code sample that would hide a menu link based on permission? (I tried hook_menu_alter() with no luck.)

Hi have done it this way:

function mymodule_menu_link_alter(&$item)
 {
  $item['options']['alter'] = TRUE;
 }

function mymodule_translated_menu_link_alter(&$item, $map)
 {

  if (!empty($item['access'])) {

  if(
   ( $item['link_title']=="MyLinkToHide1" && !user_access("access link 1") ) ||
   ( $item['link_title']=="MyLinkToHide2" && !user_access("access link 2") )

   )
   {
            $item['access'] = FALSE;
   }

 }
}


How do you use the Drupal 7 overlay on the node/edit screens for your popups when it's already being used? I'm writing a module that adds a button to node/edit forms. This button needs to popup a DIV/IFRAME in a light box. I notice that Drupal 7 uses the new Overlay module for administrative and node/edit pages.

So my question is as my button is on a node/edit page I need to overlay the overlay. Is there a way to access the overlay and change or z-index or do I just write my own overlay code to create a light box effect (overlaying the node/edit overlay)?

It is possible to change the z-index used by the overlay, but I don't think it's necessary. You just use for your overlay a z-index that is higher than the one used by the Overlay module.

In the case you need to know when the overlay is output, or how it is output, you should check the code executed by overlay_page_alter(), which is the implementation of hook_page_alter() made by overlay.module.

function overlay_page_alter(&$page) {
  // If we are limiting rendering to a subset of page regions, deny access to
  // all other regions so that they will not be processed.
  if ($regions_to_render = overlay_get_regions_to_render()) {
    $skipped_regions = array_diff(element_children($page), $regions_to_render);
    foreach ($skipped_regions as $skipped_region) {
      $page[$skipped_region]['#access'] = FALSE;
    }
  }

  $mode = overlay_get_mode();
  if ($mode == 'child') {
    // Add the overlay wrapper before the html wrapper.
    array_unshift($page['#theme_wrappers'], 'overlay');
  }
  elseif ($mode == 'parent' && ($message = overlay_disable_message())) {
    $page['page_top']['disable_overlay'] = $message;
  }
}


How to fix error Undefined index: parent in taxonomy_form_term_submit()? I got below error on my site recently.

  Notice: Undefined index: parent in taxonomy_form_term_submit() (line 829 of /var/www/Sites/xxxxx/modules/taxonomy/taxonomy.admin.inc).

I google it and find there is an old issue but seems nothing solved.

In the issue, @Cracu did mention some part of core code may cause this error:

  if (!variable_get('taxonomy_override_selector', FALSE)) {
    $parent = array_keys(taxonomy_get_parents($term->tid));
    $children = taxonomy_get_tree($vocabulary->vid, $term->tid);

    // A term can't be the child of itself, nor of its children.
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
    $exclude[] = $term->tid;

    $tree = taxonomy_get_tree($vocabulary->vid);
    $options = array('<' . t('root') . '>');
    if (empty($parent)) {
      $parent = array(0);
    }
    foreach ($tree as $item) {
      if (!in_array($item->tid, $exclude)) {
        $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
      }
    }
    $form['relations']['parent'] = array(
      '#type' => 'select',
      '#title' => t('Parent terms'),
      '#options' => $options,
      '#default_value' => $parent,
      '#multiple' => TRUE,
    );

  }

I try to look into the latest core, this part of code is still there with same logics. Unfortunately, I need taxonomy_override_selector be TRUE.

Apart from setting taxonomy_override_selector to FALSE or adding new form validation handler to set $form_state['values']['parent'].

Do anyone know if there is solution for that?

There's a couple of ways you could go about the problem:

Patch Core: If there's no outstanding issue for the problem, alter core, create a patch & bug report, and submit your patch. You can manage your patch in your deployment process until the patch is accepted upstream.
Custom Module: Looking at the comment above the code you posted, it was authored with the intention that someone might need to alter the form ("Contrib modules can then intercept before hook_form_alter to provide scalable alternatives."). You can use a HOOK_form_taxonomy_form_term_alter invocation to alter the submission handler or the form array to mitigate the warning introduced.


Call fieldset multiple times I am using webforms in Drupal7, i give the user the option to enter multiple entries for one question. So for example, "how many players", if answer is 1, fieldset 1 opens and has name, address, number in it.

if answer is 2, fieldset 1 and fieldset two appear,
if answer is 3, fielset 1, fieldset 2, and feildset 3.

if the answer is 2 or 3, I get this error:
Conditional errors on page 2:
More than one conditional hides or shows component "One Player".
More than one conditional hides or shows component "Two Player".

so my plan was to create 10 fieldsets and have them display based on the # of players the user inputs.  I understand the error, but don't know of another way to achieve this.  [the one I came up with is just crazy and would mean so many of these inside fields, OMG ]

Any suggestions / guidance, would be appreciated.

For anyone else that stumbles on this.  I found a solution.  So remember my example is "How Many Players" [i used select option 1-5].  If user selects 1, fieldset 1 appears only, if he/she selects 2, FS1 and FS2 appear, select 3, FS1, FS2 and FS3 appear.  To prevent the error I use and or statement for allow the fieldset and worked my down down.  See image.


Render a custom module inside an existing node I have a site in Drupal 7 and I have created a custom module for a functionality that I need. Usually, I create custom modules and I create a new page to show them, using the following code:

function my_custom_module_theme() {
    $items = array();
    $items['my_custom_module'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('module', 'my_custom_module') . '/templates',
        'template' => 'my_custom_module-template',
    );
    return $items;
}

function my_custom_module_menu() {
    $items = array();
    $items['my_custom_module'] = array(
        'title' => t('my_custom_module'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('my_custom_module'),
        'access callback' => TRUE,
    );

    $items['my_custom_module'] = array(
        'title' => t('my_custom_module'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('my_custom_module_empty_form'),
        'access callback' => TRUE,
    );
    return  $items;
}

function my_custom_module_preprocess_page(&$variables, $hook) {
    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias == "my_custom_module") {
        $variables['theme_hook_suggestions'][] = 'my_custom_module';
        $variables['show_messages'] = TRUE;
    }
}

function my_custom_module_empty_form($form_state) {
    $form = array();
    return $form;
}

and my module appears on mysite/my_custom_module .
What I want to achieve now is to add my custom module at the bottom of an existing node, which has it's own content and functionality.
What should I add to my_custom_module-template.tpl.php or in my node--xx.tpl.php to display my custom module inside the node?
I have already used

<?php
   $nid = xx; // NOTE :: Hard coded, but need to be variable!!
   print drupal_render(node_view(node_load($nid)));
?>

from a similar Stack overflow question, but it does the opposite of what I want, it renders the node inside the module.

You can implement hook_node_build() in a custom module to add or alter elements when a node's content is by assembled for viewing, right before rendering.

function MODULE_node_build($node, $view_mode, $langcode) {
  // Only do something if the node is rendered on its own page, in full.
  if ($node->type == 'MODULE_type' && $view_mode == 'full' && node_is_page($node)) {
    $node->content['MODULE_stuff'] = array(
      // Insert render array content here
    );
  }
}

For sorting, you can add a #weight property in the element(s) added to $node->content. But a nicer solution is to implement hook_field_extra_fields(), so you can position the added element(s) using the usual Field UI.


How to set the field label as an ? I'd like to be able to set the field label as an <h2>. How can I do?

I'm editing the features definition for a field collection directly so if it's possible to set it in there that would be super-handy!

One can provide a field.tpl.php file within the theme.

You can copy the existing field.tpl.php file from /modules/field/theme (which btw is just auxilliary and not used by Drupal) into the theme's directory and replace the line:

<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

into

<div class="field-label"<?php print $title_attributes; ?>>
<?php print $label ?>:&nbsp;

or something.


How and where is the $variables variable used in templates etc. generated in Drupal? How and where is the $variables variables that is used in templates and theme functions generated in Drupal?

Is there documentation anywhere that defines $variables?

The $variables associated array that are passed into functions such as MYTHEME_item_list($variables) are initialized by the caller of that function.


How to insert nodes into a Views result In Drupal 7, I have a View that works great but I'd like to add a few nodes into the result arbitrarily outside of the scope of the View.

Basically, let's see the View returns Content Type X, I want to include a few nodes from Content Type Y that are in addition to whatever the View generates from Content Type X.

My preliminary thought was to use hook_views_pre_render but I'm not convinced that is the best solution....yet.

You may want to use hook_views_pre_execute (see example) or hook_views_post_render() where you can add arbitrarily content (new rows or html code) into the view to fake the nodes.

Please check the following code example to give you some idea.

You may also compare how other Views-based modules doing non-database query results, such as Search API Views or YQL Views Query Backend.


Associating Multiple Date/Location Pairs to Node I'm attempting to create a custom content type in Drupal to represent concerts.  Each concert has a title, description, and multiple dates and locations (the concert may be performed on more than one day at different locations).

Since dates and locations are dependent on each other, I thought that the Field Collection module would be ideal for me.  This module allowed me to group the date and location field and add multiple values; however, when I try to display the concerts in a calendar in Views (I've tried both Calendar and FullCalendar), I can't find a way to display the title of the concert because it is now in a separate entity.

Is there any way I could make my current content type work, or is there a better way to do this?

I was able to solve this by adding a relationship in the Views setup.  Now, I have access to all the fields of the host entity.


Drupal commerce - passing attributes from one module to other Firstly I am new to Drupal commerce and start learning it on the job as required. So if you see my question as basic functionality in Drupal commerce, please pardon me.

Question: I have a simple commerce site and it look like as follows: Product view -- Shopping cart -- checkout

After checkout, I am adding a new custom module(creating an account for the user and few other things). I need to get the attributes of the product from the shopping cart module. How can I retrieve that information from the shopping cart module to the new custom module that I am building.

Thanks in advance.

We already have a rule shipped with the drupal commerce core, which creates the user account on checkout process. It might be a good starting point for you in both ways how it is looping through order information to use in your custom module or you can modify the rule as per your requirement.

Rule is "Create a new account for anonymous user."


Get selected item in hook_form_alter in D8 I have a select box named field_p_destination, and i need to get the selected value on hook_form_alter .

I tried `

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
  echo $form['field_p_destination']['widget'][0]['value']['#default_value'];`
}

Its not working . But in case of text fields its working fine . Any idea to get the select field ?

I am just giving you the example because your scope is not clear to me,in my case i am taking node edit form where i am having a field which is select box.

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == "node_page_edit_form"){

    $v=$form[field_select_field][widget]['#default_value'][0];

    //dpm($form[field_select_field]);

    dpm($form[field_select_field][widget]['#options'][$v]);
  }
}


Conflict between Omega and Views 3 exposed sort (Ajaxified) I have made a subtheme out of the Omega 4 with the responsive structure.
I tried to use exposed sort for views inside the layouts of the subtheme.

The exposed sorts are not working under the activation of AJAX inside the views, but the exposed filters are working.

Any recommendations?!

I found the solution, it seems to be a database problem for Drupal, and nothing to do with Theme or Views!

  Just remove that specific view from the layout inside your Panel/Page
  design in Pages section, and add it another time.

It will update the Drupal database and everything starts to work!


How to pass a Date as Contextual Filter? I have a custom content entity 'service' created with Drupal Console (drupal generate:entity:content). I added my own fields to the standard ones created by DC. Of which 'additiondate':

$fields['additiondate'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Addition Date'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))
  ->setReadOnly(TRUE);

Doing this way stores the date in YYYY-MM-DD string format.
I created an Embed View on this custom content entity to be used with views_embed_view().
I'd like to use Contextual Filter on the field 'additiondate' in order to have all the services that have been added SINCE the date passed as parameter.
The only way to pass a parameter seems to be '2018-04-26' and the result is all the services that have been added ON this date, as you can see in the Preview of my View with the generated request displayed:

Any idea?

Here is the screen capture of my options when I add the contextual filter:

Finally, I made it work.
I used mymodule_views_query_alter replacing the operator of the proper condition:

  if ($view->id() == 'services' && $view->current_display == 'embed_2') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'service.additiondate') {
          $condition['operator'] ='>=';
        }
      }
    }
  }


dump(), kint() & print_r() are not working in .theme file I've used drupal 8 with devel module. I want to change some values dynamically in views fields. So i tried to use theme_preprocess_views_view_fields(). When i tried to print variables using print_r(), kint() & dump(), no one print values.

/**
 * Implement theme_preprocess_views_view_fields().
 */
function galip_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  print_r($variables['fields']);exit;
}

I've enabled debug mode true in services.yml file. But i can't get any variables. How can i get variables?

Just include Kint debugger in your theme file:

require_once('modules/devel/kint/kint/Kint.class.php');

and use Kint like so:

Kint::dump( $_SERVER );


How to set page title for forum's Active and Unanswered tabs in Drupal 7? I have to set up forums in Drupal 7. I want to set page title, meta keywords and meta description for forum tabs like

  Active Forums and Unanswered Topics for forum.

How to do this?

I have solved my problem by setting custom page title in our theme's template.php file.

i have used bartic theme so in my function in template.php file is as follows

 function bartik_process_page(&$variables) {
    $path = $_GET['q'];
    if (strpos($path,'forum/active') !== false)
       {
        $variables['head_title'] =  drupal_set_title('Your_Page Title');
       }
   }

 function bartik_preprocess_html(&$variables) {
 global $theme_path;

// Add conditional CSS for IE7 and below.
  drupal_add_css($theme_path . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));

 $variables['head_title'] = implode(' | ', array(drupal_get_title(), variable_get('site_name'), variable_get('site_slogan')));
  }


Add sorting and filtering in code I need to add sorting to a view in code but can't seem to get this to work. This is my code so far.

$view = Views::getView('name_of_the_view');
if (!$view) {
  // some irrelevant code to handle a non existing view
}
$view->setDisplay('name_of_the_display');
$view->setArguments([$searchString]);
$view->setCurrentPage($page);

$view->execute();

As far as I know, I need to add $view->sort and $view->filter before the execute method but don't know what to set this to.

Do I have to pass the name of the sort/filter handler (i.e. 'random') or the class name (i.e. Drupal\views\Plugin\views\sort\Random) or an instance of a sort/filter handler or something else?

I was confused by $view->setExposedInput saying it accepts $filters as argument, but it actually works for sorting as well. So with that function you can set your exposed filters AND sorts

$view->setExposedInput([
  'your_filter' => $your_filter_value, //your exposed filter
  'sort_by' => 'your_field', //your exposed sort
  'sort_order' => 'ASC',
]);

Use above code before you execute view.

And make sure you exposed your filters and sorts in your view.


How to edit Advanced Search Form's Content Type checkbox-list using hook_form_alter I have a Drupal 7 setup. I want to remove few Content types from the Content Type checklist that appears in Advanced Search form. I could see that advanced search form comes in 'advanced' field-set of 'search_form'.

I tried to implement the solution given here, but I am not able to find the advanced array in $form.

I would also like to add styling changes and prefix elements to default text-fields that comes within Advanced Search form

Please find the below code that displays content of $form ($form_id = search_form), as I can't find advanced array within it.

    Array
(
    [#action] => /demodrupal7/search/node
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => search-form
                )

        )

    [module] => Array
        (
            [#type] => value
            [#value] => node
        )

    [basic] => Array
        (
            [#type] => container
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => container-inline
                        )

                )

            [keys] => Array
                (
                    [#type] => textfield
                    [#title] => Enter your keywords
                    [#default_value] =>
                    [#size] => 40
                    [#maxlength] => 255
                )

            [processed_keys] => Array
                (
                    [#type] => value
                    [#value] =>
                )

            [submit] => Array
                (
                    [#type] => submit
                    [#value] => Search
                )

        )

    [#form_id] => search_form
    [#type] => form
    [#build_id] => form-wAV_M_UAj5lbJgb-6vcdpmtxls5NpioPam6uNtkzRnw
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-wAV_M_UAj5lbJgb-6vcdpmtxls5NpioPam6uNtkzRnw
            [#id] => form-wAV_M_UAj5lbJgb-6vcdpmtxls5NpioPam6uNtkzRnw
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

        )

    [#token] => search_form
    [form_token] => Array
        (
            [#id] => edit-search-form-form-token
            [#type] => token
            [#default_value] => 374_q2sHn_uhIvUhwOdrriFMIM3UgfVoc7Jzsh_DHrE
            [#parents] => Array
                (
                    [0] => form_token
                )

        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => search_form
            [#id] => edit-search-form
            [#parents] => Array
                (
                    [0] => form_id
                )

        )

    [#id] => search-form
    [#method] => post
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#icon] =>
    [#icon_position] => before
    [#process] => Array
        (
            [0] => bootstrap_form_process
        )

    [#pre_render] => Array
        (
            [0] => bootstrap_pre_render
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
            [0] => search_form_validate
        )

    [#submit] => Array
        (
            [0] => search_form_submit
        )

    [#theme] => Array
        (
            [0] => search_form
        )

)

Can anyone help me with this.
Thanks in advance.

The advanced fields are added by the node.module in node_form_search_form_alter() (a hook_form_FORM_ID_alter() implementation). It sounds like your module's hook_form_alter() is getting called before the node.module one, so you're not seeing it's additions.

The ordering of when hooks are fired is controlled by the weight column in the system table. Have you altered that previously for your module? Usually, node.module has a weight of 0 so if your module comes before that in the rows in the system table when sorted by weight then that will be your problem.


Removing nodes using Feeds module I am using Feeds module (7.x-2.0-alpha8) to create nodes with CSV import.

Currently following patch Unpublish/Delete nodes not included in feed only provides the feature where if the entry is not there in the feed than delete the corresponding node.

However the above requirement doesn't seems to solve my problem. Following is my requirement

Under the CSV file I have one column called Delete, which stores Boolean value. If the entry has to be deleted than the value is 1 otherwise 0.

I wonder how it can be resolved. Any suggestions?

You could use a hook that checks for this field (which you'd have to add to the content type that you're importing into) then delete the node if its set to 1.  In order for this to work you would need to specify a field as unique otherwise feeds wouldn't know what item that already exists is to be deleted.


Location latitude longitude I am trying to update a website from Drupal 5 to 7 and I have to use location field for one of my content types. On Drupal 5, I can see the latitude and longitude fields but on drupal 7 I can not. Please check the image below.

In the Drupal 7 field settings for that location field, make sure you have enabled the longitude and latitude fields.

I believe there is also an option to "allow user to choose co-ordinates".


How can I featurise / store changes to a view provided by a module? In my case, Workbench and Workbench Moderation. Workbench Moderation gives me a "My Drafts" and "Needs review" view which I can edit to my taste, but I can't see a way of featurising the view or preserving my modifications in some way.

Is there an approach for this?

As far as I know, you cannot featurize a view that is provided by a module. What you can do is clone the view and featurize that.

I don't know about the Workbench modules specifically, but some modules allow you to choose which view is displayed via the UI. If they don't allow that, you will likely need to go in and modify the view call manually in a custom module.


Is there a way to pass many arguments and not have an ugly url? I'm writing a module that displays graphs based on a selection of arguments (an array with items to display, a daterange and some other stuff). This results in a long and ugly url.

Is there a way to get the arguments to the page with the graphs without putting everything in the url for that page? I'm looking for something that can keep temporary variables with a short reference that I can pass in the url, but haven't been able to find anything.

I'm using Drupal 7.

You could use form submission or cookies to store values, but neither of these are a particularity good ideas.

I would recommend (if you don't like the URL showing) using AJAX to retrieve/update the graph. You still have the ugly url but you hide it inside the ajax request.

So your module displays

/mypath

but the request could be

/mymodule/displaygraph/x/as/32432/s///


Put footer/signature on every blog post? I'd like to put a canned footer at the bottom of every blog post which has it's own content type.  My blog posts can have comments so I'd like the footer boiler plate to be at the end of the post content but before the "Add new comment" header.  I am NOT talking about a general footer for the entire site.  What's the drupal way to achieve this?

I see 3 pretty easy solutions :

(The easiest) You add a new field textarea to your blog content type. You configure its default value to the content you want (your blog footer content) which can be html (so you're free to type in whatever you want). Then configure the display of your blog post to have this field as the last one displayed. Done.
You can  add a entity_reference field (Entity reference module) to your blog content type. Then create a node which represent your footer, and use it as your default entity_reference field value for your blog content type. (Then you'll have to configure your display modes however you want it ...)
You can probably do this with a hook_form_alter() and insert your footer directly in the form

Hope it helps


Drupal Rule to Clear a Field But Still Retain Data? Need advice on fufilling this use case:

Use Case:

When User edits the node the first time, he populates Field A, a text area.  The data from Field A is eventually displayed on View A.

When User or other User returns to edit the same node, Field A is cleared for convenience, ready for new text input. (But the original data is still in the DB, and displayed in View A).

When the User saves the page this second time, the new data replaces the previous data in View A.

Plus: Eventually,  I also need to display the history of Field A in the application from all the saved edits.

Use hook_form_FORM_ID_alter() with FORM_ID = node_form.

Example:

function your_module_name_form_node_form_alter(&$form, $form_state) {
  $form['field_a']['#default_value'] = '';
}

For the second portion of your question, look into Node revisions.


Simpletest on select field loaded by ajax I have searched through Google and haven't found an answer. Stack Exchange is my last resort.
In my form, I have two select fields:
$form['system']['foo'] = array(
  ...
  '#type' => 'select',
  '#options' => array('A', 'B', 'C'),
  ...
  '#ajax' => array(
    'event' => 'change',
    ...
    'method' => 'replace',
  ),
);

$form['system']['bar'] = array(
  ...
  '#type' => 'select',
  '#options' => array(),
  '#prefix' => ...
  '#suffix' => ...
);

If user selects any of the options in foo field, the bar field dynamically loads the options through ajax. Example: If 'A' is selected on foo, bar field generates options like 'aaa', 'bbb', 'ccc' and can be selected by the user.
This form works and I need to provide its unit test using 'Simpletest'.
On my test case:
$edit = array(
  'system[foo]' => 1, // value for 'A'
  'system[bar]' => 2, // value for 'bbb'
);
$this->drupalPost('mymodule/mypath', $edit, t('Submit'));

gives an error saying system[bar] cannot be set to 2 (because it has no value of 2 yet?)
I need to emulate ajax call on system[foo] before setting system[bar].
I have tried drupalPostAjax:
$edit = array(
  'system[foo]' => 1, // value for A
);
$this->drupalPostAjax('mymodule/mypath', $edit, 'system[foo]');

and gives me a success result on ajax. On the next lines of code, I tried calling drupalPost() again using the previous code snippet but gives me the same error saying system[bar] cannot be set to 2.
How can I solve my problem? Please provide sample code as it can help me a lot..

EDIT:
Ajax works on the actual page (i.e the values are dynamically loaded to system['bar']). So I can assume my code in the forms is working.
However, I just noticed that ajax does not work on the generated page from Simpletest (the one found in sites/default/files/simpletest/verbose). Console from Google Chrome does not show any errors. Ajax returns status 200 but does not have any response.
I am using the default theme upon installation.

EDIT: The form and simpletest code
The form: I copied the form posted by znerol.
The simpletest code:
class MyModuleTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'Test Case name',
      'description' => 'Test Case Description',
      'group' => 'My Module',
    );
  }

  public function setUp() {
    // Enable module
    parent::setUp(array('mymodule'));

    // Get permissions
    $permissions = mymodule_get_permissions();
    // Permissions obtained correctly.

    // Create and login admin user
    $this->admin_user = $this->drupalCreateUser($permissions);
    $this->drupalLogin($this->admin_user);
  }

  // Test section
  public function testSystem() {
    $this->drupalGet('mymodule/mypath');
    $edit = array(
      'system[foo]' => 1, // Selects 'A'. Tested!
    );
    $this->drupalPostAjax(NULL, $edit, 'system[foo]');
    // Bar after ajax is loaded
    $edit = array(
      'system[bar]' => 1, // Selects 'aaa'
    );
    $this->drupalPost(NULL, $edit, t('Submit')); // Error here.
    $this->assertText(t('Submitted!'));
  }
}

However, when running simpletest, simpletest complains that system['bar'] cannot be set to 1 (aaa).
I have noticed simpletest shows the following warning before it calls ajax.

Undefined offset: 0 Notice drupal_web_test_case.php 2147 DrupalWebTestCase >drupalPostAJAX()
Undefined index: Notice drupal_web_test_case.php 2148 DrupalWebTestCase->drupalPostAJAX()
Undefined index: #ajax Notice ajax.inc 379 ajax_form_callback()

Since system['bar'] is loaded dynamically through ajax, it has an empty array initially array(). From the warning above, I tried adding a temporary option array('1', '2') in system['bar']. The same error and warning occurs.

You should set the $path parameter to NULL when submitting to the same form. Otherwise drupalPost / drupalPostAJAX will first retrieve the page again, and thus generating a new form instead of rebuilding the current one.

The following test should do what you want:

// First retrieve the page once
$this->drupalGet('mymodule/mypath');

// Set $path to NULL on subsequent requests to the same form
$edit = array('system[foo]' => 1);
$this->drupalPostAJAX(NULL, $edit, 'system[foo]');

$edit = array('system[bar]' => 2);
$this->drupalPost(NULL, $edit, t('Submit'));

The test case succeeds when performed on the following form:

function mymodule_myform($form, &$form_state) {
  $foo_options = array('A', 'B', 'C');
  $foo_default = isset($form_state['values']['system']['foo']) ? $form_state['values']['system']['foo'] : NULL;

  $form['system']['#tree'] = TRUE;

  $form['system']['foo'] = array(
    '#type' => 'select',
    '#options' => $foo_options,
    '#default_value' => $foo_default,
    '#ajax' => array(
      'callback' => 'mymodule_myform_ajax_callback',
      'wrapper' => 'bar-div',
      'method' => 'replace',
    ),
  );

  $bar_choices = array(
    0 => array('aaa', 'bbb', 'ccc'),
    1 => array('ddd', 'eee', 'fff'),
    2 => array('ggg', 'hhh', 'iii'),
  );
  $form['system']['bar'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'select',
    '#options' => isset($bar_choices[$foo_default]) ? $bar_choices[$foo_default] : array(),
  );

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

function mymodule_myform_ajax_callback($form, $form_state) {
  return $form['system']['bar'];
}


Routing custom module with alphabetic pagination My custom module:
- Plugin/Ziektes.php array returns to hook_theme

public function build() {

$letter_path = 'B';
$path = base_path();
$current_url = Url::fromRoute('<current>');
$current_path = $current_url->toString();

// Query for newest articles and return max 3 results.
$query = \Drupal::entityQuery('node');
$news = $query->condition('type', 'ziekte')
  ->condition('status', 1)
  ->condition('title', $letter_path, 'STARTS_WITH' )
  ->sort('created', 'ASC')
  ->execute();

// LoadMultiple News in $nodes variable
$nodes = Node::loadMultiple($news);

// Return $nodes variable with name items to the module.
return array(
  '#theme' => 'mytheme_ziektes',
  '#items' => $nodes,
  '#path'  => $path,
  '#url'   => $current_path,
);

I have an alphabetical pagination printedn in twig like this:

Below this pagination there are the results of nodes for example in the letter 'B' there are nodes from content-type 'ziektes' that starts with the letter B.

As you can see in my module Ziektes.php file its not dynamic it uses

$letter_path = 'B';
->condition('title', $letter_path, 'STARTS_WITH' ).

When there is clicked on a letter it goes to ziektes/'theletter' for example ziektes/b so that I can get the letter from the url and make the query dynamic.

But at page ziekte/*anyletter I get an 404 page not found so I've made a Controller and a routing:

Routing:

myroutingname.settings:
  path: '/ziektes/{letter}'
  defaults:
    _controller: '\Drupal\myblocksroute\Controller\ZiektesController::ziekte'
    _title: 'Routing Ziektes'
  requirements:
    _permission: 'access my routing ziektes'

Controller:

namespace Drupal\myblocksroute\Controller;

class ZiektesController
{
  public function ziekte($letter) {
    return [
      '#title' => $letter
    ];
  }
}

This returns the letter that is clicked, that's good! But Its only a new page with the as title the letter 'b' for example, I can't keep the twig template and the EntityQuery are not reachable from here. It suppose to stay at /ziektes form template but the url is /ziektes/b, so that the query will check the letter after the ziektes/ where I can make my $letter_path dynamic.

How can I do this?

As I alluded to in my comment, you are close, I believe. Here are some changes to get you in the right direction which begins by extending ControllerBase:

class ZiektesController extends ControllerBase
{

  // set any scope/variables here

  public function __construct($args...) {
    // set your injected dependencies to local variables
  }

  public static function create($args...) {
    // here you inject dependencies you need
  }

  public function ziekte($letter) {
    return array(
     '#theme' => 'mytheme_ziektes',
     '#items' => $this->queryNodes($letter),
     '#path'  => $path,
     '#url'   => $current_path,
    );
  }

  protected function queryNodes($letter) {
    // the following code can be refactored
    $letter_path = 'B';
    $path = base_path();
    $current_url = Url::fromRoute('<current>');
    $current_path = $current_url->toString();

    // Query for newest articles and return max 3 results.
    $query = \Drupal::entityQuery('node');
    $nodes = $query->condition('type', 'ziekte')
      ->condition('status', 1)
      ->condition('title', $letter_path, 'STARTS_WITH' )
      ->sort('created', 'ASC')
      ->execute();

    return count($nodes) ? $this->entityTypeManager->getStorage('node')->loadMultiple($nids) : array();
  }
}

ControllerBase should inject everything you need already, like entityTypeManager. That can be used to load nodes, as shown above. You don't need to call Node, and you likely don't have to do the same for Url either.

You can bring in your query as a helper method and you can inject entityQuery into your controller, see this comment on how to do that. That way, you're not using the global static container (\Drupal::). Then your code becomes:

    // Query for newest articles and return max 3 results.
    $query = $this->entityQuery->get('node');
    $nodes = $query->condition('type', 'ziekte')
      ->condition('status', 1)
      ->condition('title', $letter_path, 'STARTS_WITH' )
      ->sort('created', 'ASC')
      ->execute();

I am not sure why you need path and url though - every filter link will be routed to '/ziektes/{letter}'.


Adding jQuery plugin to Drupal Good day

I only have access to my Drupal site's admin panel, not the ftp server.
Now how can I upload a jQuery plugin, for example an image slider (with the js and css files) onto the site using the admin panel?
Note that the plugin is not part of the theme.

As I understand you need to add it on your theme's .info file:

scripts[] = js/my_jquery_plugin.js

BUT, is that file only accessible via ftp?

How can I do this using the admin panel?

Thank You

I don't think you can do it that way. You can always do it quick and dirty, depending on how it's written.

If it's your own code, wrap it in the following and throw it in a block:

(function ($) {
    // in this function, you can use the $ which refers to the jQuery object
}(jQuery));

Or you can try creating a generic file content type with a file attachment, upload the .js into the public directory, then make a new block with a PHP filter and use drupal_add_js() and load in that file.


How Much Time spent on websites of user In website have many AUTHENTICATED USER. I want to how many times spent of each user on site.

I use login history module, it show only every login time of all user.

I use time spent module, but not track all time of every page.

Please suggest how to calculate time spent of each user on every login.

Seems the Time Spent  module is what you're looking for

This module tracks, by Ajax, how long a registered user took to read a page and the amount of time he spent on the entire site.
You can configure which content type and role should be tracked and view the report, exhibiting the total hours (or minutes/seconds) a user spent reading a page and at the entire site.

Similar module -Time Tracker

Features

Track Time on any entity and or comments
Activities and Time Entries are now both fieldable entities.
Track time using time intervals (start and end times) or durations    (admin/settings/time_tracker)
Integrated Timer to track time as you go
Time estimating
User Time Sheets to display weekly logged time (user/%uid/time_sheet)
View for reporting on tracked time (time/report)


Change field value with hook_views_pre_render() I'm using Views in 8.4.0 and attempting to change the output of a field value with  hook_views_pre_render(). The default value of the field is a node ID. The intent is to replaced the value with a static string depending on a whether or not it's contained in a predefined array using in_array().

The aforementioned is relatively straightforward.

I begin by looping through the results:

  for ($i = 0; $i < count($view->result); $i++) {
    if (isset($view->result[$i]->node_field_data_node__field_lesson_nid)) {
      $viewed = in_array($view->result[$i]->node_field_data_node__field_lesson_nid, $viewed) ? 'yes' : 'no';
      // Replace the default Node ID value with $viewed.
      ...
    }
  }

The array $viewed contains a list of predefined node IDs. If the node ID exists in the array "yes" is output otherwise "no".

The problem is how to output the value for each row of results within the View object.

I tried the following at the above ellipsis:

      $view->field['nid_2']->options['alter']['text'] = $viewed;
      $view->field['nid_2']->options['alter']['alter_text'] = TRUE;

"nid_2" is the token for node_field_data_node__field_lesson_nid.

The problem is this changes the field value for every row. The last row in the results determines the value. (The View also has multiple joins (relationships) which further compounds the complexity.)

So my dilemma is where to replace the value within each row of the $view->result.

I was trying to do something similar as well. I had an integer field and I wanted to replace the integer column with a string value. That was not working. So I had to add a separate string field, maintained the integer field as a hidden field and then overwrote the string field. The code that worked is given below.

function module_views_pre_render(ViewExecutable $view) {
  // Change the comments column in the list of filings table in the view case
  if ($view->id() == 'my_view') {
    foreach ($view->result as $key => $value) {
      $custom_id = $value->_entity->get('custom_id')->value;
      $string = convert_id_to_string_get_user_name($custom_id);
      $value->_entity->set('string_field', $string);
    }
  }
}

There is documentation and sample snippets here but looks like it needs more documentation.

https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_pre_render/8.2.x


How to loop over fields from query? I am trying to create nodes from information extracted from a SQL query by using the following:

db_set_active('sage');
$query = db_query('SELECT CLIENT_ID, MASTER_CLIENT_ID, PARTICIPANT_ID FROM sage.CLIENT');
$result = $query->execute();
foreach($result as $record) {
  $node = new stdClass();
  $node->title = (string)$record->participant_id;
  $node->client_id = (string)$record->client_id;
  $node->master_client_id = (string)$record->master_client_id;
}

However, from my echo statements, I can see that my code never even enters the loop.

I had thought that execute() returns me an object of the query to loop over, but I guess I was wrong.

Could someone please tell me how I can loop over the results of my query and get the fields?

$result = $query->execute()->fetchAll();

should do the trick.

There's a lot more info and several more examples in http://api.drupal.org/api/examples/dbtng_example!dbtng_example.module/7


link field does not validate http:// I have link CCK field but the field does not validate "HTTP://" like this

how I can make the validate "HTTP://" for this field

In drupal 7, go to your content type in:

/admin/structure/types/manage/yourcontentype/fields/

Edit your field and check if it is validating your URL. I have attached a picture for better explanation.


Using third-party functions I have a third-party PHP script that I want to integrate and use in my site. The script is quite small and comes with its own functions and array indexes. How would I be able to call the functions and have them displayed in Views or CCK nodes?

If this is you own script, you could simply convert it into a module. That is easy, just create a module (tons of guides to be found in the internet) and put your functions in the .module file, then they will be available to all other code running on the site.

If this is a script/library provides by someone else, you could either place it in a custom module folder and include it with module_load_include() or (better!) declare it as a library with the help of the Libraries module. You will however need to create a custom module with some code to connect the functions of your script with drupal (Usually implementing the correct hooks and calling your functions from that) for both methods.

See also How do I go about putting standalone PHP files into Drupal 6? and How do I load a library defined with hook_library() on node/edit pages?.


Add html5 placeholders to node_add inputs I'd like to add placeholders to node_add field inputs. I'm trying to use dpm($form) but am not sure where to put it. I couldn't get node-add.tpl to work with this

 function MYTHEME_theme() {

  $items = array();

  $items['node_add'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'MYTHEME') . '/templates',
    'template' => 'node-add',
    'preprocess functions' => array(
      'MYTHEME_bootstrap_preprocess_node_add'
    ),
  );

  return $items;

}

The only template I got to work was page--node--add.tpl but $form shows a blank krumo.

To add placeholders, or any custom attributes, you need to dig deeper: implement appropriate hook_form_FORM_ID_alter. For node add/edit form, it will be mymodule_form_node_form_alter. First parameter is &$form - as you can see, it is taken by reference, so changes made to it are carried outside the function. Use dpm($form) to find appropriate element. Once you do, use #attributes to add attributes you want.