How to allow node authors to mark the best comment and to promote this comment on the top of list In my project comments are prices so its important that commenters see author's choice. I want to allow authors to choose the best comment that would get this comment promoted on the top of a comments list. Can I do it with Rules or some other ways?

As discussed in the comments above, you can create a global Flag, say Best price, for comments. In order to reorder the comments, you can create a comment View which displays all comments of a certain node with the flagged ones on top. Afterwards, display the associated block on the node's page.

Maybe there is an easier way to reorder the comments, but this should at least work and illustrate the strength of the Views module. Underneath is my exported View, which you can easily import and adapt to your needs if necessary:

$view = new view();
$view->name = 'reordered_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'Reordered comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access comments';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Relationship: Flags: best_price */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'comment';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'best_price';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['label'] = '';
$handler->display->display_options['fields']['comment_body']['element_label_colon'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Flags: Flagged */
$handler->display->display_options['sorts']['flagged']['id'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['table'] = 'flagging';
$handler->display->display_options['sorts']['flagged']['field'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['sorts']['flagged']['order'] = 'DESC';
/* Contextual filter: Comment: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'comment';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');


Putting items in multiple places in a menu I'm trying to set up a menu layout which has two links to /biblio; one under "Researchers", and one under "Staff". This is for convenience, as if you are looking under "Staff", the "Researchers" submenu is closed, and the "Staff" submenu isn't available to unregistered users. The problem I'm running into is that although I can have two links in different parts of the menu, when looking at the page it will always try to open the menu to only one of them. This means that if you are looking under "Staff", and you go to publications, suddenly you're in what seems to be a different location of the site. Any suggestions for how I can fix this?

You can use the Multiple Node Menu module.


Set Default Value for Node Title I have a content type named Account, and it has a field named account_number. Since I import the data from a csv file using feeds. The Node title for each account is always empty.

Is there a way to set the node title default to its account_number?

Thanks

I haven't used this personally, but the Automatic Nodetitles module is designed to handle tasks like this.  If you have Token installed and enabled, you should be able to populate the autotitle using a field value.


Get a views results programatically I have a page with a view on it and some exposed inputs. I need to get the results programatically. I can load a view programmatically no problem but setting the exposed input has not been working.

$view = Views::getView('inventory_listing');
$view->initDisplay();
$view->setExposedInput($view->getExposedInput());
$view->preExecute();
$view->execute();

results in ALL the rows, not the ones filtered out. I am running this in my hook_form_alter function because I need to change the display of my exposed filters. That may be part of the problem. Any ideas?

I use direct input parameter for right filtering, and it is working for me.

$view = Views::getView('my_view_name');
$view->setDisplay('display_name_from_my_view');
$view->setArguments([ $value1, $value2 ]);
$view->execute();

So, i can take result of $view by

$result = [];
if (empty($view->build_info['fail']) and empty($view->build_info['denied'])) {
    $result = $view->result;
}

After this I can render it or use for another goal.


Append Fields to node form by ajax call I have a node form with some fields, now I want to append some more fields to it on an ajax callback. in the ajax page I have rendered the new form elements with drupal_render function
My problem is that I am not getting the newly built form fields in POST or form_state.
Shall I use AHAH or can I continue with this ajax calls?

$form['country'] = array(
            "#type"=>"select",
            '#title'    =>t('Ship To'),
            '#required' => true ,
            '#options' => $options,
            '#weight' =>10,
            '#attributes' =>  array('id' => $cn_var),
        );
        $form['dyn_cost'] = array(
            "#type"=>"textfield",
            '#title'    =>t('Shipping Cost'),
            '#required' => true ,
            '#size' =>25,
            '#weight' =>11,
            '#id' =>  $co_var,
        );

        print drupal_render($form);
        exit;

This is my ajax form and it is supposed to be appending to the node form.

You can use Conditional Fields module to display form fields with certain conditions. No need to use custom ajax calls.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


How to keep content out of features? I have plenty of Panels pages that I track using the Features module. Currently, if I create put a Custom Content pane inside of a page, all of the content that is inside that pane is then stored in code.

If I make the custom content pane reusable or use a block instead, it is referenced by id. I don't want this behavior, either. For example, I create the block on my development environment, add it to my page, and commit my feature containing that page to version control. When I pull those changes into my test environment, the page is looking for a block with a specific id. Chances are the block won't exist, and I have to go create it. When I do that, though, there's no guarantee that my block will have the same id. Even worse, a block might already exist with that id, and the page will be using a block with completely unwanted content!

Blocks that are organized using the Context module rather than Panels have the same problem, I think.

I'm looking for a module or an approach that lets me reserve a space for content. I don't want that content to be kept in code (my feature) at all, but I do want the feature to know that my panel or context has a space reserved for that content. Modifying the content shouldn't cause the feature to show up as overridden.

Is there an existing module that allows for this functionality? If not, which module developers should I contact in order to get this sort of thing implemented? Or will a whole new module need to be created for this?

Maybe I'm misunderstanding the current behavior of these modules, even. Any help would be appreciated.

By the way, I don't think this is a problem that's specific to one version of Drupal, but if you have to pick a Drupal version to talk about, I'd say 7.

Though I don't think this solves your problem of not wanting the content included in the feature at all, there are 2 ways that I know of to be able to create blocks that don't use numerical ids, and that can therefore be safely included in a feature.

Boxes
Beans

Personally, I prefer the Bean approach, since the Bean Bundles are fully fieldable, allowing to create very advanced types of blocks. Both of these modules however essentially allow you to create blocks that have machine_names (feature proof) as opposed to numerical ids, which as you know are a royal pain in the ass when it comes to features integration.

EDIT: actually, now that I think of it, Bean does not create blocks with machine_names - it uses numerical ID's. It is the Bean Types (think Content Types) that have machine_names. So, if you want blocks with machine_names, Boxes is the way to go.


POST content on redirect I would like to redirect my users to the login page on certain pages when they are not logged in. I have created a custom template for my login page, I don't know if that makes a difference, but I would like to pass two bits of information to the page in a way that the
user can't see them.

I would like to pass a message that should be displayed on the login page and also the URL that the user should be directed to after login. What is the easiest and most clean way of doing this please?

Have you tried rules module. You can trigger custom action on some event. What you need to do :

create an event "when the node being viwed"
create a condition "when node is equal to some node"
Fire a action "redirect to login page"
Fire another action "show a message"(this is set drupal_set_message for you)


Adding a custom path for node I have enabled the path auto and workbench modules in my drupal installation. I have to set the url alias once only. Once a node is published and url alias is generated, the url alias should not be generated again if end user changes the title of the node. Also I have to generate the url alias only when node goes to published state.

I am trying something like this:

function hook_entity_presave($entity, $type) {
  //Do not create url alias of node unless its not published and if you create a Draft of a published node, the URL of the published node should not go away.
  if($entity->workbench_moderation['current']->state != 'published'  && !isset($entity->workbench_moderation['published']))
  {
    $entity->path['alias'] = '';
    $entity->path['old_alias'] = '';
    $entity->path['pathauto'] = 0;
  }
  else {
    $entity->path['pathauto'] = 1;
  }
  // if node is published, do not change the url alias if end user changes the title of the node.
  if(isset($entity->workbench_moderation['published'])) {
    $entity->path['alias'] = $entity->path['original']['alias'];
  }
}

and I am trying to accomplish this with hook

function hook_node_presave($node) {
  $node->path['alias'] = $node->path['original']['alias'];
  $node->path['pathauto'] = 0;
}

You can set that in the URL aliases configuration.

In http://example.com/admin/config/search/path/settings

In the section 'update action', check one of the two:

Do nothing. Leave the old alias intact.
Create a new alias. Leave the existing alias functioning.

The default is:

Create a new alias. Delete the old alias.


Theme structure for multi-site I have a multi-site setup with three themes. They look the same, but they are different in colors. What are best practices to setup my theme structure, in themes/custom/site1, site2, and site3, or in sites/site1/themes, sites/site2/themes, and sites/site3/themes?

If they only differ in color, you should provide a theme setting for choosing it and setup the theme in /themes/custom/mymulticolortheme, so it will become available for all sites. Otherwise you have to maintain multiple nearly identical themes, which is a time killer when you have to fix a bug or add a feature.

If you have different themes for each site you should place each theme in the particular site theme folder like /sites/site1/themes/custom/myspecialthemeforsite1, /sites/site2/themes/custom/mytotalydifferentthemeforsite2 etc., so that they are only available for sites they belong to.


Display Suite: how can I generate a render array for a field that is not being displayed What I'm doing is complicated, and there is likely to be a much better way to do it, so I'll try to go into some detail, and edit the question after the fact to tailor more closely to the final answer I get if the answer is to do something different.

Right now for my teaser view for nodes I generate a generated_cover field in code to allow me to fallback through a couple of potential sources of cover image.  First there is a cover image field.  If a user has uploaded a cover image for the node we use that.  Second is a cover generated by the pdfpreview module, finally if neither of those are found, it returns a blank, which I then use with field formatter conditions in display suite to replace with a placeholder image.  As you'll note from the code used for generating the fields below you'll note that they rely on `$field['build'] to get the generated field.

/**
 * Implements hook_ds_fields_info().
 */
function MY_MODULE_ds_fields_info($entity_type) {
    if ($entity_type == 'node') {
        $fields = array();
        $fields['generated_cover'] = array(
            'title' => 'Generated Cover',
            'field_type' => DS_FIELD_TYPE_FUNCTION,
            'function' => '_MY_MODULE_ds_field_generated_cover',
            'formatters' => array(
                'standard' => 'Standard output',
            ),
        );
        return array('node' => $fields,);
    }
}

/*
 * Generate the output for the generated cover image field
 */
function _MY_MODULE_ds_field_generated_cover($field) {

    // Get information about the entity being rated and the formatter we're using.
    $entity = $field['entity'];
    $formatter = $field['formatter'];

    if (!empty($entity->field_doc_cover)) {
//        $output = "cover";
        $output = render($field['build']['field_doc_cover']);
    //    $output = render(entity_view('doc_publication_files', $entity->field_doc_cover, 'teaser', $entity->language));
    } else if (!empty($entity->field_doc_pub_files)) {
//        $output = "preview";
        $output = render($field['build']['field_doc_pub_files'][0]);
    } else {
        $output = "";
    }
    return $output;
}

This has worked fine for the teaser view, though the build variable is never populated if the field is disabled for the display, so I need to include the fields in the display and use field formatter conditions to hide them.  Now I need to use the same fallback on the full display, and am running into an issue:  I need to display the file field using a different formatter AND have the pdfpreview version as an option for the cover fallback.  I used a dynamic field to bring a copy of the file field in and set up the formatter as I needed it to be, while still keeping the original file field as a hidden field set up to the pdfpreview format, but now no matter how I try to hide the original file field (with the pdfpreview formatter) and display the dynamic field, if the pdfpreview version is not completely disabled, the dynamic version will not show up.

I'm trying to fix this by not relying on the presence of the original field in my generated form anymore.  I'd like _MY_MODULE_ds_field_generated_cover to produce and render an appropriate render array for the cover image if it exists (image at medium style linking to nothing) and produce and render an appropriate pdf preview for the first file if it exists and is a pdf file (again medium style).  Otherwise it should return nothing.  That way I'll be able to use my original file field in my displays without concern that they'll interfere with each other.

I got it worked out, so here is my new code that actually renders the image fields instead of relying on them being prerendered for me:

/**
 * Implements hook_ds_fields_info().
 */
function MY_MODULE_ds_fields_info($entity_type) {
    if ($entity_type == 'node') {
        $fields = array();
        $fields['generated_cover'] = array(
            'title' => 'Generated Cover',
            'field_type' => DS_FIELD_TYPE_FUNCTION,
            'function' => '_MY_MODULE_ds_field_generated_cover',
            'formatters' => array(
                'standard' => 'Standard output',
            ),
        );
        return array('node' => $fields,);
    }
}

/*
 * Generate the output for the generated cover image field
 */
function _MY_MODULE_ds_field_generated_cover($field) {

    // Get information about the entity being rated and the formatter we're using.
    $entity = $field['entity'];
    $image_style = ($field['view_mode'] == 'teaser') ? 'list_view_cover' : 'medium';

    if (!empty($entity->field_doc_cover)) {
//        $output = "cover";
        $display = array(
            'settings' => array(
                'image_style' => $image_style,
            ),
            'label' => 'hidden',
        );
        $to_render = field_view_field('node', $entity, 'field_doc_cover', $display);
        $output = render($to_render[0]);

    //    $output = render(entity_view('doc_publication_files', $entity->field_doc_cover, 'teaser', $entity->language));
    } else if (!empty($entity->field_doc_pub_files)) {
//        $output = "preview";
        $display = array(
            'settings' => array(
                'image_style' => $image_style,
            ),
            'type' => 'pdfpreview',
            'label' => 'hidden',
        );
        $to_render = field_view_field('node', $entity, 'field_doc_pub_files', $display);
        $output = render($to_render[0]);
    } else {
        $output = "";
    }
    return $output;
}


Missing five core module folders and one enabler In Drupal 7.36, the "Administration > Modules" page (/admin/modules) lists 44 core modules. However, the folder "...\htdocs\admin\modules\" has subfolders for 40 modules, which include those 44, except Field SQL storage, List, Number, Options, and Text, plus Profile.

In other words, there are five core modules that do not have a folder in the core modules folder and there is one core module (Profile) that is not available for enabling on the "Administration > Modules" page.

Does anyone here know why that is?

The Profile doc page says to "enable in admin/build/modules". That URL on my installation just takes me to the main Administration page. So how does one actually enable this module?

The field submodules are inside the field module folder:

./modules/field/modules/number/number.module
./modules/field/modules/list/list.module
./modules/field/modules/text/text.module
./modules/field/modules/field_sql_storage/field_sql_storage.module
./modules/field/modules/options/options.module

The D7 module overview is at admin/modules. admin/build/modules was in Drupal 6; a lot of the community docs pages are badly outdated, unfortunately.

Finally, the Profile module is deprecated in Drupal 7, and therefore hidden by default.

modules/profile/profile.info:

; The Profile module is deprecated, and included in Drupal 7 for legacy
; purposes only. By default, the module will be hidden from the UI unless you
; are upgrading a site that uses the Profile module to extend user profiles.
; See user_system_info_alter().
hidden = TRUE

It's only there to provide an upgrade path for D6 sites; it can't be enabled on a new D7 site without commenting out that line.

(The reason the module is deprecated is probably that the Fields API has taken over what it used to do, so it's obsolete.)


How to highlight location on an OpenLayers view I have a view of locations displayed with OpenLayers. The map, with plot points, is displayed in a left column, and rows of the locations are displayed in a right column.  When a user clicks on one of the locations, I want that row to highlight, and to highlight the plot point to the left.  I also want to record that location ID in the user object as a location preference.

Can I simply do this with AJAX?

OpenLayers Heatmaps module allows you to create Heatmaps layers through the Openlayers module and it don't have the views integration, but you can highlight the specified location like the below one and honestly I'm not using this before.

Features

  Provides a new kind of behavior in the OpenLayers's maps settings.
  customize the radius, intensity and opacity of each Heatmaps.


drupal 7 + services 3 - inserting nodes with select fields I'm using Drupal 7 + Services 3 to create nodes with POST and JSON. Everything works fine, except field types of select - entity reference select or plain text.

The entity reference uses the autocomplete widget, while the text select is a plain radio button.

This is the format I'm using:

"field_urgency": {
    "und": [  {  "value": 1    }   ]
}

Eventually I figured this out:

    {
    "title": "some more tests",
    "type": "weed",
    "field_sprouts": {
        "und": [ 8,9 ]
    },
    "field_urgency": {
        "en": [
            {
                "value": "2"
            }
        ]
    },
    "field_species": {
        "und": [ 4 ]
    }
 }

species and sprouts are entity references and only need the nid of the target (no value= or target_id= or anything).
For unknown reason (as of yet), the urgency field required a language to be defined (other then und[efined]). Its the only select field here with a normal select list, not entity refernce.
Make sure your widgets are select list and not auto complete.


How to add directions with a link to a webform in Drupal 7 I'm creating forms with the webform module. I'd like to add 'directions for filling out the form at the top of the form. I'd like those directions to include a link to another form if users clicked the wrong form.

This seems like it should be simple to do, but I can't figure out how to do it. When I add the directions with the link in a  and put that at the top I get the link but no paragraphs, just one long running line of text, no matter how I split it up in the editor window. If I use a  field, not only does it look ugly (even when disabled), because it has a white background on a gray background site, but it displays the link as html code etc..

I have wysiwyg enabled on my site and it shows up in other places but not on these editor windows so I can't use that (or select filtered html/full as those options also aren't available) in those data types I tried.

Anyone know a way to do this?

I'd recommend creating a custom module and using hook_form_alter() as shown in this example.

You can add a form element of type #markup to add custom html in your form. And set the #weight to a low number, -50 for instance, for your markup element to show at the top.


What is the proper way to return the results of custom module's form submission? After spending hours and hours online researching, I'm more confused than ever about something that seems like it should be a very straight-forward task - Using my module's custom form, How do I display the results of a form submission that queries the db?

Here on d.se, Clive and Kiamlaluno provide 2 approaches. Clive suggests using a multistep form, and Kiamlaluno suggests making values globally accessible by storing them in the $_SESSION variable.

Clive's approach doesn't make much sense to me. I'm not trying to print the value of a form field (after checking if it has been submitted), I'm trying to print a list of items retrieved from a database.

Kiamlaluno's approach seems a bit more workable. Indeed I could query a db, store the results in the session, and return those as the return value of a page callback on another page. Ultimately, however, this seems awfully convoluted. First, if this were indeed a best practices way, then why don't more tutorials discuss details about it? What logic would be used to set and unset the variable? PHP is horrible at handling large arrays - what if I have a large result set? How do I handle pagination if I want to divide up the result set across pages? Also, isn't the session variable available only to logged in users?

Looking at Views, Views exposed filters seem to use URL query strings. Is this the correct way? After a form submits redirect to another page, append the query string to that page, pass those parameters 'page arguments', and then query and return data in the page callback based on those arguments?

On Drupal.org there is a thread that has almost 4 years of activity from people confused about this very topic. This comment says that you have to create a $form_state['storage'] variable and "then print it in your form definition." What in the world does that mean?!?!?!?

So, I'll pose my question again. I want to query a database using a form in my custom module, and I want to return a list of results (preferably paginated).

How can I accomplish this?  I'm looking for an extremely thorough answer that I can play with in practice.

As JimaJamma noted in the comments the search module contains an excellent example of one way to do this. The search_view() function is where the magic happens, this is a custom version of that logic which should help explain the process:

function MYMODULE_menu() {
  $items['query'] = array(
    'title' => 'Query',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_results_page',
  );

  return $items;
}

function MYMODULE_results_page($parameter = NULL) {
  // Even if 'page arguments' isn't defined in a hook_menu() item, Drupal breaks
  // up the URL and passes arguments through to the callback function implicitly.
  // So if the page requested is 'query/123', out item defined at
  // 'query' will be used, and '123' will be passed as the first argument, in
  // this case into the $parameter var.
  //
  // If the parameter is empty, we need to check the GET/POST request to see if
  // the form has been submitted with a new search parameter.
  if (empty($parameter)) {
    if (!empty($_REQUEST['parameter'])) {
      // Build up a new path based on the submitted parameter.
      $path = 'query/' . $_REQUEST['parameter'];

      // And re-direct there. The request will come straight into this function
      // again, but this condition won't fire.
      drupal_goto($path);
    }
  }

  // Now we're in a position to query for results if there's a non-empty
  // parameter. Otherwise we just show the form (like the search page we'll
  // show the form unconditionally).
  $results_build = array('#markup' => '');
  foreach (MYMODULE_get_results_by_parameter($parameter) as $result) {
    $results_build[] = MYMODULE_build_result_render_array($result);
  }

  $build = array(
    'form' => drupal_get_form('MYMODULE_query_form'),
    'results' => $results_build,
  );

  return $build;
}

function MYMODULE_query_form($form, &$form_state) {
  // Make we're submitting to the right path.
  $form['#action'] = 'query';

  $form['parameter'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter query here'),
  );

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

  return $form;
}

I haven't tested that or anything so excuse any small bugs. If there are any bugs hopefully the comments, and the comments in the search_view() function, will do enough to help explain what should be happening :)


Add/Edit Taxonomy Terms directly from add content form I've hunted around for a while trying to find a solution to what I believe is a common user interface in the world of data entry but appears to be missing from Drupal.

What I want to be able to do is add/del/edit taxonomy terms for a given content type directly from the Add Content page where the terms show as a multiple select. This is often done with a multi-select box and a simple + - icon next to the multi-select that would bring up an ajax form to manipulate the taxonomy terms and then refresh the multi-select box when the ajax dialog is closed.

For example, say I have a content type for keeping track of books. Fields for Title, ISBN, etc, and a multi-select taxonomy field for book genre (drama, educational, horor, children's, etc) Ideally I want the user to be able to add genre's without having to leave the add book form to do it. I know it can be done with freetagging but then you open up the taxonomy to duplicates and misspellings and other garbage. The multiselect gives a firmer set of choices first and then allows for editing once the user has browsed the list to make sure what they want to add isn't in there already. I would settle for just adding terms from that screen but edit and delete would be nice too.

Taxonomy Other module is ALMOST what I'm looking for, except it doesn't support multi-selects. Are there other modules out there that do this? What about CCK? Any options for using CCK to achieve the same result? I'm using Drupal 6.

Take a look to the Hierarchical Select module.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.


How to check if user has passed the quiz already before granting user points? I'm awarding users points for passing a quiz successfully. However, there's nothing stopping the user taking the quiz again and again to score more points.

I have thought of these options, but I don't know how to implement them:

check if the user has achieved a certain score before awarding points
lock down the quiz for users who have already passed it, redirecting them to their results page
tagging the quiz with users ID when they complete it the first time and and denying points when they complete it again.

Any help?

Step 1 - Create a flag for tracking Passed Quizes

Use the Flag module to create a flag labeled (e.g) Passed Quizes. Here is an export of the flag I used for this (you should be able to import it in your own site also):

$flags = array();
// Exported flag: "Passed Quizes".
$flags['passed_quizes'] = array (
  'entity_type' => 'node',
  'title' => 'Passed Quizes',
  'global' => '0',
  'types' =>
  array (
    0 => 'quiz',
  ),
  'flag_short' => 'Flag this item',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Unflag this item',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
    'question' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

This flag will be used in the custom rule, detailed in the next step.

Step 2 - Create a single rule to cover all situations

Here is a rule which illustrates how to resolve the challenge in your question:

{ "rules_process_a_quiz_when_passed_the_very_first_time" : {
    "LABEL" : "Process a quiz when passed the very first time",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "rules_conditional", "flag", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT flag_flagged_node" : {
                "flag" : "passed_quizes",
                "node" : [ "quiz-result:nid" ],
                "flagging_user" : [ "site:current-user" ]
              }
            },
            "DO" : [
              { "drupal_message" : { "message" : "Congratulations, this is the FIRST time you passed this quiz (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } },
              { "flag_flagnode" : {
                  "flag" : "passed_quizes",
                  "node" : [ "quiz-result:nid" ],
                  "flagging_user" : [ "site:current-user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "Congratulations, you passed this quiz yet ANOTHER time (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } }
            ]
          }
        ]
      }
    ]
  }
}

This rule requires the Conditional Rules module to be enabled (head over to the next step for some (multiple!) alternatives which does not need this extra module).

Here are the critical pieces of this rule to make Rules-magic happen:

The very first Rules Condition, which is "the" way to get access to all sorts of data about the quiz node itself (starting from "a" quiz result).
If the quiz node (to which this quiz result relates) is not yet flagged (by the flag from Step 1), and the quiz result is that it is at leastd equal to the pass rate of that quiz, then you have your very first hit you're looking for. At which time the quiz node gets flagged.

Use the Rules UI to import the above rule in your own site, after you enabled the Conditional Rules module and completed Step 1. After you are convinced it works as designed, simply add your additional Rules Action(s) to grant the User points ... only the very first time.

Step 3 - Possible Rules variations

Some variations of the rule included in Step 2, which should also achieve a similar result:

Replace the logic implemented via the Condtional Rules module by 2 equivalent Rules Components (so that you don't need the extra module). Refer to "What's the alternative to using the Conditional Rules module?" for way more details on this.
If you DO NOT want anything to happen if the quiz was already passed before, then the "else"-part of the Conditional Rules logic is empty. In that case you could rework the remaining Conditional Rules logic to a regular Rules Condition (to be executed as the very last one). As a variation, clone such rule variation in a 2nd variation, in which you just reverse that very same Rules Condition (with Rules Action as in the "else" part of the Conditional Rules logic).

Showtime

Here is a sample of a message I received after passing a quiz:

The very first time:

  Congratulations, this is the FIRST time you passed this quiz (with a score of 80 %, whereas the pass rate is 75 %).

The next time:

  Congratulations, you passed this quiz yet ANOTHER time (with a score of 100 %, whereas the pass rate is 75 %).

PS: I'm assuming this question is about D7 ...


How to style the date module How can I style the Date Module as noted in the image below?  Which hooks/functions would be involved?

Is there a better Date input widget for Drupal 7?

I'm using Drupal 7 and the Date module is currently 7.x-2.0-alpha4.

.

I'd have to see the html, but find the class that wraps each field (the border is applied to that) and use a float left with some right margin. Find what class wraps both of them and apply overflow:hidden to that. The fields should now look like what you want.


Can't correctly reference bundle in EntityFieldQuery, field_get_items I'm using EntityFieldQuery in an attempt to query for specific field values (dates in an event db) then perform some analysis on them.

I've gotten far enough to correctly query and return specific nodes as a result but am getting stuck on field_get_items - I can't get the actual field values out. It appears I am not passing the necessary parameters of the bundle to the function.

Where am I going wrong?

Drupal throws this error on the last line of code starting w $output
"EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7734 of /home4/xxxxx/public_html/xxxxxx/xxxxxx/includes/common.inc)."

Here's my code:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_date', 'value', 'NULL', '!=');
$result = $query->execute();

if (isset($result['node'])) {
  $stories = $result['node'];

  // Get all fields attached to a given node type
  $fields = field_info_instances('node', 'event');

  // Get id of body field
  $field_id = $fields['field_date']['field_id'];

   //echo $field_id... testing, works;

  // Attach a field of selected id only to get value for it
echo field_view_field('node', $stories, 'field_date');

  //Get values of our node field
  $output = field_get_items('node', $stories, 'field_date');
}

I get an error on the last step

A couple of things...first one is you haven't loaded the nodes. If you change

$stories = $result['node'];

to

$stories = node_load_multiple(array_keys($result['node']));

You'll have the fully loaded node objects available.

The other two things are both related; field_view_field() and field_view_value() both accept a single entity; currently you're trying to pass an array, which it won't like.

A simple loop will fix that:

foreach ($stories as $story) {
  $output[] = field_view_field('node', $story, 'field_date');
}

And similar for field_get_items().


Ubercart 3.x catalog page (terms categories) theme? How to change output theme for categories page in Ubercart 3 for Drupal 7?

I not sure if you are referring to a taxonomy term page. In case if you are then please follow below mentioned steps:

Go to: admin/structure/views
Find a view called: Taxonomy term
Edit this view and add the fields as you wish
Under 'FORMAT' change to table, etc will change the overview of the taxonomy term page.

By modifying this view you will be able to change the layout, and the add more fields to the page.

Note: changing this view will change all the taxonomy term pages.


Attaching a JS library to every page I'd like to attach a javascript library to every page call. I created a directory for my module called flot_d8
I created an info file, lot_d8.info.yml. My understanding is, the libraries section should insert the javascript on every page load:

name: FLOT-D8
type: module
description: 'This module provides a wrapper to the javascript FLOT library.'
package: Misc
version: 8.x-1.0
core: 8.x
hidden: false
libraries:
  - flot_d8/flot

The library file which describes the flot asset is flot_d8.libraries.yml. I placed the flot library in drupal/modules/flot_db/flot:

flot:
  version: 1.x
  js:
    flot/jquery.flot.js: {}
  dependencies:
    - core/jquery

I enabled my module and fail to see the inclusion of jquery or foot in the header. My next attempt was to make a flot_d8.module file with a call to hook_page_attachment_alter:

<?php
function flot_d8_page_attachments_alter(array &$page) {
  // Attach the flot asset on every page.
  $page['#attached']['library'][] = 'flot_d8/flot';
}

Still no dice. Any advice? I'm wanting to begin playing around with getting the flot library working in D8. I'll eventually move the javascript attachment to occur during themeing, but I don't want to attempt that until I can even get the simplest case working.

As background. I've installed the PHP module so I can enter PHP directly into a page. If I insert the scripts and add javascript directly in the page. it works fine. This tells me the files are in the webspace and readable by the outside world:

EDIT:
I surrounded the jQuery, and still no go. I tried simplifying the problem to just try to force the inclusion of jQuery on every page load and that does not work either. I changed the module file to be

function flot_d8_page_attachments(array &$page) {
  // Attach the flot asset on every page.
  $page['#attached']['library'][] = 'core/jquery';
}

and changed the basic page to be

<?php
$jquery_already_included = TRUE;
if (!$jquery_already_included) {
  echo '';
}
?>

?>

and even that does not work.

It looks like the javascript file WERE included before, but they were in the footer. When jQuery code is placed in a basic page, that appears to not work. However, forcing the js files in the header allows everything to run.

I changed my module file to be:

<?php
function flot_d8_page_attachments(array &$page) {

 $page['#attached']['html_head'][] = [
    // The data.
    [
      // The HTML tag to add, in this case a <script> tag.
      '#tag' => 'script',
      '#attributes' => array(
        'language' => "javascript",
        'type' => "text/javascript",
        'src' => "http://test.mysite.com/core/assets/vendor/jquery/jquery.js",
      ),
      '#value' => '',
    ],
    // A key, to make it possible to recognize this HTML <HEAD> element when altering.
    'jquery-define'
  ];

  // Attach the flot asset on every page.
  $page['#attached']['html_head'][] = [
    // The data.
    [
      // The HTML tag to add, in this case a <script> tag.
      '#tag' => 'script',
      '#attributes' => array(
        'language' => "javascript",
        'type' => "text/javascript",
        'src' => "http://test.mysite.com/modules/flot_d8/flot/jquery.flot.js",
      ),
      '#value' => '',
    ],
    // A key, to make it possible to recognize this HTML <HEAD> element when altering.
    'flot-define'
  ];

}

And my Basic-Page javascript now works.


Show Author's Info in a Block How would I go about creating a block that displays the current page's author name, picture and short bio? I'm new to Drupal and don't know if this is done using a View block, custom block or by editing a block template. The block should only display if in a page or certain content type.

This will be little bit lengthy process but can be done. This you can do by Views module which is in core in Drupal 8, BUT before that you have to do some other stuff with the user account. The entire process I am listing out in steps.

Since your question is not complete clear, I am providing the method for Author Info only, if you clarify I will add the second part.

Author Info Block

Adding - Bio field & Social media profile field
Creating Views.
Add created block to appropriate place.
Block visibility setting

1. Adding - Bio field & Social media profile field

Now, the user profile setting do not provide the Bio field by default hence we need to create that one.

1.1 Go to Configuration>Account Setting>Manage field

1.2 Add new field name: Bio, field type: Long text(formatted, long)>save

1.3 Add new field Social Links: Install and enable the Social Profile Field. What this module does, this module provide the field which provide the provision for adding the social media links, The link will automatically converts to ICONS, that is the good part.

Again go to Configuration>Account Setting>Manage field and add new field Social link and for this choose field type: Social profile field. Note: The picture field is by default, which  provides by core.

The final screen shot will be looks as below,

Now, Under the user profile- Bio and Links will be added as new field so you can add this by going under Edit of any user profile.

Now, we add set to go for Views,

2. Creating Views: Author info

2.1 Go to Structure>Views.

2.2 Add new view: Author Info. Select Users in views setting. Select Create a block in Block setting. Set Unformatted list of Filed under  Block display settings. Select 1 under items per block. Click->Save and edit.

2.3 Views setting page:

2.3.1 Now add Relationship: Go under Advanced setting. under relationship click add and from the list select Content Author, give it a name Author node as shown in the following image of 2.3.4.

2.3.2 Now add contextual filter: Same as above step, click add to contextual filter. select ID. And select Provide default value. Under that select Content ID from Url. (as shown in following image)

2.3.3 Come under FIELDS and add following field: Picture(category: User), Bio(category: User), Links(category: User).

2.3.4 Remove anything which is under the FILTER CRITERIA. Save it. Your final views setting page will be looks like this,

3. Add the created block: Go to Structure>Block> and under first sidebar add this block.

4. Block visibility setting: Now, till this step, everything works fine, but these blocks are not visible to Anonymous user, And to set that, Go to Again go to views setting as shown in just above image, under BLOCK SETTING > Access click permission and select none option, and save. Now, this block will be visible to all users.

Output Image: I have reprocessed this above mentioned process in my Drupal 8 trial site and you can see in following image, with all Author info. on only page which has been authored by that author.


URL alias to access user profile as admin I realized that users on my site have their path ending in the form "user/number" (for example: user/3) when I check People in the Admin Toolbar and click on their username. I would like to use URL aliasing or some alternative that allows the path end with their username (for example: user/john_smith). How can I do this?

You can create aliases using the Pathauto module.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

There are various tutorials of this module you can watch.


How to change the field name in the url when using views exposed sort? I've read a few posts on this and there does not seem to be an answer to that, is that right?

My exposed filters allow the user to change the sorting, but the url is kinda bad:

?sort_by=field_rating instead of just ?sort_by=rating, for instance. Can this be achieved somehow? Is it advisable to try out better exposed filters module when you have already kind of customized your exposed filters? /:

For order_by filter you can just set the filter identifier:

Although there is no option to set the identifier for sort_by filter, you can achieve your goal by altering the form.

Example

/**
 * Implements hook_form_alter().
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form['#id'] == 'YOUR-FORM-ID') {

    // fields which you want to rename
    $form_state['my_custom_names'] = array(
      'field_rating_value' => 'rating'
    );

    // rename option values
    foreach ($form_state['my_custom_names'] as $name => $new_name) {

      $form['sort_by']['#options'][$new_name] = $form['sort_by']['#options'][$name];
      unset($form['sort_by']['#options'][$name]);

      if ($form_state['input']['sort_by'] == $name) {
        $form_state['input']['sort_by'] = $new_name;
      }
    }

    // the custom submit handler need to be fired before the original one
    array_unshift($form['#submit'], 'my_custom_exposed_form_submit');
  }
}

/**
 * An additional submit handler for exposed filters.
 */
function my_custom_exposed_form_submit(&$form, &$form_state) {

  // set the form state values to their original names.
  foreach ($form_state['my_custom_names'] as $name => $new_name) {
    if ($form_state['values']['sort_by'] == $new_name) {
      $form_state['values']['sort_by'] = $name;
    }
  }
}

Make sure to replace YOURMODULE and YOUR-FORM-ID with proper names.


Add text field to poll entity I have installed the Poll module in Drupal 8. I need to add a field to it, such as a text area for the poll description.

How can I add a field to a content entity like Poll, which is not a content type?

Poll is not a fieldable entity, so this is not possible in ui.

You can do this in code:

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'poll') {
    $fields['description'] = BaseFieldDefinition::create('text')
      ->setLabel(t('New discription field'))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

Apply the schema update on the database:

drush entity-updates


How do I link a page in a template? If there is a basic page with the route '/about', how can I link it in a template file?

Let assume the page is a node whose ID is 4. You can use the following code, in a template file.

About us"


How to properly use contextual filter on group content fields On my homepage, I created a view for group contents with relationship on "Group content" and "Group". I want to create a contextual filter that when I search on the exposed filter, results will be displayed on new page.

I have an exposed filter of "Category" and "Region" and without contextual filter the result displays on the same page.

I tried filtering with field "Name" as "Display a summary", and I get this:

But when I manually click on any item and check its URL, i'm getting this:

http://localhost:8888/drupal-8.2.3/home/Mozilla%20123?field_trade_type_job_target_id=All&field_region_business_target_id=All

And I can't search to other items anymore since I am on a filter specific path, in the example above, /Mozilla%20123?

I tried another field name, "Category" and I get this, since the 3 given examples are in the same category:

18 is a taxonomy path. When I manually click the content, I am directed to:

http://localhost:8888/drupal-8.2.3/home/18?field_trade_type_job_target_id=All&field_region_business_target_id=All

with this content:

This image supposed to be what I want to achieve in the first place when I click search on the exposed filter in the homepage.

Any help is greatly appreciated. Thanks!

Alright, I found the solution to my issue.

These are the steps I come up and followed.

Add taxonomy term relationship to the view.
On the Contextual filter, search "Name" with taxonomy as description
Under "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED", tick "Specify validation criteria"
Choose the desired vocabulary.
Save and test in the Preview section.


How do I add a custom validation handler to an existing form/field? How do I add a custom validation handler to an existing form (or form field) in Drupal 8?

I have a form that I haven't created. I want to add my own validation rules on some fields when the form is submitted.

For Drupal 7, Custom validation for a form? explains to implement hook_form_alter() and then add your validation handler][1] to the $form['#validate'] array, but in Drupal 8 forms are classes. Validation is done through the validateForm() method and I don't know how to plug my code into that.

Berdir gave the correct answer, that a constraint is the correct way to go about adding validation to a field in Drupal 8. Here is an example.

In the example below, I will be working with a node of type podcast, that has the single value field field_podcast_duration. The value for this field needs to be formatted as HH:MM:SS (hours, minutes and seconds).

To create a constraint, two classes need to be added. The first is the constraint definition, and the second is the constraint validator. Both of these are plugins, in the namespace of Drupal\[MODULENAME]\Plugin\Validation\Constraint.

First, the constraint definition. Note that the plugin ID is given as 'PodcastDuration', in the annotation (comment) of the class. This will be used further down.

namespace Drupal\[MODULENAME]\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that the submitted duration is of the format HH:MM:SS
 *
 * @Constraint(
 *   id = "PodcastDuration",
 *   label = @Translation("Podcast Duration", context = "Validation"),
 * )
 */
class PodcastDurationConstraint extends Constraint {

  // The message that will be shown if the format is incorrect.
  public $incorrectDurationFormat = 'The duration must be in the format HH:MM:SS or HHH:MM:SS. You provided %duration';
}

Next, we need to provide the constraint validator. This name of this class will be the class name from above, with Validator appended to it:

namespace Drupal\[MODULENAME]\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the PodcastDuration constraint.
 */
class PodcastDurationConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    // This is a single-item field so we only need to
    // validate the first item
    $item = $items->first();

    // Check that the value is in the format HH:MM:SS
    if ($item && !preg_match('/^[0-9]{1,2}:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/', $item->value)) {
      // The value is an incorrect format, so we set a 'violation'
      // aka error. The key we use for the constraint is the key
      // we set in the constraint, in this case $incorrectDurationFormat.
      $this->context->addViolation($constraint->incorrectDurationFormat, ['%duration' => $item->value]);
    }
  }
}

Finally, we need to tell Drupal to use our constraint on field_podcast_duration on the podcast node type. We do this in hook_entity_bundle_field_info_alter():

use Drupal\Core\Entity\EntityTypeInterface;

function HOOK_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if (!empty($fields['field_podcast_duration'])) {
    $fields['field_podcast_duration']->addConstraint('PodcastDuration');
  }
}


Print image from filepath in Twig I have a paragraph with an image field. If the image field is empty, I want to display a default value. I do not want to just set the default image because an editor could remove that. Here is my code so far:

{% if content.field_image|render = true %}
    {{ content.field_image }}
{% else %}
    {% include "/themes/mytheme/img/my_img.png” %}
{% endif %}

How can I get the image at that filepath to show up in the template?

For example if your default image called default_img.png inside images folder inside your theme MyTheme.

You can try the following:

implement hook_preprocess_HOOK

/**
 2. Implements hook_preprocess_HOOK().
 */
function extended_url_preprocess_paragraph(&$variables) {
  $variables['theme_path'] = drupal_get_path('theme', 'MyTheme');
}

In your twig you can do something like:

{% if content.field_image|render = true %}
    {{ content.field_image }}
{% else %}
<img src="{{ theme_path ~ directory }}/images/default_img.png"/>
{% endif %}


Any flexible customizable theme for display configuration via panels? Recently, I have been trying to design pages using panels and mini-panels. I followed some tutorial online, but the method used was a bit questionable. Since I am a newbie at this, I crashed my system beyond all repair, lol, but I managed to export valuable configuration and reload it on a fresh install. So, I am happy enough with that...

I have been playing with changing colors under Bartik, but honestly, that won't be enough...

I am looking for a flexible theme that will allows me to easily design the layout of pages from scratch using panels (most preferably). Ideally, I should be able to configure colors and fonts easily and the basic template should be simple and elegant. I want to load my own pictures to customize it (i.e., no preloaded pictures or they should be made removable).

Basically, the site is about sharing tips. Users will be able to put comments and vote for posts made by an editor. Nothing crazy.

Does anyone have a good recommendation to make for Drupal 7? Is there any such thing as a newbie-proof template? Thanks.

I still very new to the Panels module and theming in general but I have really enjoyed the Zen base theme.

I think it would have been confusing as a 'first' theme, but if you've been playing with Bartik and other common Drupal themes I think you'll love Zen.

The support, documentation and standardization surrounding the project is very impressive.

I should note though you need to be comfortable designing with CSS.  It's very 'clean' out of the box.


Image preview using views I want to Create like this type of Image preview on particular related images. I have image fields with multiple images for a content type, and I would like to obtain this effect.

Is there any possibility by creating views? Is there any way to obtain this effect with other ways?

Modules You Need:

Views
Libraries
Views Slideshow
Cycle JS : Save this js file to /sites/all/libraries/jquery.cycle/ where you have to create 2 directories i.e.  libraries and under that jquery.cycle

Now assuming your content type name is IMAGE with two fields

Title
Image

Add 3 dummy images to your newly created content type IMAGE
Now go to admin/structure/views/import
$view = new view();
$view->name = 'slideshow';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Slideshow';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Slideshow';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'slideshow';
$handler->display->display_options['style_options']['slideshow_type'] = 'views_slideshow_cycle';
$handler->display->display_options['style_options']['slideshow_skin'] = 'default';
$handler->display->display_options['style_options']['skin_info'] = array(
  'class' => 'default',
  'name' => 'Default',
  'module' => 'views_slideshow',
  'path' => '',
  'stylesheets' => array(),
);
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['enable'] = 1;
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['type'] = 'views_slideshow_pager_fields';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_pager']['views_slideshow_pager_fields_fields'] = array(
  'field_image' => 'field_image',
  'field_image_1' => 0,
);
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_controls']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_controls']['type'] = 'views_slideshow_controls_text';
$handler->display->display_options['style_options']['widgets']['top']['views_slideshow_slide_counter']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['type'] = 'views_slideshow_pager_fields';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_pager']['views_slideshow_pager_fields_fields'] = array(
  'field_image' => 0,
  'field_image_1' => 0,
);
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_controls']['weight'] = '1';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_controls']['type'] = 'views_slideshow_controls_text';
$handler->display->display_options['style_options']['widgets']['bottom']['views_slideshow_slide_counter']['weight'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['timeout'] = '5000';
$handler->display->display_options['style_options']['views_slideshow_cycle']['speed'] = '700';
$handler->display->display_options['style_options']['views_slideshow_cycle']['delay'] = '0';
$handler->display->display_options['style_options']['views_slideshow_cycle']['start_paused'] = 0;
$handler->display->display_options['style_options']['views_slideshow_cycle']['remember_slide_days'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['items_per_slide'] = '1';
$handler->display->display_options['style_options']['views_slideshow_cycle']['wait_for_image_load_timeout'] = '3000';
$handler->display->display_options['style_options']['views_slideshow_cycle']['cleartype'] = 0;
$handler->display->display_options['style_options']['views_slideshow_cycle']['cleartypenobg'] = 0;
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_image']['delta_offset'] = '0';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image_1']['id'] = 'field_image_1';
$handler->display->display_options['fields']['field_image_1']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image_1']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image_1']['label'] = '';
$handler->display->display_options['fields']['field_image_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image_1']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image_1']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image_1']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_image_1']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'image' => 'image',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'slideshow';

Simply go to your-site/slideshow and Voilà! Feel free to comment if you got stuck or need my help.


Adding a radio button to a Drupal View page Does anyone know how to 'inject' a radio button onto a Drupal View page?

I have an exposed filter that has nothing to do with a radio button but I want to add a radio button in front of the label in order to apply some additional AJAX to it.

Use HTML <form>, ex: w3schools.com/html/tryit.asp?filename=tryhtml_form_radio

To "inject" your code you could add a header text field to your view OR create a template file for your view.


How to manage version control for patched contrib modules? I got some great feedback regarding patching contrib modules.

Is there a good way to keep track of patches to contrib modules?
For example, let's say I create a patch for a contrib module and submit the patch to the issue queue.

A month goes by, a new version of the module has been released (without my patch) and I get notified to update to the next version.
If I keep my patch file in the module directory I think it will get wiped out when I do the automatic upgrade?

Should I move the module from sites/all/modules to sites/default/modules to prevent automatic updates?

Does anyone have a good system?

Use Drush Make. It's built into Drush 5. Your makefile will serve as not only documentation of what patches you're using, but documentation of what versions of everything you're using, where to download external libraries, it's practically guaranteed to be up to date, and it means you no longer have to store contrib and external code in your source code repository. Just your custom code.

Basically, you create a file that tells Drush Make what version of core to download, which contrib modules and themes to download, which external libraries to download, where to place them (you can separate contrib modules to a "contrib" subdirectory, for instance), which patches to apply (to all of those).

Drush Makefiles are used to build Drupal distributions.

Have a look at a pretty simple makefile from Discursive, and a more terse makefile from OpenOutreach.

EDIT: I really should include a link to at least one makefile that uses a bunch of patches and a much better example of using Drush Make on a client project: WiseDecider (check the makefiles in that install profile directory, then also go up a directory to find the rebuild.sh script that "builds" it -- downloads, patches, etc. the site and sets up symlinks and such to glue everything together. Also a disclosure: Wise Decider is a client of the Drupal shop I work for and Discursive is the open-source version of another client project of ours.

EDIT 2: Don't use any kind of "automatic updates" with this method. The process is:

Update your makefile locally
Rebuild the site by rerunning the build script
Test on your local instance of the site against a new dump of the production database (don't forget drush updb)
Deploy the updated codebase to your testing/staging server (don't forget drush updb) for internal QA / client QA (if applicable)
Redeploy the updated codebase to production (and again, don't forget to run the db update scripts).

Our deployment scripts (included in Wise Decider) use rsync and symlinks to pushing code to the remote LAMP server.


Force new articles to have tags (term + subterm) associated with it previous question

I have a site where articles need to be classified as, apple, banana, cranberry, etc....

Each category has sub-cats like apple - 1, apple - 2, ... banana - 1, banana - 2 ...

Now apples can have 10 subs and banana can have 200 or something like that.

I already make a vocabulary using taxonomy of all the terms and subterms.

What I need to do is have it so that users submit articles and it must have a category and sub-cat associated with it.

I want to do it this way so that I can have an index page of all apple articles, or just apple - 1, or banana - 2's ... etc.

What you are seeking to do is very basic and one of the early things you learn how to do in Drupal.  The simplest way to answer your question is to recommend you get a book such as Drupal 7 by Tom Geller or any of the other introductory Drupal books. Lynda.com also has a video series that can fill you in on how to use Drupal.  You can accomplish want you seek by modifying or creating a content type and adding field s linked to taxonomy terms. You can make it a requirement to add a value for each new entry.  Eventually you will want to master the Views module to find your content and display it.

Before you start working on the design of a site, yuo may want to spend some time studing Drupal basics. Drupal has a steep learning curve in the beginning and you will have to cover a lot of ground before it starts clicking and you will feel confident diving into a project.


Images not shown in View Mode Teaser I have a content type teaser with an image field and display these teaser in a panel layout. This works perfect if I choose the Build Mode "Full Content" in the Panel Settings for the content.

I themed the content type with a node template (node--xyz.tpl.php) and have no checks about the view_mode in it. I print out the image with the function render():

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

I'm very confused, as I wrote above, with the Build Mode "Full Content" it works fine. I've checked the Manage Displays Settings and they are the same for both View Modes. The Variable in the render() function is filled in both cases, but in View Mode "Teaser", the output is empty.

Check http://YOUR_SITE.NAME/admin/structure/types/manage/YOUR_CONTENT_TYPE/display/teaser

You have to add field_teaser_image to visible fields list.

Field UI module must be active.


What is the value of $page['content'] in custom front page? I'm a Drupal noob and inherited a Drupal website to maintain. The site has a custom theme, which includes a "page--front.tpl.php" that Drupal loads as the front page. Within this script, there is the following call:

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

This call used to display homepage-view.tpl.php (found under themes//), but I upgraded some modules and changed some settings in an attempt to fix some problems and now it appears to be showing all nodes, (there is a pager for /node?page=X in the section rendered by that print statement).

My guess is that $page['content'] is returning /node. Either /node pointed to homepage--view.tpl.php before or $page['content'] returned the value of homepage--view.tpl.php. Either way, how can I get the old behavior back?

Thanks in advance.

$page[content] returns the content for the current page, whatever that may be.  If a view is set at the content, it would return the view, or a node, or a block in the content region or anything else set to show in that region, either through the UI or programmatically. It returns rendered html for all elements in that region.

Chances are under blocks, that view? is no longer listed to render in the main content region as a result of whatever setting changes you made.

If it's a view and set as a block you can modify it under the blocks page, block configuration to show in the region.


How do I allow full HTML while rendering a view? Some HTML code like <iframe> is stripped out. How can I allow full HTML in a view?

    $options = array(
        'id' => 'area_text_custom',
        'table' => 'views',
        'field' => 'area_text_custom',
        'relationship' => 'none',
        'group_type' => 'none',
        'admin_label' => '',
        'empty' => TRUE,
        'tokenize' => FALSE,
        'content' => "My HTML Code with <iframe ... >",
        'plugin_id' => 'text_custom',

    );
    $view->setHandler('page_1', 'footer', 'area_text_custom', $options);

I would suggest having your view display "content" of type "teaser" which would then allow you to use a twig template file such as node--content-type--teaser.html.twig.

This way you can add whatever markup you want to the twig file... even iFrames.

If you must have fields, for instance in exposed filters combine, remember you can "force" use fields in views :)


Views results diplay modes I have a view with its filters exposed. when someone searches for any content results are shown perfectly in list view . now wat i want is a link showing grid view of the same result. more apecific i want a result to be in 2 modes  1) list view and another one is the grid view.

You can do this by creating two different display of same view. If your current view display is page at path like /view/list-view then create another page display of same view with path like /view/grid-view. Then Configure that display as Grid view under views Format settings. You can use that path to create link to that view later anywhere you want.


Exclude node title in bulk Is there a way to exclude titles in bulk? I want to exclude title of several nodes all at once.

I'm using Exclude Node Title to remove node titles to the display. However, I can only edit it one by one by opening and editing each nodes.

What I want is to update nodes by bulk if possible.

Thanks!

override the node template and remove title from there.


Theming login page--user--login.tpl.php I'm trying to theme the login user page and it seems that I'm missing something and I can't figure out what it is.

here is what I did:

I've added this code to my template.php:

 function mxblog_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'mxblog') . '/templates',
  'template' => 'page--user--login',
  'preprocess functions' => array(
  'mxblog_preprocess_user_login'
  ),
 );
return $items;
}

and this that I'm trying to render in the page--user--login.tpl.php

   print drupal_render($form['name']);
    print drupal_render($form['pass']);

    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);

When using page--user--login.tpl.php you have to manually fetch the user login form, as your overriding the entire page template not just the form.

You can either include this directly in the template (along with any other markup):

print drupal_render(drupal_get_form('user_login'));

Or in your mxblog_preprocess_user_login() function must return the form:

function mxblog_preprocess_user_login(&$variables){
  $variables['form'] = drupal_get_form('user_login');
}

then in the template you should be able to to do as you want:

print drupal_render($form['name']);
print drupal_render($form['pass']);
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
print drupal_render($form['actions']);


Copying a site to a multi-site installation On Server A (debian) drupal was installed by the package manager. So basically the codebase is at: /usr/share/drupal7 with /usr/share/drupal7/sites symlinking to /etc/drupal/7/sites.

Server B has basically the same setup (ubuntu).

The multi-site feature is configured like that: At /etc/drupal/7 we have a apache.conf:

Alias /site1 /usr/share/drupal7
Alias /site2 /usr/share/drupal7

<Directory /usr/share/drupal7/>
        Options +FollowSymLinks
        AllowOverride All
        order allow,deny
        allow from all
</Directory>

I copied the Site from A to B. In A it was installed at /sites/default so I copied it to /sites/default at B. The index page (www.foo.com/drupal7) is redirected to /sites/default. So basically it works.

But if I go to e.g. www.foo.com/drupal7/members I get:
404: The requested URL /usr/share/drupal7/index.php was not found on this server.

Also: If I want a multisite like www.foo.com/site1 I create it at /sites/foo.com.site1

Question 1: How can I confiure it so it works on / rather than on /drupal7? So basically I'd like to use this site "normal" on /sites/default but another site at /sites/site1.

Question 2: How can I fix the 404 error?

How can I confiure it so it works on / rather than on /drupal7

This has to do with your Apache VirtualHost. It probably is pointing to /usr/share/ instead of to /usr/share/drupal7. So in order to access the content in the drupal7 folder, you need to add the folder to the url.

  Question 2: How can I fix the 404 error?

Relating to:

  But if I go to e.g. www.foo.com/drupal7/members I get: 404: The requested URL /usr/share/drupal7/index.php was not found on this server.

The first thing is figuring out if there is an index.php file there. If so, does it have the correct permissions?

It seems to be an Apache error, not a Drupal error at this point. ;)


How to redirect from confirmation page back to page of form? Is it possible to have a form redirect the user after landing on the confirmation page back to the previous page (page of the form)?

Note: I'm using Webform for D8

I have written the code for d7 where the article node form once submitted it is redirected back to the form.
    It will help you for d8.
    /**
     * Defines hook_form_alter()
     */
    function demo_form_alter(&$form, $form_state, $form_id) {
        if (strstr($form_id, 'article_node_form')) {
          $form['actions']['submit']['#submit'] = array('demo_form_submit');
        }
    }
    // custom submit handler for '_node_form'
    function demo_form_submit($form, &$form_state) {
      // call default action
      node_form_submit($form, $form_state);
      $form_state['redirect'] = url('node/' . 'add' . '/article', array(
          'absolute' => TRUE
        )
      );

      $_GET['destination'] = $form_state['redirect'];
    }


Filtered HTML Text format without an editor How can I set up the following:

Administrator should be able to use Full HTML with an editor window in Nodes.
Users should be able to use Filtered HTML in Nodes without an editor - just the markup.
Everybody should be able to use Filtered HTML in comments via markup - no editor.

First you create your two text formats (if not already present).

Then you can use the wysiwyg module (http://drupal.org/project/wysiwyg) to display an editor for the Full HTML text format (on /admin/config/content/wysiwyg). wysiwyg will only display editors that you have set up properly (usually by placing a third party library in sites/all/libraries)

You can limit use of the text formats via the permission settings.


Rate widget in panels not working I'm using the votingapi and rate modules but I have some issues with those modules and panels.

I'm using panels to render the node view. I added content using node > Rate widget. Everything looks fine viewing the node, even if I use the rate widget in the node.

The problem comes when I refresh the page. The rating is not anymore in the widget. That's weird because the value of the rating is stored in the votingapi_vote table, even if I show the widget using views it displays the correct rating, but not with panels.

What I'm doing wrong? Thanks!

I just found the answer. The problem occurs when the option "Use source translation" is checked in the Rate configuration section. Here is a patch to solve the problem source translation option on untranslated nodes causes 0 votes display


How would I wrap (or hard-code) HTML into a block title? So I see this in the block.tpl.php:

/**
* @file
* Default theme implementation to display a block.
*
* Available variables:
* - $block->subject: Block title.
* - $content: Block content.
* - $block->module: Module that generated the block.
* - $block->delta: An ID for the block, unique within each module.
* - $block->region: The block region embedding the current block.
* - $classes: String of classes that can be used to style contextually through
*   CSS. It can be manipulated through the variable $classes_array from
*   preprocess functions. The default values can be one or more of the
*   following:
*   - block: The current template type, i.e., "theming hook".
*   - block-[module]: The module generating the block. For example, the user
*     module is responsible for handling the default user navigation block. In
*     that case the class would be 'block-user'.
* - $title_prefix (array): An array containing additional output populated by
*   modules, intended to be displayed in front of the main title tag that
*   appears in the template.
* - $title_suffix (array): An array containing additional output populated by
*   modules, intended to be displayed after the main title tag that appears in
*   the template.
*

I'm trying to set the $title_prefix & $title_suffix in my hook_block_view without much luck...

Here is the working version of what I have:

/**
* Implements hook_block_view().
*/
function activities_block_view($delta = '') {
 switch ($delta) {
   case 'find_activities_small':
     $block['subject'] = t('Find Activities');
     $block['content'] = drupal_get_form('find_activities_form');
     return $block;
     break;
 }
}

You can hard code in block template: "Drupal 7 Template Suggestions", so determine what module/delta/region appropriate for you.
Other way is using theme preprocessor.


How to hide/remove "Request New password" link in Drupal 7? I am using 'Login Block' to access Intranet pages from our website. I used 'Login Block' on www.example.com/common-intra
 page to login into intranet section.

I am using userprotect module to hide profile/username/password information from the users when they logged in into Intranet section (www.example.com/common-intra) with universal account.

But, I wanted to hide/remove "Request New password" link from Intranet Login page:

I found this module, haven't used yet though:
https://www.drupal.org/project/noreqnewpass

Is there any other easy way to just hide "Request New password" link from that Intranet Login page?

I still want this tab on general login page such as:
www.example.com/user
 But, I just want to hide it from the www.example.com/common-intra page.

I also tried to hide it with css.

This is my page source code:

        <form action="/common-login?destination=node/16" method="post" id="user-login-form" accept-charset="UTF-8">

      Username *

     <input type="text" id="edit-name" name="name" value="" size="15" maxlength="60" class="form-text required" />

  Password *

 <input type="password" id="edit-pass" name="pass" size="15" maxlength="128" class="form-text required" />

Request new password

<input type="hidden" name="form_build_id" value="form-_xyzabc" />

<input type="submit" id="edit-submit" name="op" value="Log in" class="form-submit" />

</form>

I gave class name 'common-intra' to user login block to my node template.

.common-intra ul li{
    display: none;
}

I also tried:

.panel-pane pane-block pane-user-login common-intra pane-user common_login_button ul li
    {
          display: none;
    }

this will remove it from the render array before it is printed. In your theme's template.php, add:

function MYTHEME_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'user_login_block')
    {
        $form['links']['#markup'] = '

Create new account

';
    }
}

Basically, it is just rewriting the markup for the links in the user login block. You can tweak this to theme as well. this should only apply to the user block


User uid incrementing in non sequential manner I have a drupal site that has been running for about 1 year. there are about 1000 members in the users table

recently I have noticed something very strange the Users uid field is no longer inrementing sequentially.

It now jumps up in the 10s, for example, my last 8 users, the uids went from 7999 to 8068, 8094, 8350, 8416, 8458, 8534, 8566.

So sometimes it is jumping 100s at a time.

How can I work out what might be causing this, and should I be worried?

If it is exactly 10 then it might have to do with MySQL's Auto Increment value
https://stackoverflow.com/questions/1686327/change-the-step-auto-increment-fields-increment-by

drupal.org currently uses this feature for master slave replication. Right now all users and nodes being created have a odd value. If you look further back this value was EVEN at one point.


Why does this route work with a slash and not a dash? I have defined a custom dynamic route that works, but isn't ideal:

/**
* Defines dynamic routes.
*/
class GuideUnitRoutes {

  /**
   * {@inheritdoc}
   */
  public function routes() {
    $route_collection = new RouteCollection();

    $route = new Route(
      "/guide_name/{guide_id}/{child}",
      [
        '_controller' => '\Drupal\guides\Controller\GuidesUnitController::view',
        '_title' => 'Hello',
      ],
      [
        'guide_id' => '\\w+',
        'child' => '\\w+',
        '_permission' => 'access content',
      ]
    );

    $route_collection->add("guide.child", $route);

    $route_collection->setMethods(['GET']);

    return $route_collection;
  }

}

If I define it to be ideal, it stops working:

/**
* Defines dynamic routes.
*/
class GuideUnitRoutes {

  /**
   * {@inheritdoc}
   */
  public function routes() {
    $route_collection = new RouteCollection();

    $route = new Route(
      "/guide_name-{guide_id}/{child}",
      [
        '_controller' => '\Drupal\guides\Controller\GuidesUnitController::view',
        '_title' => 'Hello',
      ],
      [
        'guide_id' => '\\w+',
        'child' => '\\w+',
        '_permission' => 'access content',
      ]
    );

    $route_collection->add("guide.child", $route);

    $route_collection->setMethods(['GET']);

    return $route_collection;
  }

}

The route that works is guide_name/foo/bar while guide_name-foo/bar doesn't work. I would like to know why.

Reading the Symfony docs it looks like this should be a problem. But for some reason Drupal isn't liking this. Is there an undocumented (or maybe a document that I missed) that forces tokens to be delimitated with /. right now if I change the - to a / and reload the same route it works.

The dash is not the problem, you could use a dash in the fixed part, but ...

  Unlike generic Symfony routes, Drupal requires that a slug occupies a
  complete path part - the portion between two slashes (or everything
  after the last slash).

https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes

Alternatively you can use path processing to rewrite the path to comply with the Drupal routing system. See Do new routes in Drupal 8 *require* a static first portion?


How to override subtheme settings (inheritance)? I am having some difficulty overwriting my subtheme code using my own theme.css file (located in sites>all>themes). I can find the code that results in the display of whichever css style property I'm trying to change (e.g., font-family in the header region) easily, using the chrome DevTool, but when I go to target that area in my own css file it seems not to have any effect on the display. Is there any general methodology with which I can go about inheriting my adjustments to the theme styles? FYI I have renamed my subtheme's files so that is not the issue.

Any help would be wonderful.

Assuming you've cleared the cache and all that before trying to inspect any changes, it sounds like your base theme (the theme you've based your sub-theme on) is one of those themes where the configuration is for a large part done by means of the administrative interface. This means that edits done to the .css fileshave no effect, as they're overridden by settings the administrative interface.

A number of popular themes has this property, including the Adaptive Themes family and Omega 3.

To check out if this is the case, navigate to Administration » Appearance » Settings for your theme (or sub-theme).  If there is a lot of settings for fonts, etc., hacking the .css files will not help much and you need to use the administrative interface for styling.


how to stop annoymous users to login in drupal In wordpress, I have been disabling unknown people from accessing my wp-login.php using a script in the .htaccess.

RewriteCond %{REMOTE_ADDR} !^154\.70\.159\.2
RewriteRule ^wp-(login|register)\.php http://www.example.com [R,L]
RewriteRule ^wp-(admin)\.php http://www.example.com [R,L]

Meaning only the user with that above IP will b allowed to Login.

How can I do this with Drupal, so that I redirect unknown user with different IP to my homepage. Those who try to visit the www.example.com/user link.

There is the restrict by IP module, which can solve the use-case pretty fast. For the second part, depending on if you are in 7 or 8, you would want to write code to handle a request to either of the routes, evaluate the allowed IPs against the user IP, and do a redirect. Would be easier and more manageable vs the htaccess route, in my opinion.

You can disable user registration by disabling it in the admin (only admins can create accounts).

Furthermore, no one can even get to /admin or administrative pages without the right permissions anyway, so if they are not logged in, it isn't really an issue. That just leaves the login and forgot password page. Forcing a redirect within admin paths might also interfere with things like AJAX actions as well - I would probably leave that alone.


How do I insert a localized menu item? When writing a custom module, what is the proper way to insert a localized menu via hook_menu or hook_menu_alter? By localized I mean not only the translated label - that'd be done using the t() function on title - but also having localized path and page callback.

I tried something like this:

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

  switch($language->language){
  case 'en':
    $items[] = array(
      'title' => 'Contact Us',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/285'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  case 'pl':
    $items[] = array(
      'title' => 'Kontakt',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/286'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  }
  return $items;
}

but this is not behaving properly - once created, the menu item stick at the original language regardless of subsequent language negotiations. So what is the way to go?

Edit after trying out the code provided in answers
OK, so I approached that topic afresh and tried out all of the three methods suggested below. The two programmatic methods have the culprit that the array key used to install the menu item (as in: $items['corporate/contact-us']) will display in the status bar on hover, regardless of the language chosen. This is cosmetic but I consider it a bad UX. The third - UI-based - method has a side-effect (which is not the point of the original question) but was tried out just for curiosity. The point of my question was - whether it was possible to install a localized menu item totally programatically, and get exact result as when done through UI. Looks like this is not quite possible, unless there's a piece of know-how that I'm missing.

The array returned from hook_menu() is cached, and each implementation of hook_menu() is only invoked when the cache is cleared, which what happens, for example, when a module is disabled/enabled.

If the users are redirected to a different node depending on the currently set language, then the code should be similar to the following one.

function mymodule_menu() {
  $item['mymodule_path'] = array(
    'title' => 'Contact Us',
    'page callback' => 'mymodule_redirect',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_redirect() {
  global $language;

  switch ($language->language) {
    case 'en':
      $goto = 'node/285';
      break;

    case 'pl':
      $goto = 'node/286';
      break;

    // ...
  }

  if (isset($goto)) {
    drupal_goto($goto);
  }
}

The alternative would be:

Create a link through the user interface (admin/structure/menu/manage/main-menu/add)

Use the following code to alter where the link takes

function mymodule_menu_link_alter(&$item) {
  if ($item['module'] == 'menu' && $item['link_title'] == t('Contact us')) {
    $item['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$item, $map) {
  global $language;

  if ($item['module'] == 'menu' && $item['link_title'] == t('Contact us')) {
    switch ($language->language) {
      case 'pl':
        $item['link_path'] = 'node/286';
        break;

      // ...
    }
  }
}

The first hook is necessary, or hook_translated_menu_link_alter() is not invoked.

The module could also programmatically add the link to the main menu. In this case, the code I would implement is similar to the following one.

function mymodule_enable() {
  $item = array(
    'link_path' => 'node/285',
    'link_title' => t('Contact us'),
    'menu_name' => 'main-menu',
    'mlid' => 0,
    'plid' => 0,
    'module' => 'mymodule',
  );

  menu_link_save($item);
}

function mymodule_menu_link_alter(&$item) {
  if ($item['module'] == 'mymodule' && $item['link_title'] == t('Contact us')) {
    $item['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$item, $map) {
  global $language;

  if ($item['module'] == 'mymodule' && $item['link_title'] == t('Contact us')) {
    switch ($language->language) {
      case 'pl':
        $item['link_path'] = 'node/286';
        break;

      // ...
    }
  }
}


Change file path of aggregated CSS file path How do I go about changing the file path of the aggregated CSS file paths?

As most of you know, when using the Drupal option (from admin/config/development/performance) to 'Aggregate and compress CSS files' Drupal creates different CSS files that look something like this:

My issue is that my site visitors are always seeing the cached (old) version of my stylesheet when they visit my site. Of course I always want them to see the newest version, but I also want to optimize my website as well as possible.

Back to my original question. Is there any way to change the path that looks like gibberish (first example starts with "791YXB.....") ? I've gone through several of the questions here, but I can't find an exact answer for this.

Just for reference, this is how my performance options are setup:

After making changes to my CSS files I also always click the button to 'Clear all caches'.

Not the answer you're looking for but it does solve the problem you're having (old css); try the Advanced CSS/JS Aggregation module.