Why does view display incorrectly when logged out? I have a view with a page display configured. When I take a look at the page in the browser, while logged in, it displays correctly. When logged out, it's a mess: the fields are out of order, the sort order is wrong, the field settings are wrong...

I've built views with this approach dozens of times before and have never experienced this. In fact, I've even built a similar view-based page in the same site with no issues. Any idea what's happening here?!

I've flushed the caches. No role permission settings have been changed beyond the default.

Nevermind.

After walking away for an hour or so, coming back and then refreshing the page, everything is working. WTF? Does anyone know if this is a Drupal setting somewhere or is it an artifact of the somewhat locked-down instance of Drupal that I have to work with.

Grumble grumble.


How do autocomplete text fields work? I am asking this question because I have an autocomplete text field with #autocomplete_path set to a valid working path but key events are not handled by the misc/autocomplete.js file. When the form is being created, it apparently assigns all the functions to the respective variables, but none of those functions are executed. For example following function in the misc/autocomplete.js isn't executed.

Drupal.jsAC = function ($input, db) {
  var ac = this;
  this.input = $input[0];
  this.ariaLive = $('#' + this.input.id + '-autocomplete-aria-live');
  this.db = db;

  $input
    .keydown(function (event) { return ac.onkeydown(this, event); })
    .keyup(function (event) { ac.onkeyup(this, event); })
    .blur(function () { ac.hidePopup(); ac.db.cancel(); });

};

Hence, when a user types a letter, key up or key down handlers aren't invoked and nothing happens. So to debug, I want to know how autocomplete works.

Could someone please explain how this works?

Working with Drupal autocomplete form is good, instead of using the jQuery autocomplete.

Here we have a solution that how to create a custom autocomplete form and to get the user names or whatever.

I am giving the simple example of using it.

Take a menu item in hook_menu to get the autocomplete form. This will call the function called test_autocomplete_form.

$items['autocomplete_form'] = array(
        'title' => 'Test autocomplete form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('test_autocomplete_form'),
        'access arguments' => array('access test autocomplete'),
        'type' => MENU_NORMAL_ITEM
);

// Which will get the autocomplete form
function test_autocomplete_form(){
    $form = array();
    $form['testauto'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'test/autocomplete',
        '#description' => t('Please type any letter.'),
    );
    return $form;
}

We have to mention our custom path in for the #autocomplete_path attribute. Here I have given a path like test/autocomplete which will have to get the autocomplete result for that need to have one more menu item with the same path which we have given for the #autocomplete_path:

// menu item to get the autocomplete result,Which will call the function called 'test_autocomplete'
$items['test/autocomplete'] = array(
        'title' => 'Test autocomplete',
        'page callback' => 'test_autocomplete',
        'access arguments' => array('access test autocomplete'),
        'type' => MENU_CALLBACK
);

// function to get the autocomplete result, I am taking the user table to get the users names in the autocomplete field
    function test_autocomplete($string = '') {
      $matches = array();
      if ($string) {
        $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10); // only 10 results will show
        while ($user = db_fetch_object($result)) {
          $matches[$user->name] = check_plain($user->name);
        }
      }
      drupal_json_output($matches); // Returns the data in JSON format
    }


What argument to pass hook_update_n()? We have a custom module, mymodule, that we are using to create a custom block programmatically. We tried to do the following and it does enable the module successfully, but i get the following warning.

What is the argument that needs to be passed in?

  Missing argument 1 for mymodule_update_8501()

mymodule.install

function mymodule_install() {
  // Run update on install.
  mymodule_update_8501();
}

function mymodule_update_8501(&$sandbox) {
  // Do something.
}

A hook_update_N implementation is generally supposed to be invoked by the system, not manually.

Instead of thinking of it as "run an update on install", you could think of it as "perform an action on both install and update". A fairly common pattern for that is:

function MYMODULE_install() {
  _MYMODULE_install_something();
}

function MYMODULE_update_8501(&$sandbox) {
  _MYMODULE_install_something();
}

function _MYMODULE_install_something() {
  // Shared functionality here.
}

You don't have to use a global function; you could implement the shared functionality in a service and make use of that instead. The point is to separate out the logic for what needs to be done, and consume it in the same way wherever you need to.

If you do want to continue with your current approach, just pass it any initialised variable - doesn't matter what it is if you're not using it, and if your code is the only caller, it won't have any side-effects.


Add custom submission buttons to navigate through different wizard pages I need to navigate the user through different pages of a multistep webform. I have added additional submit button to the webform using following code.

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form_id == 'mywebform_id') {
    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );
    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
}
}

But now How could I navigate the user to the pages based on user clicks on which button?

I found this in community website. But not able to understand where should I put this code in my custom module.

How to programmatically skip pages in wizard forms

I used another more durty way. I just hide pages which must be skipped

function my_module_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id)
{
  if (!isset($form['#webform_id']) || $form['#webform_id'] != 'my_form') {
    return;
  }

  $pages = &$form_state->get('pages');

  if (some_statement) {
    $pages['skipped_page_name']['#access'] = FALSE;
  }
}

but it works only in forward direction. And if user clicks "previous page" it may cause unexpected behaviour. So you also need "show" pages again on each step:

$pages = &$form_state->get('pages');
foreach ($pages as &$page) {
  $page['#access'] = TRUE;
}


Table form with two checkbox columns I know it is fairly easy to create a table form with one column of checkboxes using table_select. But I would like to have two columns, preferably on the right of the text (as opposed to checkboxes in the left margin with table_select).

I looked at the code of the permissions table in core, but that one seems closely integrated with theming and I would like to avoid messing with that.

What would be the best way to achieve this? I'm using Drupal 7.

This does not seem possible.

However, I found that with tabledrag I could do what I wanted. Instead of having two checkboxes, I used the dragging option instead of one and left the other checkbox in the row you can select by dragging upward. This had the added benefit of being able to specify  the order for the items.

The simple table drag example was easy enough to follow and implement.


Sort nodes based on referenced node Im pretty new with advanced views and references module (Drupal 7). Im seeking for some help.

I would like to sort nodes based on node post date of the nodes that references it. So I have node type A and node type B that can reference node type A (A-one, B-many). I would like to sort type A nodes based on which has the latest Type B node.

Almost like journals that can have posts and I would like to see a list of the journals that have the newest posts.

Any idea how to approach this correctly, I seem to struggle and get some odd results.

Update:
I would like to sort the journals by the newest post in them. Right now it sorts by the first post in journal. Any idea how to set this? (obviously setting the sort criteria on the sort field to ascending doesnt work, because it will just flip the list of journals...)

You have B that references A (single value entity reference field).

Construct your view as follows:

View of content (nodes) filtered by type A

Relationship: Entity Reference: Referencing entity (A bridge to the Content entity that is referencing Content via YOUR_ENTITY_REFERENCE_FIELD.). ISSUE - are you making this required? If you do then some A's that are not referenced will not show up. If you leave it as not required then unreferenced nodes will show up in the list either first or last, depending on whether sort is ASC or DESC.

Sort Criteria: Content: Post date, and set the relationship to the relationship added.

And that is it. To test your view you might want to add the field: Post Date, and set the relationship to the relationship added. This will show the post date of the referencing node so you can easily see if it works or not.

You might also want to add a second sort criteria.


Passing variable from preprocess block to the block body There is a block which its body is produced by PHP Code. I need to set a variable before loading the block and use it in it. This is my code

function THEME_preprocess_block(&$variables){
    $variables['var']="some text";
}

when I open the block configuration page and in its body I write

<?php print $var;?>

it prints nothing. How do I can pass variable from block template page in to the block body in the block configuration page?

Your variable will be available in block.tpl.php. Consider making your own block like described on How to theme a custom block?. (You probably do not need hook_theme().)

Using PHP directly in blocks (via UI) is not the best practice: It slows your site down, as the block needs to be rendered with every request, when it comes to caching.


How does contextual menus work in Drupal 7? I've been trying to understand this for a while now, but I find the documentation either to lacking, or maybe I just don't understand what I'm looking for. Could anyone enlighten me on how to implement them?

One thing I'm trying to do is to be able to have contextual menus for each node in a list of nodes (loaded using node_load_multiple) that I'm sending along to a theme() function and looping through inside the .tpl.php

I'll put my temporary solution here for now anyway in case it will help someone.

What I did was just creating a new theme function (?) in my module

$themes['contextual'] = array(
    'template' => 'contextual',
    'variables' => array('links' => array(), 'destination' => null)
);

Then I defined my contextual.tpl.php

        <?php foreach($links as $url => $title): ?>

            <?php echo l($title, $url,
                array('query' => array('destination' => $destination))) ?>

        <?php endforeach; ?>

Finally, to use it, wherever there is a need for a contextual menu, add the class contextual-links-region to the container div of the node (or whatever), and inside the div I use my function, for example:

<?php echo theme('contextual', array('destination' => 'node/'.arg(1),
    'links' => array('node/'.$somenode->nid.'/edit', t('Edit node')))); ?>


Setting node title as view argument/path I'm creating a feed view that generates a specially-formatted file when nodes of a specific content type have /tsv appended to the path (generated by path_auto)

I.e.,

http://localhost/content/a-title/ --
node
http://localhost/content/a-title/tsv
-- feed view

How do I do this? I have node/%/tsv as the feed path, Node: Nid as argument (with "Node ID from URL" as the "Action to take if argument not present").

I feel there must be something really obvious I'm missing... Apologies if this has been covered before, I really did look for a solution before posting.

Thanks!

I'm not sure if I understood you question but I think the answer is:

In Arguments set Node: Nid as argument. Then set Provide Default argument and choose NODE ID from URL.

Here are all the steps.

You have 2 different views to your node.

Normal view. URL-> mydomain.com/node/%nid/ shows your node content
Feed view. URL -> mydomain.com/node/%nid/tsv shows your feed.

But when you navigate to mydomain.com/node/%nid/tsv it does not work right? So what you're asking is how you "create" this URL in order to show the feed... is that it?

If that's the case, in VIEWS2:

Create a new PAGE display.
In Page settings (bottom left corner) there's an option called PATH. Set this to node/%/tsv.
Still in Page Settings theres an option called menu. Set this to Menu Tab if you wish to show a tab linking to your view. | view  | TSV |
In Arguments set Node: Nid as argument. Then set Provide Default argument and choose NODE ID from URL.
Validation set Basic Validation (or Node Type if the Feed is only available to certain node types)
In fields, select the fields you wish to show.
Add a filter to node published (to show only if the node is published) and a filter user role (to limit access to certain users)

And that's it... when you navigate to mydomain.com/node/%nid/tsv it shows the fields you selected.


Can you change the view item output amount depending on user role? Is there a way to do this within one view/display or do I have to make two seperate displays, one showing field_images with unlimited item output and one display showing field_images but only showing max 2 images - depending on user role?!

I'd clone the view, the public one I'll name (temporarily) Public and change the access permission so anonymous users can view it.  The original one I'll name (again temporarily) Private and change the access to the authenticated user role.

Now you have two view displays, Public & Private.  Public display setting can be 2 and Private can be set to unlimited.


Entity forms bypass the access handler My entity defines an access control handler (a subclass of \Drupal\Core\Entity\AccessControlHandlerInterface) as well as a delete form (a subclass of \Drupal\Core\Entity\EntityConfirmFormBase).

The access handler designates certain entities as uneditable, and returns \Drupal\Core\Access\AccessResult::forbidden() on the "update" and "delete" operations for those entities.

This has the correct effect of hiding the "Edit" and "Delete" operation from the entity list.

Unfortunately, it doesn't do the same when visiting the forms directly via their URLs.

What am I doing wrong here? How do I actually block access to the forms?

Edit: The 404 was because I had the wrong URL for the edit form; turns out it's actually for all operations.

Do I need to call $this->entity->access($this->operation) myself in buildForm()?

In your delete route add _entity_access: yourentity.delete to the route requirements.

As Ivan pointed out in the comment, this is a matter of the route not automatically requiring entity access when it points at an entity form. The entity access requirement must be added to the route explicitly.


How to add multiple value using autocomplete widget We create a input field using user interface for add multiple languages .How i can add multiple language using comma separate so after comma they will populate other language.

You need to explode the string inside the autocomplete function.

function autocomplete_callback($string) {
  $explode_str = explode(',', $string);
  $last_str = drupal_strtolower(array_pop($explode_str));
  // use $last_str in the query
  $explode_str[] = $result;
  return implode($explode_str);
}


How can I make a link from content profile node to it's user account page? I'm trying to find out how to make a direct link from content profile node view/edit page to it's account page.

As an admin role when I check somebody's profile node I sometimes also  need to check his/her account. So it would be much easier if I can make a direct link.

I need this link to be visible only to Admin role. Is there any way to make it?

Quick and easy/dirty on the view page at least, in your node template for your content profile type, let's assume it is node-profile.tpl.php, you could add something like

<?php if (user_access('administer users') && $page): ?>
  <?php print l('User Account For This Profile', 'user/' . $node->uid);
<?php endif; ?>

wherever you wanted that link.  If you want it on the teasers of the node as well, eg, if the profiles are listed in a view or on the front page, etc, just take out the && $page otherwise this will only show up in the full node pages.  You can also pick any permission you want, I just grabbed the first one that made sense to me :)

ADDITION:  if you actually have a role called 'Admin' you can check for it like this:

 <?php
   global $user;
   if (in_array('Admin',array_values($user->roles)) && $page) {
      print l('User Account For This Profile', 'user/' . $node->uid);
   }
 ?>


How to ask drush to add timestamps to output? Some of the steps in our drush-make process take a while and having timestamps in the build-log would be useful -- for every line.

Is there a way to do this already, perhaps? The DRUSH_BACKEND pieces of JSON contain timestamps (seconds since Unix epoch), but they aren't shown for every step. Perhaps, there is something like a --timestamp flag in drush already?

It doesn't look this is possible. There is a list of available commands for drush make here: http://www.drushcommands.com/drush-7x/make/make


Upload Nodes with Image Fields I'm using jquery mobile and phonegap for a mobile app. I have uploaded an image file and received the fid but the subsequent request to create a node and attach the fid fails. The node is created although the image field is not filled in with the fid. Also the uploaded image in ../sites/default/files doesnot have dimensions(height and width).

Post the image:

var filedata = {
        "file":{
          "file":imageObj['base64s'][0],
          "filename":imageObj['names'][0],
          "filepath":"public://"+imageObj['names'][0],
          "mimeType":"image/"+imageObj['names'][0].split(".")[1],
          "filesize":  imageObj['sizes'][0]

        }
    };

$.ajax({
    url: localStorage.appurl+"/api/file.json",
    type: 'post',
    data: filedata,
    dataType: 'json',
    cache: false,
    headers: {
      'X-CSRF-Token': localStorage.usertoken
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.log('error '+errorThrown);
      d.reject(errorThrown);
    },
    success: function (data) {
      d.resolve(data);

    }
  });

Create the node:

$.ajax({
url: localStorage.appurl+"/api/node.json",
type: 'post',
data: "node[title]=new node&node[type]=ftritem&node[field_ftritem_images[und][0][fid]=7895",
dataType: 'json',
heders: {
  'X-CSRF-Token': localStorage.usertoken
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
  console.log('error '+errorThrown);

},
success: function (data) {
console.log("Node created");

}
});

Im getting this error:

Notice: Undefined offset: 0 in image_field_widget_form() (line 358 of /var/www/dt11/modules/image/image.field.inc).

Notice: Undefined offset: 0 in file_field_widget_form() (line 526 of /var/www/dt11/modules/file/file.field.inc).

Has anyone faced this before ? Any suggestions are highly appreaciated.

There is a problem in Drupal core. I made an issue for it here and a patch has been supplied, but it didn't work properly for me: https://www.drupal.org/node/1912458

I did get it to work by only doing part of what the patch does.

Find line 504 of modules/file/file.field.inc and change it from this:

if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {

To this:

if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality'])) {

I don't know if this produces adverse side effects anywhere else, but it does allow services to be used in the way you are using it.


How to remove field from form and configuration? We have a custom module, mymodule that has a form, mymoduleForm with two fields: enabled content types and urls.

We no longer need the enabled content types field on the form and want to remove it from the form and configuration. We do not have either config/install/mymodule.settings.yml and config/schema/mymodule.schema.yml files.

How can we remove the field (enabled content types) from both the form and configuration?

mymoduleForm.php (all lines below we are thinking need to be removed related to enabled_content_types)

public function buildForm(array $form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');

  $types = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->loadMultiple();

  foreach($types as $type) {
    $content_types[$type->id()] = $type->label();
  }

  $form['enabled_content_types'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Enabled Content Types'),
    '#description' => $this->t('content types .'),
    '#default_value' => $config->get('enabled_content_types'),
    '#options' => $content_types,
  ];

  ...

  return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');
  $mymodule_config
    ->set('enabled_content_types', $form_state->getValue('enabled_content_types'))
    ->set('urls', $form_state->getValue('urls'))
    ->save();

  parent::submitForm($form, $form_state);
}

change this line

->set('enabled_content_types', $form_state->getValue('enabled_content_types'))

to

->clear('enabled_content_types')

In Drupal, go to config form and click save.

Side Note: Alternatively, you could also delete the config via Drupal Console or Drush as mentioned in the answers here, How do I remove a configuration object from the active configuration?

Now you may now remove the relevant code.

public function buildForm(array $form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');

  $types = \Drupal::entityTypeManager() // remove
    ->getStorage('node_type') // remove
    ->loadMultiple(); // remove

  foreach($types as $type) { // remove
    $content_types[$type->id()] = $type->label(); // remove
  } // remove

  $form['enabled_content_types'] = [ // remove
    '#type' => 'checkboxes', // remove
    '#title' => $this->t('Enabled Content Types'), // remove
    '#description' => $this->t('content types .'), // remove
    '#default_value' => $config->get('enabled_content_types'), // remove
    '#options' => $content_types, // remove
  ]; // remove

  ...

  return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');
    ->clear('enabled_content_types') // remove
    ->set('urls', $form_state->getValue('urls'))
    ->save();
  parent::submitForm($form, $form_state);
}


What is the Drupal API for reading Drupal configuration files (.info .make etc.)? Drupal configurations such as .info, .make appear to follow common structure. There must be Drupal API for reading these configurations from code.

How does one load and read these configurations in his code?

You want drupal_parse_info_format.

  Data should be in an .ini-like format to specify values. White-space
  generally doesn't matter, except inside values.

  key = value
  key = "value"
  key = 'value'
  key = "multi-line
  value"
  key = 'multi-line
  value'
  key
  =
  'value'

  Arrays are created using a HTTP GET alike syntax:

  key[] = "numeric array"
  key[index] = "associative array"
  key[index][] = "nested numeric array"
  key[index][index] = "nested associative array"

  PHP constants are substituted in, but only when used as the entire
  value. Comments should start with a semi-colon at the beginning of a
  line.

I actually know this because the Profiler module uses it to parse out its .info file for profile configurations.


Static field works, dynamically modified element gets lost I'm new to Drupal forms - trying to figure out a maddening problem.

I have a content type of 'doc-upload' with various fields including 'publisher_code'.

When I define the 'publisher_code' field type to 'text', and go through my upload process, yada yada yada, the value appears in my $node structure later as expected.

When I change 'publisher_code' to "field type: List (text), widget: Select list", and I try to dynamically populate that element with:

function mymodule_form_doc_upload_node_form_alter(&$form, &$form_state) {

  $publishers = array( 'pub1' => 'Publisher 1', 'pub2' => 'Publisher 2' );

  $form['field_publisher_code'] = array(
    '#title' => t('Select a publisher'),
    '#type' => 'select',
    '#options' => $publishers,
    '#multiple' => FALSE,
    '#empty_value' => '',
    '#empty_option' => '- None -',
    '#required' => TRUE
  );
}

The form displays properly, but when the form is submitted, the 'field_publisher_code' doesn't come out the other side - presumably it's getting filtered/invalidated somewhere, but I can't seem to find where?

instead of over writing the form element just edit variables you want to change something like below

  $publishers = array( 'pub1' => 'Publisher 1', 'pub2' => 'Publisher 2' );

  $form['field_publisher_code']['#type'] = 'select';
  $form['field_publisher_code']['#options'] = $publishers;
  $form['field_publisher_code']['#multiple'] = FALSE;

I presume your $form already has the variable when you get the form.


getting individual field values I'm trying to fetch each individual field of an items array. here is the image of the kint result

here is what i have tried.

{{items[0].content}} -- this one prints the whole thing in the items array.
{{items[0].content['#context'].value}} ---- does nothing
{{items[0].content['#markup'].getValue()}} ---  does nothing

Have looked for documentation, couldn't find one. Any explanation or url to documentation or example will be appreciated.

Try with items[0]['content'] or if its field of type text you will find the value of the text with items[0]['content']['#text'] or items[0]['content']['#value']


How to use 'if Token is' I would like to use an if statement depending on my token something like

<?php if ([simplenews-category:name] == 'fishing'): ?>
 Go fishing   <?php else: ?>
 Go sailing    <?php endif ?>

Above code doesn't work, can somebody please give me advice?

I'm using Drupal 7

You need to replace the token first with it's actual value.  You can do this with token_replace();

I haven't used simplenews yet, but you will need to do something along the lines of:

<?php if (token_replace('[simplenews-category:name]', array('node' => $node)) == 'fishing'): ?>
 Go fishing   <?php else: ?>
 Go sailing    <?php endif ?>

Once [simplenews-category:name] has been converted, string comparisons should work as intended.

As a note, you will likely need something other than array('node' => $node) to get this to function.


Creating secondary menus, that are different based on the page being viewed I'm new to Drupal development so bear with me.  I'm attempting to copy a production site that has used old school page controller organization into a newly setup Drupal 7 install.  I've set up the header, sidebar, and footer all of which will always be the same so I've created them as blocks.

The content within those blocks is categorized into 5 categories and each one uses a slightly different layout at the top and bottom.  What is the best way of handling this situation?

Create multiple additional blocks and make sure to assign the appropriate pages to those blocks, or set up a template of sorts that can tell what blocks need to be displayed based on the category of the content.

If you want to have different layout on different pages you can use power combo Omega + Context + Delta.
Using this modules you can create different layouts, different menu items and other things on different pages without codding.

See tutorial and Theory


Is it possible to replace html outside form with ajax? Is it possible to replace a <div> outside form with ajax on select element?

I am having some difficulties, when Drupal generates new content it wraps my HTML with <div> and I don't know why.

This is my form element.

$form['select_element'] = array(
'#type' => 'select',
'#title' => t(''),
'#options' => array(1 => 'Test 1', 2 => 'Test 2'),
'#ajax' => array(
  'callback' => 'ajax_callback',
  ),
);

This is my callback function.

$output = theme('custom_theme_function', array('test_param' => 11,));
$commands[] = ajax_command_replace("#div-id", $output);
return array('#type' => 'ajax', '#commands' => $commands);

This due to this part of ajax.js

// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly iterpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('

').replaceWith(response.data).
var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

// For legacy reasons, the effects processing code assumes that new_content
// consists of a single top-level element. Also, it has not been
// sufficiently tested whether attachBehaviors() can be successfully called
// with a context object that includes top-level text nodes. However, to
// give developers full control of the HTML appearing in the page, and to
// enable Ajax content to be inserted in places where DIV elements are not
// allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
// content satisfies the requirement of a single top-level element, and
// only use the container DIV created above when it doesn't. For more
// information, please see http://drupal.org/node/736066.
if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
  new_content = new_content_wrapped;
}

This ensures that text nodes are not lost when replacing contents. The second parts of the script checks if the data sent is a single top-level HTML node, and if not, wraps it in a

Back to your problem, the solution is to make sure that theme('custom_theme_function', array('test_param' => 11,)) returns your content in a single HTML node (div, span, ul, li... as long as it is single)


How to set the default value of an entity reference to an entityform type I'm using the module EntityForm to create a couple of different forms.

Each form should be attached to a different content type as an entity reference field.

I can create an entity reference field that shows a select list of "EntityForm Type" from which the user can choose when creating content.
I would like to set a default value however (and will hide the field so it can't be changed), since there shouldn't be choice as it's always the same kind of form that needs to be attached.

I know this is possible with nodes by loading a specific node, but in this case they're entityform types and not nodes.

I've found a way, but it might not be the best way. I remove all the other options from the select list so the one I want is the only one left. (What is strange, is that in some content types I can set a default value for the entity reference and in some I cannot, but this worked anyway)

if ($form_id == 'inschrijvingsformulier_testdag_p_node_form'){

    $form['field_inschrijvingsformulier_tes']['und']['#options']=array(1 => 'inschrijvingsformulier testdag',);
    $form['field_inschrijvingsformulier_tes']["#attributes"]['class'][] = 'element-invisible';
}


How to remove and add joins to a view? Because of some buggy handlers I need to write a hook that will:

Get location_instance table's alias from the original query
Remove location_instance table join
Remove that alias join
Remove a location table join
Add 2 new joins

Apparently views does things a little differently so I can't just $query->join() my way to freedom. How exactly do I accomplish the above?

This is an issue I have been sturggling with myself.  You may want to start by looking at hook_views_query_alter() and read this related Drupal Answers question.

Then you can use these functions: views_plugin_query_default to actually affect change on your query.


How can override the title markup on a node page? I've managed to implement a custom page template but it still uses the default title markup.

I'm trying to find out how to replace the markup around the title so I can change it to something like:

Node title

Subtitle

Can I override a template like region--header.tpl.php or something similar?

I'm using an omega based custom theme too btw.

As expected as soon as I posted this question I found the solution..

If you use the template region--main-heading.tpl.php you can override title markup.


Radios button in form arrays How can i check which radio button has been checked from a list of radio buttons ? Is there any key in the form array which holds the checked radio ?

I am using an ajax call for a bunch of radios buttons and i would like to do some "checking"  only if the right radio button was selected.

As an alternative , how can i append the "#ajax" parameter to only one radio button in a list of radio buttons ?

You can check the element's value in $form_state['values']. Add the full parameter list ($form, &$form_state) to the form builder function.

For example:
function mymodule_something_form($form, &$form_state) {


Attempt to charge recurring fee 2 failed Attempt to charge recurring fee 2 failed.I am getting this error when i want to charge via developer a/c authorize.net. Normal payments going well but recurring is the porblem..Any idea to fix this error..D7 i am trying.....

Authorize.net renewals cannot be tested while your authorize.net account is in "Test Mode". I have tested and confirmed this. It will work if you set the account to live mode.

You can see the relevant discussion here: http://drupal.org/node/812922


How do I delete all book page nodes, book outline, and uninstall book module I would like to remove a book, its contents, its outline, and uninstall the book module itself.
I deleted all the "Book page" content type nodes. I then deleted the one book listed under:
admin/structure/book
However, when I try and uninstall the module using Drush I get the message:
"To uninstall Book, delete all content that is part of a book"
I'm assuming this is the outline data on non "Book page" nodes that I missed, but there's nothing there in the Admin UI to tell me which ones they are. The UI says "No books available."
There is a module that addresses the issue of deleting book pages and their outlines in this answer here in Drupal 7.
Is there a way to easily find and delete that book content and uninstall the module in Drupal 8?

It sounds like you have orphaned book content. You can go look for any nodes of type book page at /admin/content, and delete them all. Also, check your configuration of the book module to see if any other content types are enabled as book content. You may have to determine which nodes of those content types have been created as book pages but not assigned to an outline.


Change the Drupal Commerce checkout completion page How do I redirect the final checkout page of my Drupal Commerce install (from checkout/%/complete) to the actual order created (user/%/order/%)?

This seems easier than having to build and theme the line items in the completion message pane, not to mention I have inserted other information to the order display.

I used the Rules module to redirect on checkout completion event, and this seems to be working so far.


Term reference field: Checkboxes with add new textfield I need to change the presentation of a Term reference field. Drupal 7 has 3 widget types:

Select list
Check boxes/Radio buttons
Autocomplete term widget

I need to display check boxes to select 1 or many terms when adding a node, but I also need to display a textfield to allow adding new term.

The autocomplete term widget allows to choose existing terms and add new ones, which is the functionality I need, but what I exactly need is a list of checkboxes with the existing terms and the textfield below that allows adding a new term.

I've searched modules, but I can't find one that allows me to do this. Is there a module that performs this? If not, how do I do this in code? Is there any way to customize the widgets to create that functionality? Thanks.

http://drupal.org/node/1208512#comment-5605324

It has been adapted from Select or other to support taxonomy term references.

It is a non-contrib module and you may need to tweak it to your taste, especially as it adds Other: to the term you have added. I just tried it out and that part needs to be fixed, but it shouldn't be difficult.


Show all content related to child taxonomy terms in parent I don't think I could explain it any better here then I have in the title.

Basically if I have a taxonomy term call Parent and it has sub terms called Child 1 and Child 2. I'd like to be able to see any content related to Parent's sub terms (Child 1 & Child 2) appear on the Parent taxonomy page.

Thanks in advanced!

Looking around I have found the solution that helps me. It's a module called Hierarchical Select.


Menu is not creating in admin/settings page? I am adding a custom module, and wants when someone install the module, menu will be added to add data in the admin/settings page...
But i am getting nothing:

Below is the code i wrote.. pricepackages is the module name i want to created

please help me ..

function pricepackages_menu()
{
    $items = array();
    $items[] = array(
        'path' => 'admin/settings/favorites/quotes',
        'title' => t('Manage Quotes'),
        //'page callback' => 'drupal_get_form',
        //'page arguments' => array('poke_test_form'),
        'callback' => 'drupal_get_form',
        'callback arguments' => 'pricepackages_settings',
        //'access callback' => 'poke_access_callback',
        'access' => user_access('Access administration pages'),
    );
}

Settings hook is like this:

function pricepackages_settings()
{
    //$form['#submit'][] = 'poke_test_submit';
    $form['quote_manage'] = array(
        '#title' => t('Select User'),
        '#type' => 'textfield',
    );
    return $form;
}

function pricepackages_menu()
{
    $items = array();
    $items['admin/settings/favorites-quotes'] = array(
        'title' => t('Manage Quotes'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_settings'),
        //'access callback' => TRUE,
        'access arguments' => array('access administration pages'),
    );
}


Translate was disallowed for HTML input in a view- how to enable? I have created a custom field in view and I want to translate it but the Drupal prevent me,
It shows this error

How I can resolve this problem?
I used Drupal 7.7

By default, Filtered HTML and Full HTML are not available for translation.  You can override this by enabling the i18n module and visiting:

/admin/config/regional/i18n/strings (on Drupal 7)
admin/settings/language/configure/strings (on Drupal 6)

Just check the boxes for the text formats which you wish to enable.

Depending on your situation, you may also need to enable the i18n Views module.


How to redirect /user to /user/UID, for logged in users? I run a social movement community site, which features links to the '/user' page, which either shows people the login/registration page, or shows them their user account if they're logged in. If people are logged in, how can I make these links to /user redirect to /user/UID ? (E.g. if I'm the one logged in, I'd like to redirect my visits to http://effectivealtruismhub.com/user to http://effectivealtruismhub.com/user/1 - currently it shows me my user page, but just shows http://effectivealtruismhub.com/user in the address bar.)

This is a valuable feature because people benefit from seeing the URL of their user page, as on this community site and others they'll want to share it with people.

If you were handcoding this, you would create a menu path using hook_menu, with %uid as the second parameter. And the page_callback value of the menu item would be the function rendering the user page. You will then use hook_user_login to set the redirect rule.

If you were doing this using contrib modules, I suggest you looking into profile2, it comes with a built in functionality where each user has their own profile page.

edited:
The last sentence on your question, makes me led to think that the user/%uid path needs to be accessible users/visitors other than the owner. So let's here is how you would do it.

Create your custom module, let's call it ea_custom for the sake of
this example.
Add hook_menu and page_callback to your ea_custom.module and register the path for the individual user page.

/* Implements hook_menu */
function ea_custom_menu() {
  $items['users/%user'] = array( //the %user will be used as argument for the page callback
    'title' => t('User Profile'),
    'page callback' => 'ea_custom_render_userpage',
    'page arguments' => array(1), //zero base array. This tells hook menu to first load user with the specified uid specified by %user parameter.
    'access callback' => 'user_access', //so non-onwer can also view it
    'access arguments' => array('access content'),
  );
  return $items;
}

/**** page callback for users/%user ****/
function ea_custom_render_userpage($user) {
   //you now have accessed to the user object
   drupal_set_message('' . print_r($user, TRUE) . '');

//assemble your output using the values inside $user object
   $output = $user->uid; //etc.. etc...

return $output;
}

Additional notes: you can use different methods to get values from entity objects such as user and node. I would recommend you to check entity_metadata_wrapper for one. Also, instead of using %user, to get user object, you could opt to use %profile2, since you have that module installed, and it will allows you access to fields you have attached to profile type.

wow, I can't seem to format this properly. Here is the paste bin: http://pastebin.com/kiv6GfPN


Let Users Make a Feedback before Download File I want to let users fill a form feedback about the node before downloading the file that attached to that node! like in Dialog or Popup, which modules should I use here?

Depending on your Drupal coding skills I would use a custom form with a modal using the OpenModalDialogCommand. In the modal you can attach a form with a textarea and a submit button. On clicking the submit button the feedback from the textarea gets stored, the modal gets closed (CloseModalDialogCommand) and a BinaryFileResponse gets returned.

I don't know of any contributed modules that provide this functionality.

P.S. I am assuming that you are using Drupal 8 here.


What does the project: key in module.info.yml do? Note: this is not the book module from core.

I inherited a custom module that was not written by me. Its .info.yml contains a project: key which I have never seen ever before.

ps_book.info.yml

name: Book
type: module
description: Provides lesson page structure
package: Pivotal Science
dependencies:

version: '8.x-1.0'
core: '8.x'
project: 'ps_book'

I noticed that when I install the module I get 3 errors in the log.

I did a mouseover, so you can read the full error. The other two are the same except they end in es.po. and fr.po.

In Let Drupal 8 know about your module with an .info.yml file I couldn't find any mention of the project: key.

If I remove the project: 'ps_book' line, I no longer get those 3 errors when I install the module.

Is there any official doc for this key? If not, should someone add it the docs?

The Drupal 8 documentation for the keys to use in a .info.yml file doesn't mention it, but that is the same key documented in Writing module .info files (Drupal 7.x).

  project (Discouraged, packaging use only)

  Module maintainers should not use this at all. The packaging script on drupal.org will automatically place a string here to identify what project the module came from. This is primarily for the Update status module, so that Drupal installations can monitor versions of installed packages and notify administrators when new versions are available.

Drupal uses its value for building URLs when finding information about the module, or any file related to it. Technically, every Drupal core module could use the value of the project key to build a URL for something related to a module. I take the documentation gives the primary use of that key, since the Update module is present in all the last versions of Drupal.

I guess that, since its usage is discouraged, they don't document it for Drupal 8 to avoid users add it in their .info.yml files. It could help users creating a module that handles new keys in .info.yml files, though.
As for documenting it, I would document it just to avoid a developer creates a module that handles custom keys that conflict with the ones already used from Drupal core. I can understand this is seen as a use case that remotely interest developers, though.


How to set the price without decimals? in my store, I want to set the products price without decimals,
e.g. "$500.00" ==> "$500"
I put following codes in the template.php:

function roomify_travel_commerce_currency_info_alter(&$currencies){
  $currencies['TWD']['format_callback'] = 'roomify_travel_commerce_currency_format';
}

function roomify_travel_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

    return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}

then the price became correct, but my admin page was broke!
and apache error log showed:

[Thu Feb 09 07:20:41.168665 2017] [proxy_fcgi:error] [pid 25564:tid 139845024192256] [client **.**.**.**:40368] AH01071: Got error 'PHP message: PHP Fatal error:  Call to undefined function mytheme_currency_format() in /opt/bitnami/apps/drupal/htdocs/profiles/roomify/modules/contrib/commerce/commerce.module on line 641\n', referer: http://**.**.**.**/drupal/?q=admin

please tell me where I went wrong! thank you!!

Your callback function is in your theme's template.php file, which is only loaded when that theme is being used.

I'm assuming your admin backend uses a different theme, so it can't find your callback function on admin pages.

The best solution would be to move the logic into a custom module; it's not theme related functionality so best practice would be to move it there anyway, even if it wasn't causing a problem.


Don't repeat yourself: Natural place for clculations on the FieldItemList of a custom FieldType wanted I have a custom field type that contains a number field, among others.

class MyFieldItem extends FieldItemBase {
    public static function propertyDefinitions($field_definition) {
        $properties = [];
        $properties['some_number'] = DataReferenceTargetDefinition::create(
            'integer'
        );
        ...
    }
    ...
}

I need the sum of all values of the property some_number. A function adding the numbers would look like this:

function addAllNumbers($items) {
    $sum = 0;
    foreach ($items as $item) {
        $sum += $item->get('some_number')->getValue();
    }
    return $sum;
}

I need this sum for many purposes, like to display it in the formatter, or to validate forms.

Now, I've found that I'm calculating this sum in several places in my code. But an important programming principle tells me: "Don't repeat yourself!"

Where is a natural place to perform calculations on the FieldItemList of a custom FieldType?

I see several candidates for such a place.

The .module file. However, this is hardly connected to the custom FieldType and often a confusing collection of random things.
The MyFieldItem class defining the custom FieldType. Here, the iteration would go over $this->parents. However, I don't see a way to access the FieldType object from within the Formatter.
The formatter. However, then it would be necessary to somehow format the FieldItemList during the form validation.
Some utility class. But probably, other developers would find that strange in the future.

  There should be one-- and preferably only one --obvious way to do it.
  (The Zen of Python, by Tim Peters)

The natural place would be a method in a custom field item list:

class MyFieldItemList extends FieldItemList {

  public function addAllNumbers() {
    $sum = 0;
    foreach ($this->list as $item) {
      $sum += $item->some_number;
    }
    return $sum;
  }

}

Set the list class in the field type:

 * @FieldType(
 *   ...
 *   list_class = "\Drupal\mymodule\MyFieldItemList",


Having trouble printing my theme from a custom module I created a custom tpl.php page with some basic HTML:

TEST

And a module file that defines the theme:

function my_module_test_theme($existing, $type, $theme, $path) {
    $items = array();

    //Test
    $items['test_test'] = array(
        'template' => 'test-test',
        'path' => drupal_get_path('module', 'my_module') . '/templates',
    );

    return $items;
}

But when I try to print it out in my theme it doesn't work:

<?php $output = theme('test_test'); ?>

Am I printing out the theme in my site's theme's page.tpl.php incorrectly?


Drupal Views: How to remove 1 item if it matches the Node TItle I'm trying to remove one item from a block view if the CCK node title of that item matches the node title of the page it is appearing on.  Can someone tell me how I would achieve this?
Thank you!

It's better and easier to match by Node ID. To do that, add a "Node: NID" argument (or a 'contextual filter' in newer Views versions) to your view, set it to "Provide default argument", choose "Node ID from URL" as default argument type and check the "Exclude the argument" box. That should do the trick.


Error in validation of managed_file field with Form API To begin I worked with this solution but a wild error appear: Image Upload in a Custom Module

Here is my code :

function module_top_content_equipe_admin_form(){
  $default = get_variable_value(variable_get('module_top_content_equipe_display', ''));
  $default_image = variable_get('module_top_content_equipe_image', '');
  $form['module_top_content_equipe_display'] = array(
    '#type' => 'text_format',
    '#name' => 'module_top_content_equipe_display',
    '#title' => t('Content of the block'),
    '#description' => t("Text to display"),
    '#format' => 'filtered_html',
    '#default_value' => $default,
  );
  $form['module_top_content_equipe_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'module_top_content_equipe_image',
    '#title' => t('Top Content page l equipe Image'),
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#default_value' => $default_image,
    '#upload_location' => 'public://',
  );
  return system_settings_form($form);
}

function module_top_content_equipe_admin_form_submit($form, &$form_state){
  if (isset($form_state['values']['module_top_content_equipe_image'])) {
    $file = file_load($form_state['values']['module_top_content_equipe_image']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}

and my error when I submit the form

  Fatal error: Cannot unset string offsets in /includes/form.inc on line
  2157

Thank you with advance

There's a bug in the way system_settings_form() handles managed_file types. It's to do with the upload/remove buttons and parent elements (if you read the whole issue you hould get a good take on what's going on).

I don't know if it's the same error as I was having, but adding code like the following to the top of the form's submit handler fixed it for me:

foreach($form_state['buttons'] as $delta => &$button) {
  if (preg_match('/module_top_content_equipe_image_(upload|remove)_button/i', $button['#name'])) {
      $button['#parents'] = array();
    }
  }

Not ideal by any means, but it does work.

On another note, the #process property attached to the managed_file item is unnecessary. That code should be run in the form's submit handler, and since your submit handler is named in the right convention it will be run when the form is submitted, which is when you need it to.

Try removing the #process line altogether and see what happens.


What am I doing wrong in my theme that's breaking CAPTCHA? I have a bug in my CAPTCHA implementation. When I click the "Get new captcha!" link, it does not refresh the image CAPTCHA.
After a ton of research in issue queues, testing and breaking my local, and finding everything that was NOT causing it I finally turned off my custom theme and lo, the "Get new captcha!" link works again.
My custom theme is built on USWDS Base theme.

not using a CDN

I'm using:

Drupal 9.0.11
CAPTCHA and Image CAPTCHA 8.x-1.1
USWDS Base Theme 8.x-2-4

No errors are produced in the log or in the console. I "feel" like it might be something related Ajax, but I can't figure out how to sniff it out or narrow it down.
Can anyone give me suggestions for settings I can test and change or specific places in code I might check to try to fix this? Thank you.
Update: I just tried using straight USWDS Base theme, no custom theme, and CAPTCHA bug is still there. So not my custom theme, but my contrib base theme.

I found the conflicting template inside USWDS base theme. For anyone else having this problem, you must alter this template:
/themes/contrib/uswds_base/templates/form/details.html.twig

You can either wholesale replace with the same template from Bartik's classy template (or similar), or else custom rewrite it using the working template from Bartik and customizing it to what you need. I needed to rip out the ul/li based markup that USWDS imposed, but still keep the classes and accessibility markup.
In case it helps anyone else, here's what I ended up using:

  {%- if title -%}
    {%
      set summary_classes = [
        required ? 'js-form-required',
        required ? 'form-required',
      'usa-accordion__button',
      ]
    %}

    <button type="button" aria-expanded="true" aria-controls="{{ attributes.id }}-content"{{ summary_attributes.addClass(summary_classes) }}>{{ title }}</button>
  {%- endif -%}

    {% if errors %}

        {{ errors }}

    {% endif %}
    {%- if description -%}

{{ description }}

    {%- endif -%}
    {%- if children -%}
      {{ children }}
    {%- endif -%}
    {%- if value -%}
      {{ value }}
    {%- endif -%}


How to edit fields' values in the hook_node_load function? In the hook_node_load function I want to alter a field's value.
I printed the node variable and got the following structure for the field:

    [field_myfield] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1316760775
                        )

                )

        )

So I should write something like $node->field_myfield[und][0]['value'] = 'sth'. My site has 2 available languages, and [und] will be changed when language is changed.
How can I alter the field value for all languages?

I'd go with entity_metadata_wrapper(), see this blog post for more info on that.

$node = node_load(323);
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->title = 'New title for the node';
$wrapper->save();

It works for any property: title, fields, author, etc.


"View" with article shown according to detection/selection language I would like to create a View (using the View module) to show my translated article separately according to the url path. Doing so, going to www.mysite.com/fr/blog should only show my article with the term "story" in french and going to www.mysite.com/en/blog should only show my article with the same term "story" in english.

I added an Entity translation relationship
I added an entity translation "language" set as "current user's language"

But none of my article are displayed on the views whatever the language path I use.

Here is my Views configuration:

Many thanks for your help!

When 'FR' detected on Url default language of website will be changed So you have to Set it to  Default Site Language


Proper way to package translation files with a custom module? I have a custom module. In this module all strings are in English. However, my website is in French and when installing the custom module, I'd like the French strings to be picked up and imported automatically.

What's the best way to generate and then package the .fr.po translation file with my custom module?

(With D7, I would use potx to generate the .po file for my module, then I'd put the file under sites/all/modules/custom/MYMODULE/translations. But potx no longer exists for D8 and the d.org documentation isn't very helpful.)

potx itself isn't directly available as a Drupal 8 module, but it doesn't need to.

It also works as a drush extension and can be run on Drupal 8 code. Haven't tried it if providing a translations folder still works, but I think so.

So, still works pretty much the same as in Drupal 7.


Is it possible to have common content for several users? For example, sometimes there is a situation when several project's users need to work with common content not using one account for them.
That is, each member of the group has his own account with his login and password. But they need to have possibility edit and delete data inputed by other member of the group before.
Are there any solutions which can realize it ? And it is desirable to the solution wouldn't be the Organic Groups module or based on creating of a lot of roles.
And if there isn't the solution, how, by you opinion, is the best way to create this feature ? Can one try to use the Relation module and overriding Access control to perform it ?

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


List items of a certain content type in another content type For college we have to create a website with drupal. This website has to be for a travel agency that does surf vacations. We already have the  basic website up and running but are kinda stuck with the destinations.

I will quickly explain how the website should be set up and our problem.

So bassicly a customer should be able to go to the page called "Destinations" and have a list of the 4 available countries where they could book a vacation. Like for example you have Australia and Costa Rica. However when a user clicks on for example Australia he should get a new list of possible locations within this country where he wants to go surf.

We have tried with many different ways to get this to work the problem however is that both the countries and local destinations should have a picture and a short description. Also the user should be able to select their "level" on the specific location.

What we have tried:

Taxonomy: We have tried using taxonomy but it doesn't allow us to give the right design to the website. It will list the countries but without any description or picture.

Ubercart: I wish this would have worked but somehow you can't create subclasses in ubercart or just only show a list of classes with views.

Thank you for taking your time and we hope to find a solution soon.

Kind regards.

A general out line is given below,

Create a content type for country, add your available
countries with images and description
Create a destination content type, with necessary fields like
image,description etc: (If you want process booking with payment, use
Ubercart and create a product class Destination, modify the required
fields)
Add a country field to destination contenttype of 'fieldtype' - Node Reference, choose widget as select list. This allows choose country on creation of a new destination
Use Views to list the destinations page, by selecting necessary fields,
Use views to create the list of related destinations based on the
country name and save it as a block. So based on the country
selection the destinations can be list in this block
If you are using online payment for booking use ubercart, otherwise
on booking you can send an enquiry to admin.

Hope you got an idea on how to proceed.

UPDATE
To get list of the destinations on clicking the country do the following

In your destination listing view, Add a 'Contextual filters'(
Arguments in D6) and choose the 'country nodereference field'.
In your four country listing view, in fields choose Nid (Nid)  also
and choose 'Exclude from display ' option for that field.
Then in the 'Country name field' - click 'Rewrite results' and choose
'Output this field as a link' checkbox. In link path give path like
below
eg: destinations/[nid]  ie: where destinations is the path of the
your destination page and [nid] is the token for the node id.
Probably you have to just change 'destinations' only with your path.

Thats it, now on clicking the country it will goto destinations page which shows all destinations belongs to the particular country


Tagging separate files I wonder if, and how, the following would be possible to tag each uploaded file with one or more tags and show these files filtered on their tag(s).
I know it's possible to do this for nodes but have not found a way to tag single files.

The purpose of this would be the creation of an image bank in which the administrator can upload images or files (pdf, zip) and define each image/file as being, for example, 300dpi, print, high resolution, color, black & white, etc.

In both Drupal 6 and Drupal 7 files are not used independently. Most often, fields are used through a file field, on either a node (D6 or D&) or an entity (D7).

To do the above, I would suggest using a file field on something, that holds all the info about the file. You could add things like title, teaser  text, description in addition to tagging. For Drupal 6 the only option you have is to use nodes, for Drupal 7 you could use nodes or create your own entity in a custom module. The easiest thing will be to use nodes, as you wont need to create a lot of functions for editing, loading, rending... the entity. Nodes are probably also a good match in this case since the files are content on your site.

Another plus doing this, is that you would be able to use the Views module, and create different galleries or list of image files.


How to remove 'Message log' tab from profile page? I've got this tab on profile pages of all users and for whoever I've tested, pressing this tab just yields:

  No logged messages

So it seems a real glitch that comes with some module which I've no clue of. So just wondering how can I remove the tab?

It's part of the Messages modules; it has nothing to do with Private messages.

It's not a glitch, it's what this module does: a simple example of a way to deliver messages (notifications) to users.


Display top level of book, in book navigation block In my theme's .theme file I have the book navigation block stored in a twig variable like so.

function mytheme_preprocess_page(&$variables){
    $book = \Drupal\block\Entity\Block::load('booknavigation');
    $variables['book'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($book);
}

I'm then calling it in my page.html.twig template like so

    {{ book }}

    {{ page.content }}

However on basic pages that are book pages, sibling book items are shown but the top level book page is not. Even when visiting the top level book page the link is not shown in the book block.

Why isn't the top level of the book ever displayed? And is there a way I can get the top level to be shown?

UPDATE:
I've looked at creating a book-tree.html.twig. The contents are below

{% import _self as book_tree %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ book_tree.book_links(items, attributes, 0) }}

{% macro book_links(items, attributes, menu_level) %}
  {% import _self as book_tree %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

        {{ dump(book_tree|keys) }}
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ book_tree.book_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

But I don't see where I can access the top level.

UPDATE: I found a workaround but I'm looking for a solution that does not require that workaround. Users should not have to create an empty page with the same title just to act as the non displayed top level.

This looks like a bug in the book module.

I have added a patch for it.

https://www.drupal.org/node/2827910#comment-11780887

You could add that patch, or create a new block that overrides the BookNavigationBlock,

in a custom module add /src/Plugin/Block/CustomBookNavigationBlock.php:

  namespace Drupal\mymodule\Plugin\Block;

  use Drupal\book\Plugin\Block\BookNavigationBlock;

    /**
     * Provides a 'Book navigation' block.
     *
     * @Block(
     *   id = "custom_book_navigation",
     *   admin_label = @Translation("Book navigation - Customized"),
     *   category = @Translation("Menus")
     * )
     */
    class CustomBookNavigationBlock extends BookNavigationBlock {

      /**
       * {@inheritdoc}
       */
      public function build() {
        $current_bid = 0;

        if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
          $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
        }
        if ($this->configuration['block_mode'] == 'all pages') {
          return parent::build();
        }
        elseif ($current_bid) {
          // Only display this block when the user is browsing a book and do
          // not show unpublished books.
          $nid = \Drupal::entityQuery('node')
            ->condition('nid', $node->book['bid'], '=')
            ->condition('status', NODE_PUBLISHED)
            ->execute();

          // Only show the block if the user has view access for the top-level node.
          if ($nid) {
            $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
            return $this->bookManager->bookTreeOutput($tree);
          }
        }
        return array();
      }

    }


Pathauto , Using Body Value for URL Alias I am trying to use the use the node body value for URL alias using Pathauto . I am trying the below path pattern : content/[node:body:?]
But this doesn't seem to have any effect .
I have tried this also : content/[node:body:Text] ..yet no result .

Any pointers to resolve this is highly appreciated .

Thanks

Without questioning why you would want body text in a URL alias you should be able to access this by using:

[node:body:value] for the value
[node:body:summary] for the summary


Is there a trick to getting Mime Mail to recognize by-mailkey theme templates? I have installed Mime Mail 7.x-1.0-alpha1 and got it set up and working for the most part.  The thing I'm having trouble with is getting it to recognize a by-mailkey template. I have been able to copy the mimemail-message.tpl.php into my theme directory, modify it and have it apply to the HTML email I am sending just fine.  I can put that file anywhere in my theme directory and it finds it and overrides the default. I cannot however get it to recognize a by-mailkey template no matter where I put it in my theme directory.

I have an email with the key help_wanted set. I have created a template file called mimemail-message--help-wanted.tpl.php, which I believe is the correct template name to apply to the email with that key.  I have cleared the cache and sent the email, but the default template is still applied.

I have also tried using mimemail-message--help_wanted.tpl.php with no luck.

I know the proper key is being passed because I can set up the mimemail-message.tpl.php to override the default template and print out the $key variable in the template and get help-wanted.

Does anyone have any experience with this and might know what I could be doing wrong?

Use latest dev version of Mime Mall module. It doesn't work in 7.x-1.0-alpha1 and 7.x-1.0-alpha2.

But you can also make a quick hack. In file mimemail.module need to comment the row #531

$key = str_replace('_', '-', $key);

After that you can use mimemail-message--help-wanted.tpl.php template.


How to add cck custom date field? I am trying to create custom compound field with a text field and a date popup.

I've tried the following code:

 $element['year'] = array(
    '#title' => t('date'),
    '#type' => 'select',
    '#default_value' => $options['year'],
    '#options' => $options,
    '#weight' => 2,
  );

...

function _universitydegrees_values_year() {
    $options = array(
        'year',
        1970,
        1971,
        1972,);
    return $options;
}

In Drupal 6 we had the Multigroup module, which was bundled as part of the CCK 3.x branch. As of comment #353 on the State of the multigroup module thread, you should be able to just swap your CCK 2.x code for the 3.x branch and run the updates without no problem. I used this module a few years ago and it worked fine.

Be advised however that apparently the CCK Multigroup module migration path to D7 is undefined. i.e., if you develop your site in D6 with CCK 3.x there's no guarantee that you will be able to automatically convert your CCK data to D7.

There are other Drupal 6.x field-grouping modules metioned here that you might find worth researching. This post also talks about different grouping modules and it might interest you.


Image cache present in which config file I am new to drupal and was learning about image cache.So far its going good but I want to know where exactly the image cache config is getting saved.I mean to ask which file I have to browse to see image cache setting?If my doubt is silly then please forgive me.Thanks

Image cache is core in Drupal 7 IIRC. So you can access its config and settings via /admin/config/media/image-styles. The cached images themselves are saved in your theme/files dir as defined in /admin/config/media/file-system.


Add HTML Tags for all the site pages I was searching around but with no clear solution for me!

I would like to add the below HTML code for all my Drupal 8 website pages:

<meta name="viewport" content="width=device-width, user-scalable=no" />

How can I do that, is there a contributed module for it ?

Thank you,

1. Using metatag module

If you want to do it without custom coding you can try metatag module

enable MOBILE & UI ADJUSTMENTS submodule
go to metatag settings admin/config/search/metatag
edit the GLOBAL settings
under MOBILE & UI ADJUSTMENTS fill in viewport input box

2. Using viewport module

There is also a dedicated module called viewport which will allow you to do just that.

3. In your custom theme

But can be easily done in your custom theme. Put the following code inside the THEMENAME_preprocess_html function in your THEMENAME.theme

function THEMENAME_preprocess_html(&$variables) {
  $viewport = [
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => [
      'name' => 'viewport',
      'content' => 'width=device-width, user-scalable=no',
    ],
  ];
  $variables['page']['#attached']['html_head'][] = [$viewport, 'viewport'];
}

NOTE: if THEMENAME_preprocess_html function does not exist you can create it and put the code inside.  You can't redeclare it otherwise you will end up with WSOD.

function THEMENAME_preprocess_html(&$variables) {
  //...
}


Why is jQuery UI toggle not working in my theme? I've tried setting up a jQuery toggle menu without much success. I followed the exact instructions and code from this tutorial, but even this simple script is not working.

Regular JS (like an alert) seems to work fine. I have Views installed and it seems the views admin uses extensive jQuery and works fine. Is there something I have to do to enable jQuery on my theme?

jQuery is added by Drupal core and is available globally.

Clear cache at Admin > Config > Performance

Check your script.js has been added to the html source.


How to generate commerce add to cart form on a page with full functionality? I am building a small site with very simple products, what I am trying to do is build a product list based on one product node, it's more easy to use an example to explain.

Like I have a product node with these fields, title, unit number, unit, price, we call it [base product].

Title:  juice
unit number: 100
unit: ml  /milliliter/
price: 3$

Now how to generate a product like this? Please note that the price are auto-calculated.

juice 100ml  3$  add_to_cart_form
juice 200ml  6$  add_to_cart_form  /* 3$x2 */
juice 300ml  9$  add_to_cart_form  /* 3$x3 */
juice 400ml 12$  add_to_cart_form  /* 3$x4 */
juice 500ml 15$  add_to_cart_form  /* 3$x5 */
juice 600ml 18$  add_to_cart_form  /* 3$x6 */
juice 700ml 21$  add_to_cart_form  /* 3$x7 */

Please note that this product is actually one product reference page but have several add_to_cart form buttons,  all the information is generate from [base product]

Because the product is so simple that I don't want the user have to increase the product quality themselves by input numbers or click the add_to_cart buttons again and again, just pick up a quality and add_to_cart.

However, this also can be solved by adding product nodes with different quality number, but it's a pain if you want to change the price information when you product reference page have a much longer list for displaying, especially when all the products have a same [base price].

Any insight or suggestions will be much appreciated. Thanks in advance.

use the inline entity form module to enable product variations. in the node you only have a product reference field, where you reference all your desired product(-variations)

then the user still can input the quantity, but also choose the product-variation. in your case the different ml-units.


How to render text including video embed field I have a formatted text field, and am using the video_embed module to allow users to embed video into that field, using the video_embed_wysiwyg submodule.
I am then trying to render the field in a block, but I simply get the JSON output in the text field:

{"preview_thumbnail":"/sites/default/files/styles/video_embed_wysiwyg_preview/public/video_thumbnails/A5jNGsBHHUE.jpg?itok=7fW8O9To","video_url":"https://www.youtube.com/watch?v=********","settings":{"responsive":1,"width":"854","height":"480","autoplay":1},"settings_summary":["Embedded
Video (Responsive, autoplaying)."]}

Here is my render array:
$text=check_markup($node->get('field_html_containing_video_content')->value, $node->get('field_html_containing_video_content')->format);

    $renderArray=[
      'content'=>[
        '#type'=>'inline_template',
        '#template'=>$text
      ]
    ];

    return $renderArray;

I've got the video embed filter enabled on the relevant text format, and have tried changing the order of the filters.
Any ideas what i am doing wrong here?
We are using a bootstrap subtheme.
Thanks for any help given.

check_markup() is not able to handle attached metadata which some text filters need to work properly.
You have to use the render element processed_text:
$renderArray = [
  'content' => [
    '#type' => 'processed_text',
    '#text' => $node->field_html_containing_video_content->value,
    '#format' => $node->field_html_containing_video_content->format,
  ],
];

More info How to safely render node body on a custom variable?


How to properly recognize a session id generated by drupal? I'm storing stuff in a session that is sometimes handled by drupal. The session id is passed forward to another service, which checks back to the original server to get the session data.

When the session id is generated by drupal, i want to recognize it so i can include the drupal bootstrap instead of creating a normal php session. What would be a proper way to recognize drupal session ids ?

Is there a way to make it more specific, like change the sessionid myself ?

Drupal will let you override the default session handler using the session_inc variable. This is what Drupal actually uses to bootstrap the session:

require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');

So to replace that with your own, set the variable to your own path:

variable_set('session_inc', 'sites/all/modules/MYMODULE/session.inc');

And re-implement the functions from the core session.inc in your custom file, making changes where necessary.


Changing Twig template of form items through the theme I have a block, which renders out a form using code that looks like this:

{{ attribute(form.facets, 'filter_' ~ filter.name) }}

I'd like to amend the markup and CSS classes for the various elements that are output, including fieldset, input, label etc. I appreciate that I can override the template files for fieldset for example, by creating a fieldset.html.twig file in my theme, but I don't want to change the markup for every fieldset element. I only want to apply my custom templates to form elements which are rendered out from a specific block.

I know that I can use a 'suggestion' (mytheme_theme_suggestions_alter) to alter the template for any element, but I can't see a way of determining if an 'input' for example, is an input within my block, or some other block on the site. Does anyone know how I'd identify this?

You can use drupal_static() together with the following two hooks in your module or your theme to add template suggestions for input elements based on the block ID where the input element is used in (same would work with fieldsets or any other form/render element):

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_block(&$variables) {

  $bid = &drupal_static('block_id', TRUE);
  $bid = $variables['elements']['#id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_input_alter(array &$suggestions, array $variables) {

  $bid = &drupal_static('block_id', FALSE);

  if ($bid) {
    $suggestions[] = 'input__block__' . $bid;
    $suggestions[] = $variables['theme_hook_original'] . '__block__' . $bid;
  };
}

For example the search form textfield:

<!-- FILE NAME SUGGESTIONS:
   * input--search.html.twig
   * input--search--block--neato-search.html.twig
   * input--block--neato-search.html.twig
   x input.html.twig
-->

For example the password textfield:

<!-- FILE NAME SUGGESTIONS:
   * input--password.html.twig
   * input--password--block--userlogin.html.twig
   * input--block--userlogin.html.twig
   x input.html.twig
-->


unable to set dateboosting in apachesolr with D6 I'm using Drupal 6.22 with apache solr module for search functionality, specifically using 6.x-1.6 version of solr. I had a date field for my node added to the solr indexing named as ds_myDate in ISO-8601 format (Y-M-DTH:i:sZ) and used it for sorting the search results which worked fine.

Recently I decided to replace the sort with a search boost functionality so that most relevant search results are boosted based on the ds_myDate field. In my custom module's hook_apachesolr_modify_query adding the following code (based on understanding from http://wiki.apache.org/solr/FunctionQuery#Date_Boosting)

$params['bf'][] = "recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)";

to effect the boosting threw 400 error stating Can't use ms() function on non-numeric legacy date field ds_myDate. Hence I tried using an alternative of adding the same in the queryfield instead of boostfield in the same hook as

$params['qf'][] = "recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)";

which got added but did not show any impact on the search results.

As I have very little or no access to the Solr server or its logs I logged the solr query in the search function and in both cases the field was added to the query. In the former case of using boost field (throwing 400 error) the solr search url would return a path like

...qf=tags_inline^5.0&bf=recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)
&bf=recip(rord(created),4,3403,3403)^200.0&fq=...

and in the latter method of using as queryfield would return

...qf=tags_inline^5.0&bf=recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)
    &bf=recip(rord(created),4,3403,3403)^200.0&fq=...

Would be great to know what I'm doing wrong here or how this implementation in Drupal could be done properly since 7 has a hook like hook_apachesolr_query_alter where the date boosting could be done.

For the legacy date field that the ds_ dynamic field is set to use in the 1.6 version schmea.xml, you can use the rord() function. It's not considered best practice any longer but it works with field types that don't enable using ms(). More information at Solr Wiki. The example query goes like this (copying it here to avoid link rot):

recip(rord(creationDate),1,1000,1000)


Strange question pertaining views as forms? I am attempting to provide quizzes in Drupal. The Drupal quiz module is out of question as a version for Drupal 7 does not exist. The way to go about doing this then IMHO is using web-forms. I am treating each question that is part of the quiz as a separate node entity.

The idea is to cluster these questions based on taxonomy vocabularies and establish a quiz. Clearly the best way to have nodes together would be VIEWS with some filter criterion. However, this clearly backfires. It establishes the required set of questions as a view. But this does not necessarily establish them a single quiz form, but rather a set of individual forms all present in the single page. Essentially, if my view has 10 questions, then it has 10 SUBMIT buttons.

My aim is to try and create this view as a form, but I think that is not possible anymore. I feel I should just post this here, regardless to get an answer or alternative ways to go about doing this.

I'm not sure Views would be the way I'd go with this. It's for getting data displayed from the database and this just seems like you're stretching the scope of what it's designed to do.

Is there any reason each question has to be on a different node? That seems to be adding even more complexity.

My suggestion would be to use webform to a the form for each different quiz. Especially if site administrators will have to create the quizzes regularly as webform offers the best UI for doing this. The difficult bit then is to write some sort of add on to webform (I don't know how much of an API webform has) that changes how the form is submitted and validated to be more 'quiz like'.


How PHPTemplate works and what it do? There is a default templating system PHPTemplate in Drupal, they say.

But where can I see it? I don't see anything more than pure php in template files .tpl.php. Once I've seen template system Smarty in non-drupal webpage files and there was tempalting syntax with { } braces in .php files with HTML. I also have seen Blade templating syntax in Laravel framework's files.

So where is the PHPTemplate in Drupal (or how it works and what it do?)

PHPTemplate:

  A theme engine that allows you to use template files written in pure
  php. These template files do not need to be processed by the theme
  engine, and as such execute a lot faster than most other template
  engines. Another major advantage to using PHP as your template
  language, is flexibility, as the advanced user can access any
  information / functionality available in the Drupal API, and is not
  restricted to what the template engine / language allows him to do.

  This is the default theme engine starting in Drupal 4.7. If you are
  using Drupal 4.7 and above, you don't need to download PHPTemplate
  here.

A Template system does not need to use special code or markup to be called a template. PHPTemplate refers the system of implementing pure php code template files, how those files are accessed and referenced by the system and how other parts of the system (such as template.php) can modify the results of those files


How can we find the id of the parent form in preprocess_HOOK() or HOOK_alter() theme functions? I'm working with an entity-creation form that needs some extensive theming. So far this has required me to alter template suggestions and create (twig) template variables for fieldsets. I've used template_preprocess_fieldset() and hook_theme_suggestions_fieldset_alter() to do this.

The suggestions and variables I'm creating are specific to one entity type, so I'd like to use the form id or the entity type to limit the action of the functions above, but the variables available within the scope of the functions don't include information outside the scope of the fieldsets themselves--in other words, I can't find out what form the fieldsets belong to.

Is there a way, in the context of a theme's preprocess_HOOK or HOOK_alter functions, to get information about the parent form?

I'd neglected to mention that I'd unsuccessfully tried @Berdir's two-part solution:

Set some value in hook_form_alter()
Access that value in hook_template_suggestions_fieldset_alter()

Going back at @Berdir's suggestion, I cracked it (thanks!)
In Drupal 8, this combination works for my specific issue (and should work for other implementations of `hook_theme_suggestions_HOOK_alter() as well):

/**
 * Implements hook_form_alter().
 */
function themename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'some_specific_form_id':
      foreach ($form as $key => $value) {
        if (strpos($key, 'field_') === 0) {
          $form[$key]['widget']['#parent_form_id'] = $form_id;
        }
      }
      break;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function u2d8_theme_suggestions_fieldset_alter(array &$suggestions, array $variables) {
  // Key the use of this suggestion to the front page.
  if ($variables['element']['#parent_form_id'] === 'some_specific_form_id') {
    $suggestions[] = 'fieldset__some_specific_form';
  }
}

Not directly, but you can do it in two steps. In a form alter, set whatever information you need on the element where you later need it.

I'd suggest do use some sort of prefix, like #project_form_id = ABC

That should then be available in the preprocess/suggestions hooks.


How to open a popup form from a view link? I'm really struggling with this issue.
Well I'm having a view, in this view a field configured as personalized text as a link.
I want to open a popup form on click on the link.
Here is what I did in the method called by the link:

 $response = new AjaxResponse();
  $title = 'Title for the Popup.';
  $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
  $response->setAttachments($form['#attached']);
  $content = '
' . 'Content in HTML format' . '
';
  $options = array(
    'dialogClass' => 'popup-dialog-class',
    'width' => '75%',
  );
  $modal = new OpenModalDialogCommand($title, $content, $options);
  $response->addCommand($modal);
  return $response;

But It's not working at all!
Please help!

Your code is building an ajax response. This only works in ajax callbacks, nowhere else.

If you want to make a link modal, so that it will open in a popup, you have to set the class use-ajax and the attribute data-dialog-type. Like in this example from ConfigSync.php:

$links['view_diff'] = [
  'title' => $this->t('View differences'),
  'url' => Url::fromRoute($route_name, $route_options),
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => json_encode([
      'width' => 700,
    ]),
  ],
];

For modal links to work you need to attach a library, see How to create modal windows (pop-ups)?


Include date module in custom module I have а custom module that will show some reports. It will have two textfields, so when a user clicks one of the fields "starting date" and "end date" a calendar will popup and will able to select the dates. After selecting the dates, it will show the table with the results.

I've been using "Date" module with content type/fields, but I've never done in a custom module.

If these are the two fields:

<?php

$content['starting_date'] = array(
     '#type' => 'textfield',
     '#title' => 'Starting date',
);

$content['end_date'] = array(
     '#type' => 'textfield',
     '#title' => 'End date',
);

?>

How can I show the popup calendar when a user clicks on some of the textfields and show the results?

I'm using Drupal 7.

EDIT: I'm marking Clive's answer, but the date_popup works only on forms, not custom fields.

Assuming you have the date popup module installed and enabled:

$form['starting_date'] = array(
  '#type' => 'date_popup',
  '#title' => 'Starting date',
  '#date_format' => 'd/m/Y',
  '#default_value' => date('Y-m-d'),
);


Alter entity.user.canonical (/user/{uid}) route When a user (e.g. nid = 37) goes to some other user's profile page at a url like /user/1, /user/2, ..., /user/n, I want automatically redirect them to their own: /user/37 page.

How can I do properly this with Drupal 8?

I think I must create a custom Controller Class and configure the default drupal route (/user/{uid}) adding my custom Controller, but I don't know how can I do this.

There are at least two ways you could pursue to do what you're trying to achieve:

You can alter routes using a RouteSubscriber.
Listen for a event (likely KernelEvents::REQUEST), and respond appropriately.

The RouteSubscriber is probably a bit hard to do (I haven't written one yet, I just discovered their existence the other day), but is more in keeping with the older hook_menu_alter patterns from previous versions of Drupal.

The EventSubscriber is probably easier to write once you understand the event system (which requires some learning but is where lots of the future of Drupal internals is headed).


How do I get the current URL in a rule? I am trying to make a Rule where after the user logs in they are redirected to the front page except when they are setting their first time password or resetting their password
To do it I want to use a Rule that acts on User Logged In, with a condition that checks if the url they are on has edit in the name, and if it doesn't then redirect them to the front page.
My issue is that when I try to use the Path Contains Text condition it never triggers, and if I try to print the url in a message as the action it is always empty.
What am I doing wrong? What do I need to do to get the results I want?

Here is a working example taken from the Rules Examples module, which is a submodule of D8 Rules Essentials.
langcode: en
status: false
dependencies:
  module:
    - tr_rulez
  enforced:
    module:
      - tr_rulez
id: redirect_to_home
label: 'Redirect to home on Login'
events:
  -
    event_name: rules_user_login
description: 'Issue #2975452-6: Redirect all users to "/" on login, except for when a one-time login password is used.'
tags:
  - login
  - redirect
  - rules_examples
config_version: '3'
expression:
  id: rules_rule
  uuid: 7263942c-3847-460d-af3f-6c78f80fbcc1
  conditions:
    id: rules_and
    uuid: a8c1bb95-b783-4238-a7e1-9b4b9fb96ca4
    conditions:
      -
        id: rules_condition
        uuid: f35e2d95-850d-455d-99e2-629e37b17cb7
        context_values:
          text: reset
        context_mapping: {  }
        context_processors:
          text:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_path_contains_text
        negate: true
  actions:
    id: rules_action_set
    uuid: d17285ef-4de4-498a-8b78-654cf79566ee
    actions:
      -
        id: rules_action
        uuid: a529b090-e6f3-4421-aede-75489267d888
        context_values:
          url: /
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect


Minimum schema version I am updating my site from Drupal 8.2.1 to 8.2.4, while running update.php I encounter this problem

  The installed schema version does not meet the minimum.
  Your system schema version is -1. Updating directly from a schema version prior to 8000 is not supported. You must migrate your site to Drupal 8 first.

I am unable to proceed any further. What exactly is causing this problem?

Use Drush. The following commands worked for me.

drush updb -y
drush cr


Charts Module not working for one site - No messages in the log Using Drupal 8.5.4 and I am referencing the url as https://www.ostraining.com/blog/drupal/create-charts-with-views/

as a guide.  I have built charts with an empty scratch sites without issues.  However, when I try to integrate it into an existing site I get nothing.  I have checked the sites messages with but nothing is there.  I am not really sure where to look to troubleshoot the issue.

I just want a basic chart, nothing fancy out of the gate.

As the Charts maintainer, I am happy to help. My first recommendation is to update to the latest version of Charts (beta1). This has improved handling of fields within Views and a new default in place for Charts Attachments that prevents some issues that users have faced previously. The next thing, and what I think is most likely, is that the libraries did not install properly. Please try disaggregating your JS (from the Admin > Config > Development > Performance page) and then on the page where the chart should be displaying, try inspecting the code and looking for the library's .js file (e.g. highcharts.js). If you're using Chrome, the console tab may tell you something about what is happening.

This also seems silly to say, but be sure your View has results, that it has a field for a title and a field for data, and that those are set in the format settings. This should help for most issues you would experience, but if you are still having trouble please add more information to this post so that your issue can be better diagnosed. Good luck!


Button to selectively include content in an RSS feed When creating or editing some content types I want to be able to have the option to add the content to an RSS feed thats generated by Views.

Is this achievable?

Well, you can just add a field to the content type(s) you are collecting with your view and use that to filter the rss feed. You could easily add a "include in rss" checkbox for example with whatever default value you like.


Why does $page['content']['#attached']['js'] works , while $page['#attached']['js'] does not? Trying to attach js by means of #attached by means of hook_page_alter (see https://drupal.stackexchange.com/questions/171918/how-to-add-javascript-with-attached-and-hook-page-alter), I found that the following code

 function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

works properly - it attaches the file - while

function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

does not. Why is it so?

For #attached elements to be processed, the array needs to be run through drupal_render(). That never happens for the $page array.

Parts of it are rendered, e.g. in page.tpl.php:

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

But never the $page array itself.


Views exposed filters do not display in front end I created a view block. I can see the view block on my page (node/30) no problem. Edited the view by adding filter criteria. I also changed "use Ajax to Yes". I can see the exposed filter in views edit page but I dont see the views at all on my actual page when I add the filter criteria. After I remove the filter criteria, I see the views again on my page. When i added the filter criteria, I also checked "exposed to user option.." I am not sure what I did wrong.

Please help.

D

Mb it's because there is no result. In that way you will see exposed form on edit page, but view will not be displayed on front because it's empty (so, there is no need to display exposed form for user and it's hidden).

Try to go on your view's edit page to No results behavior and make it display some text to see if view has no result