EVA + Corresponding Node References + Views + Sort by Order of Appearance on Page Node

Ok, I think I figured this out after some ideas I got while researching kalabro's answer. Basically I needed a better understanding of the logic of how EVA works with node references and related objects in views. So here's what I did --

First I changed the contextual filter in my view to "Content: Nid" with a default value of "Content ID from URL". Next I added a relationship to the field "Related Org" (which is the node reference field in my County content type) and did not check "require this relationship. Then I filtered my results to only include County content types and added the "Related Org" relationship to the title and body of my included fields -- except for the first title field (the related county itself) which I used to group the related organization by. Finally, I removed all sort criteria from the table settings and from the sort section.

Here's a screen shot of my views set-up: http://www.diigo.com/item/image/16wo5/7chr

Here's a screen shot of my county view: http://www.diigo.com/item/image/16wo5/r1dx

After thinking about this problem some more I'm not sure that I actually needed to create the corresponding node reference in order to accomplish this. I haven't tested it yet. Also, there may still be some tweaks to this set-up that don't show up because of my limited testing. Still, I feel like I'm on the right path now with a better understanding of how EVA, node references, contexts and relationships work together in views. And I am definitely left with a greater appreciation of the power of Drupal 7.

If anyone wants more details about my set-up please let me know.

Thanks to kalabro for helping me to get started thinking in a different direction.

-Scott


Add theme_hook_suggestions only for nodes in content

I would recommend you override the default term page with a view, and then theme it like you are doing for your other view.
All you have to do is create a view with that same path (taxonomy/term/%) and it will override the default page.

There is even a view already configured for this purpose, you just have to enable it.

On the views listing admin page it is called "Taxonomy term". Just enable and configure this view and then you can override it's themeing.


Added fields are not displaying while creating the user

this is a similar questions on Drupal answers. I would remove this one as i considered duplicated.

Adding fields to user registration form


Where to find structure of objects that I can access in PHP snippets added to different parts of UI?

You can install the devel module and use the dpm function to check it out.
You can check the whole list of devel functions at http://ratatosk.net/drupal/tutorials/debugging-drupal.html


drush migrate:upgrade not behaving as expected

I figured it out!

I just needed to run drush migrate:rollback. That put Drupal back into a state where it understood that the migrations hadn't actually been run yet.


How to add a custom widget to a node creation form Drupal 6

I'd take a look at two modules, the base level Hierarchical Select module and its Hierarchical Select Node Reference submodule.  The second module allows you to create "on the fly" a node referenced by the parent node being created and may do what you need without custom coding on your part.


Disable welcome message for specific roles but keep for others, user_mail_notify

I kind of stumbled on this after nobody answered my question. (I was desperate)

The solutions is to:

Edit your welcome email, under Account Settings.
Enable Mail Control and disable the welcome email. This content is saved  in the database, so don't worry about losing anything.
Create a new Rule to react on a new event: After saving a new user account
Add in your condition: User has Role && User is being Notified.
Under Actions: Send Account E-mail.
Under E-mail Type: Choose Welcome E-mail.
Save! Clear Cache! Get More Coffee!


Question regarding hook_user_presave() and setting roles

The documentation for hook_user_presave() says the hook is invoked when an user account is updated, or created, not just when the user account is updated.

If you look at user_save(), you will notice that $account->is_new is set before invoking hook_user_presave(), when the user account is being created. If the account is being updated, $account->is_new is not set, and $account->original contains the user object before any changes.

In Drupal 8, $user->is_new will be replaced with Entity::isNew().


JQuery Accordion closes unintended when ajax-link from inside gets response

You can probably use one of the jQuery Accordion API functions to manually control the state of the accordion

e.g:

// getter
var active = $( ".selector" ).accordion( "option", "active" );
// setter
$( ".selector" ).accordion( "option", "active", 2 );

more info here


Relevant Content Module Custom/Overwirete Theme

You are the themer. In your theme, copy that function, but call it YOURTHEME_relevant_content_block. Now change the function to output whatever you want it to.


How do I redirect in a class sub-classing the EventSubscriber class?

To catch a 404 exception you need to subscribe to a KernelEvents::EXCEPTION event. As there is already a base class for html exceptions you don't need to code this yourself. You can simply put the code in an on404() method of a class that extends HttpExceptionSubscriberBase:

  Utility base class for exception subscribers.

  A subscriber may extend this class and implement getHandledFormats()
  to indicate which request formats it will respond to. Then implement
  an on*() method for any error code (HTTP response code) that should be
  handled. For example, to handle 404 Not Found messages add a method:

  public function on404(GetResponseForExceptionEvent $event) {}

  That method should then call $event->setResponse() to set the response
  object for the exception. Alternatively, it may opt not to do so and
  then other listeners will have the opportunity to handle the
  exception.


Possible to alter user account status options on user_register_form?

Finished working through the implications of this and have confirmed it is not possible to alter the user_status fields through Drupal without causing other complications through other modules -- the 0/1 logic for users is too ingrained in core to overcome.

I've addressed the requirement through a number of other Drupal hooks that work alongside the user module, will be releasing user_reopen module shortly to community.


Ok I've managed to solve it myself.

For anyone that is interested my Render Array now looks like this.

    return array(
        '#slides' => $slides,
        '#theme' => 'slider_block',
        '#attached' => array(
            'js' => array(
                array('data' => array('word' => 'world'), 'type' => 'setting'),
                drupal_get_path('module', 'single_slider') . '/js/tes.js'
            ),
        )
    );

And my Javascript file (test.js) now looks like this.

(function($)
{
    //console.log(Drupal.settings.word) //This won't work and will return with undefined.
    $(function()
    {
        alert('Hello ' + Drupal.settings.word);
    });
}(jQuery));


I believe this was due to the user logging in as http://example.com and then trying to access a link (from an email) to http://www.example.com/page-that-requires-a-login. In addition the user had a bad browser-memorized password for http://www.example.com, though his password for http://example.com was good. This apparently caused an odd loop of login failures.

I have uncommented the Drupal-supplied redirects in .htaccess that force all http://www.example.com URL's to redirect to http://example.com versions, and have told all my users they may need to re-memorize their passwords in the browser.


i have prepared form api, now how to insert form values when i click submit button by using db_insert

You would need to add a custom form submit handler.

$form['#submit'][] = 'mymodule_custom_form_submit';

Then, in the function, use $form_state['values'];

function mymodule_custom_form_submit($form, $form_state){
    db_insert('yourtable')
        ->fields(array(
            'totp' => $form_state['values']['totp'],
            'pd' => $form_state['values']['pd']
          ))
        ->execute();
}


I think there is a typo.

Just replace

'#theme' => 'theme_args',

with

'#theme' => 'item_list',

There is no theme called "theme_args".


On you link display something like this :

$current_path = current_path();
$current_path_alias = drupal_get_path_alias($current_path);
print url('my-webform', array('query' => array('from' => $current_path_alias )));

If you are on content/mynode, the link will display my-webform?from=content/mynode.
If you want just the unaliased path skip the use of dupal_get_path_alias()

$current_path = current_path();
print url('my-webform', array('query' => array('from' => $current_path)));

If you are on node/18, the link will display my-webform?from=node/18.


attributes is a variable containing attributes information (class, id, others..) for the main container of the template.
It should usually be used only once.
You can create a new attribute variable like this :
{% set my_attribute = create_attribute() %}|
And you can use it as usual :
<div{{ my_attribute.addClass(image_classes).setAttribute('data-type', 'image') }}>
  {{ content.field_two_column_image }}
</div>

More information about using the attributes variable in Twig templates :
https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21Attribute.php/class/Attribute/8.2.x


I don't think Real Name does what you think it does.  At least not by default.  The module is primarily for using parts of the user account other than the username when the user account is displayed (such as the by-line on an article).

You can set the edit link to send people to mysite.org/user/my-real-name/edit but unless you've done something to make that URL exist, which I'm not sure you can do with this module, it won't do anything.


Is comment fields data store in render array?

The render array for a node contains also the content of the comments, which is added by comment_node_view(), an implementation of hook_node_view(). That hook is invoked from node_build_content(), which is called from node_view().

The Devel module shows the following output for a node render array.

In Drupal 8, node_view() is a thin wrapper for entity_view(), which renders the node using entity_render_controller().


Set a different home page for each role?

I haven't tried this exact scenario, but I just did a quick check user roles and permissions are options in the selection rule when making pages with the Panels module.


Any module/theme hosted on Drupal.org is licensed under the GPL License v2+, which allows you to edit them, as long as you respect the license itself.

You can edit out that string. Even if you were distributing your version, you should distribute the source code too, which is the theme itself, as PHP is not compiled. You should not remove the attributions left in the comments from the previous author, though.


Your entity-relationship model is likely going to map to what we call 'Content types' in Drupal.

Content types are defined using the Content Construction Kit module, commonly referred to as CCK.

With CCK, you point-and-click to define what fields you want the content type to have - text fields, numbers, links, references to other content types, references to users in your Drupal site.

With the content types defined, you can figure out what kind of lists for that content you want - tabular, blog-style, etc, and use the Views module to create that listing.  Views is a point-and-click query builder, complete with sorting, filtering, access control, dynamic URL arguments, and relationships (think joins) to other content types.

That's typically how 'databases' are done in Drupal - but you don't have to do anything with the database at all, really.

If you've got a really specific use case that can't be solved with some combination of the 7000 or so contributed Drupal modules, then it might be time to grab a copy of 'Pro Drupal Development' and learn module development to integrate your custom module into the rest of Drupal to meet your exact need.


The data table shold look like this:

 $data = array
    (
        array("Volvo",22,18),
        array("BMW",15,13),
        array("Saab",5,2),
        array("Land Rover",17,15)
    );

And whole working example will look like this:

function hoook_export_excel() {
    module_load_include('inc', 'phpexcel');
    $data = array();
    $headers = array();
    // First worksheet
    // Get the nodes
    $data = array
    (
        array("Volvo",22,18),
        array("BMW",15,13),
        array("Saab",5,2),
        array("Land Rover",17,15)
    );

    $headers = array("CAR","COUNT1","COUNT2");

    // Store the file in sites/default/files
    $dir = file_stream_wrapper_get_instance_by_uri('public://')->realpath();
    $filename = 'export1.xls';
    $path = "$dir/$filename";
    // Use the .xls format
    $options = array('format' => 'xls');
    $result = phpexcel_export($headers, $data, $path, $options);
    if ($result == PHPEXCEL_SUCCESS) {
        drupal_set_message(t("Ok"));
    }
    else {
        drupal_set_message(t("Error"), 'error');
    }
}

This will return Excel:


There is no need to add wilcard placeholders after your last path element. Anything tacked onto the end of the URL will be passed to the callback as arguments automatically.

If the example you give above, if someone goes to $title/arbitrary/arguments, then 'arbitrary' and 'arguments' will be passed as arguments to your page callback:

programs_page('arbitrary', 'arguments');

If you want arguments in the middle of your path, you can specify them with a % sign, or if you would like to automatically load and pass an object to your page callback, you can use wildcard loaders.


How do I enable comments for user profiles?

You can use Profile2, that attach node to user profile, so it can be commented and will look as commenting to user.


alter the exposed form , make field hidden and accept it through node form field

Yes its possible we do it like this

 function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "views_exposed_form"){
        $formId1 = "views-exposed-form-view-name-block-2";
        if($form_state['view']->name == "view_name"){
            if($form['#id'] == formId1){
                $form_state['input']['field_name'] = $value_field_name;     //set value
                $form['field_field_name']['#default_value'] = $value;//set default value
                $form['field_field_name']['#value'] = $value;//set the field value
            }
        }
    }
}


PHPUnit testing a method that changes an entity field

You can't do that in a unit test, you have to work with real entities in a functional test since $entity->save(); needs the database to be loaded.
And as $result = $this->service->changeEntityField($entity); will return an entity there's no way $result can be equal to 10 or 20. It will be equal to an entity. But in a functional test you'll be able to load the entity and check if the field has the good value or not after your function has been called.


How to disable picture button after click?

The link needs a slash in front of it:

/user/login

instead of:

user/login

Logout would be:

/user/logout

You need to use relative paths or you will continue encountering this behavior. A better way would be to send the variables to your template(s) via the appropriate preprocess function, and use the l() function to create links.


Is it reasonable to run hundreds of sites by one Drupal core?

Technically, there shouldn't be. But even if I had enough server resources, I'd reconsider my approach. A few problems I can think about. Note that they are really small annoyances and there are workarounds. If each site of your network has to be a very serious site, and all you are expecting is less files on the server and ease of updates, I think it's a bad idea.

Your sites.php file will get larger. You can specify which settings.php file should be used in the sites/sites.php file. That file will get larger with the number of sites in your network. However, in a age that you store 100 configurations in $GLOBALS, this shouldn't be a problem.
Your modules page will load slower if you put all modules in sites/all/modules folder, but only want to use them in a few sites.
In core or shared module updates, make one wrong move and everyone will know.
You can't use different robots.txt.
In fact, you can't use just about any "known files". favicon.ico, apple-touch-icon, Bing verification file, oh gosh.
Say hello to the complicated vhosts file and .htaccess for me. I'm a fat guy and so they should be.


How do I allow both kg and lbs units for a field

Create two fields, one for number, second for unit. Optionally put them in a field  collection.

Then, add Computed field that will use both values for computation and store the result the way you need it. For best flexibility, you might want to create two of them, ie field_real_kg and field_real_lbs.

  computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields


How do I customize a table display with views

In order to do this I handled everything on the views-view-unformatted-{view_name}.tpl.php level.

I am not sure if it is the most efficient way of doing all of the work, but it works like a charm. If anyone has any suggestions on how to optimize the code, or if I should be putting this work in the template.php file please let me know, but as it stands this answered and solved my problem.

/* Issue:         In order to accomodate the appropriate style requirements of
 *               this view we need to override with this file and handle the $rows
 *               in the following format. The standard Table Format for Views
 *               does not provide what we want (refer to Description to understand
 *               what we wanted).
* Description:   Overriding the views-view-unformatted...tpl.php file so we can
 *               better control view page. This View displays
 *               all the Employee Titles. Which is fine, but we want it in a
 *               particular format:
 *  (headers)                  A                 B                 C
 *  (titles)              App Specialist   Batch Processor   C.........
 *                        App Developer    B..........       C.........
 *
 *
 * ==========================================================================
*/
?>
<?php
    /*
     Lets grab and collate all of the Employee Titles and the the headers for
     each set of Employee Titles (Example of a set = all titles that start
     with 'A', or 'B', etc.
    */

    // Employee Titles.
    $titles = array();
    // Employee Title Headers.
    $title_headers = array();
    // Keep track of the character we are on.
    $first_character = '';
    // Keep track of the last character we were on.
    $last_character = '';
    // Header count for the iteration process.
    $head_count = 0;
    // Title count for the iteration process.
    $title_count = 0;

    foreach ($rows as $row) {
      $employee_title = strip_tags($row); //strip
      $employee_title_trimmed = trim($employee_title); //trim
      $first_character = $employee_title_trimmed[0];

      // We don't have the character saved.
      if ($last_character != $first_character) {
        // Increase count.
        $head_count++;
        $title_count++;
        // Fill the headers array.
        $title_headers[$head_count] = $first_character; // add the letter
        $last_character = $first_character; // update the last character
      }
      // Fill the employee title's array
      $titles[$title_count][] = array($employee_title_trimmed => $row);
    }

    /* Time to display the header and title arrays. */
    // We only want 3 columns, so that's what this variable ensures. if we
    // wanted 4 or 2 columns we just change this variable and it will take effect
    // throughout.
    $columns_limit = 3;
    // counter for the employee title headers.
    $count_header = 1;
    // Max counter for the headers.
    $max_count_header = $count_header + $columns_limit;
    // Counter for the employee titles.
    $count_list = 1;
    // Max counter for titles.
    $max_count_list = $count_list + $columns_limit;

    print("
");
    while($count_header < sizeOf($titles)){ //never exceed size of titles
      print"
"; // Header row starts.
      // Display 3 or less headers, depending on where we are in the array.
      for ($count_header; $count_header < $max_count_header; $count_header++){
        print "";
        print $title_headers[$count_header]; // Display header.
        print "	";
      }
      print"
"; // Header row stops
      print"
"; // Employee title row starts
      for ($count_list; $count_list < $max_count_list; $count_list++) {
        print'';
        print"
";
        foreach ($titles[$count_list] as $titles) {
          $title_value = array_values($titles);
          $title_entry = $title_value[0];
          print"
";
          print $title_entry; // Display the employee title.
          print"
";
        }
        print"
";
        print"	";
      }
      print"
"; // Employee title row stops.
      $max_count_header = $count_header + $columns_limit; // Update Header's Max
      $max_count_list = $count_list + $columns_limit;     // Update Employee's Max
    }
    print("
");


How to check node table for entry by current date before inserting new node?

This should do the trick:

Make a module and insert following code, switch "foo" with your module name.

    /**
    * Implements hook_node_presave($node).
    */
    function foo_node_presave($node) {
      // Lets search for nodes on the current date.
      $somedate = strtotime(date('Y-m-d'));

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node');
      $query->propertyCondition('created', $somedate, '>=');
      $query->propertyCondition('created', $somedate + (60 * 60 * 24), '<');
      $result = $query->execute();

      if (!empty($result)) {
        node_delete_multiple(array_keys($result['node']));
      }
    }

Obviously you might want to do some additional checks before deleting the nodes:

// Nodes of the same type
$query->propertyCondition('type', $node->type);

//Only delete published nodes
$query->propertyCondition('status', 1);


Currently only files coming from a HTTP(s) source are supported in the D8 version of Feeds. So the sources for the files need to look like this:

http://www.example.com/myfile.jpg
http://www.example.com/myfile.pdf
https://www.example.com/myfile.jpg
https://www.example.com/myfile.pdf

Adding support for local file paths is planned:
https://www.drupal.org/project/feeds/issues/2968671
See also other file target related issues:
https://www.drupal.org/project/issues/search?issue_tags=Feeds%20file%20target


Content creation screen: Add another field conditionally

You may want to take a look at the Hierarchical Select module. It provides this kind of functionality for vocabularies.


Assuming this is about D7, here is a blueprint of just another idea (as in your bullet item "4"):

Create a single node for each number, of content type (say "Golden Coin"), so  10x10 = 100 of such nodes.
Use the Views module to display a 10x10 grid of those 100 nodes, and link each of them to there corresponding node.
Use the Flag module for authorized users to "flag" such nodes, to indicate "reserve this one".
Use the Rules module to make the remaining magic happen, using Rules Events such as "When such node is flagged", with Rules Actions such as "Create appropriate notifications (eg towards the admin)".
Repeat the above for "Silver Coin", or add an extra field to the Flag you'll be using, to select between "Silver" and "Gold".


The problem was due to the PHP version being used. It seems that Drupal 6 has some problems with PHP 5.4.


An instruction how to do this can be found on:
http://purewebmedia.biz/article/2014/08/01/create-multi-layer-map-drupal-7-openlayers-2x


How to add a class to the webform error message

I think the short answer is no, since the errors set in the error message box could come from any source, meaning the errors in that <div> aren't necessarily just your webform errors. Since it looks like you're using your webform as a block I'm guessing you can't target a body class to check if you're on a particular page type either.

If you were setting your own error messages you could add a <span> around the message with your custom class, but that would mean bypassing the validation handling webforms provide.

One possible solution would be to use JavaScript to find <li> elements that have text matching the error messages you want to style and moving them to a custom container. Another could be creating a YOURTHEMENAME_status_messages() function in your theme's template.php and doing a regular expression or string comparison to output specific error messages in a separate container. This route would affect all error message using the same text though, so it could affect an error message that was not from your webform.


If there aren't modules that avoid the redirection happens, the only case the redirection from user/logout to the front page doesn't happen is when the user is already logged out. user/logout is defined as the following, in user_menu().

  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );

When a menu is accessed from the users, Drupal first calls the access callback; if the access callback returns TRUE, then Drupal calls the page callback. In this case, the redirection is done from the page callback, which is never called when the user is logged out. (In that case, user_is_logged_in() returns FALSE.)

For a page like user/logout, the login block is not shown. In fact, user_block_view() contains the following code, used to render the login block.

  // For usability's sake, avoid showing two login forms on one page.
  if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
    $block['subject'] = t('User login');
    $block['content'] = drupal_get_form('user_login_block');
  }
  return $block;

What you can do is implementing hook_block_view_MODULE_DELTA_alter() to show the login block also on user/logout, in the case the redirection to the front page doesn't happen for any reason.

function mymodule_block_view_user_login_alter(&$data, $block) {
  if (!$GLOBALS['user']->uid && $_GET['q'] == 'user/logout') {
    $data['subject'] = t('User login');
    $data['content'] = drupal_get_form('user_login_block');
  }
}


How do I create a year-only drop-down field?

The Year Only module provides this feature by defining a new field type.

.

It comes with a range configuration.

It produces the following result in the entity (node, ...) edit form. Configured with unlimited number of values in this example.


You either need to make your aliases not language specific (you can only do that in the alias administration page right now, not in the node edit form) or you need to create one for each language.

If the alias shows up for all languages, make sure you made the path field translatable in the content translation settings, maybe something doesn't work correctly otherwise.

See https://www.drupal.org/node/2775275 for an issue to allow language-unspecific aliases. You could also use tokens to get the original language with pathauto to work around it.


Above menu is rendered from toolbar.tpl.php inside toolbar module.

All you need to is override above toolbar.tpl.php by copying it to your themes folder and modify code to add image.

<?php

/**
 * @file
 * Default template for admin toolbar.
 *
 * Available variables:
 * - $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 value has the following:
 *   - toolbar: The current template type, i.e., "theming hook".
 * - $toolbar['toolbar_user']: User account / logout links.
 * - $toolbar['toolbar_menu']: Top level management menu links.
 * - $toolbar['toolbar_drawer']: A place for extended toolbar content.
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_toolbar()
 *
 * @ingroup themeable
 */
?>
<div id="toolbar" class="<?php print $classes; ?> clearfix">

    <?php print render($toolbar['toolbar_home']); ?>
    <?php print render($toolbar['toolbar_user']); ?>
    <?php print render($toolbar['toolbar_menu']); ?>
    <?php

    $variables = array(
      'path' => 'path/to/img.jpg',
      'alt' => 'Test alt',
      'title' => 'Test title',
      'width' => '5px',
      'height' => '5px',
      'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
      print theme_image($variables)?>
    <?php if ($toolbar['toolbar_drawer']):?>
      <?php print render($toolbar['toolbar_toggle']); ?>
    <?php endif; ?>

  <div class="<?php echo $toolbar['toolbar_drawer_classes']; ?>">
    <?php print render($toolbar['toolbar_drawer']); ?>


How can a module detect when the "access denied" page is output?

You can set which pages are displayed when 403 & 404 errors occurs (admin/settings/error-reporting).

I guess you can add a new page in your hook_menu(), then set this page as the 403 error callback. When your custom menu callback is hit, you know you're outputting the "access denied" page!


How to list all the user's "member for" via "Views"?

This is quite easy to achieve. Simply add the user's created field to your view, then change the field formatter for this to Time ago.


Assuming that you really want to groups with "Title" and those with "Choose one of:" to look the same, you can achieve that quite easily with nested paragraphs.

Something like a "Semester" paragraph type with a paragraph field called "Course groups", and a "Course group" paragraph type that has "Title" + Course lists. Then the title for the optional groups would simply be "Choose one of".

If you need different markup/output, you could handle that either with an "Optional/Select one" checkbox that you can check in a template or by defining two separate paragraph types and allowing both on the nested paragraph field, e.g. "Required course group", "Choose-one-of course group" paragraph types.

Or any other similar combination of nested paragraph types, whatever you need exactly.


Should I declare the usage of a new template.php file?

Drupal 8 themes don't have template.php files. Now they use a mytheme.theme file, which needs to be located inside the directory containing the theme. (Replace mytheme with the machine name used by the theme.)
Preprocessing and modifying attributes in a .theme file shows an example of preprocess function, which is placed in the mytheme.theme file, instead of the template.php file.


Managing featured content the drupal way

If your goal is to make a simple workflow for your clients, you have to take into account your clients' general ability to use the Web.  What is easy for one client may be very difficult for another, so it's hard to say which workflow is superior.  For example, when I set up a Drupal website for a CS professor, very little customization was required; on the other hand, when I set up Drupal for my grandfather, I had to do a lot of workflow customization to remove options and simplify things.

As far as easily allowing content to be "Featured," I usually set it up with Flags.  This is a pain to set up but is very simple for end users.  Basically, you have a flag for each section you want to feature.  This flag should allow you to flag nodes of the content type you want to feature.  Then you create a rule using the Rules module that trims the flag to 1; this means that only one piece of content can have the flag at any given time (assuming you only want to flag one piece of content per section).  Then users with the appropriate permissions can simply flag the content that they wish to feature and it will automatically be featured.  Advanced users probably don't need this, but for users with limited computer skills it may be helpful.

As for your concerns about excessive markup, Drupal in general generates lots of wasteful markup.  There are solutions like the Fences module and Semantic Views to try to slim it down, but in general I would not worry about this; you would have to have a huge amount of traffic before the time you spent trying to slim down the markup paid off.


drupal 7 get title token without anchor tag

I solved this issue. As described below :

We can use fields as token only whose we selected a block field.

I have selected title as block field with link to content node. so it was taking title anchor as token. I have removed tick for  "Link to node" option from title field settings.

Now it's working fine.


How can a module check if Drupal is showing one of the update pages?

devel.module has a function called devel_silent() that does some very comprehensive checking. I might replicate this in your own module.

function devel_silent() {
  // isset($_GET['q']) is needed when calling the front page. q is not set.
  // Don't interfere with private files/images.
  return
    function_exists('drupal_is_cli') && drupal_is_cli() ||
    (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'ApacheBench') !== FALSE) ||
    !empty($_REQUEST['XDEBUG_PROFILE']) ||
    isset($GLOBALS['devel_shutdown']) ||
    strstr($_SERVER['PHP_SELF'], 'update.php') ||
    (isset($_GET['q']) && (
      in_array($_GET['q'], array( 'admin/content/node-settings/rebuild')) ||
      substr($_GET['q'], 0, strlen('system/files')) == 'system/files' ||
      substr($_GET['q'], 0, strlen('batch')) == 'batch' ||
      substr($_GET['q'], 0, strlen('file/ajax')) == 'file/ajax')
    );
}

You can probably simplify this a bit to just the part that is checking for 'update.php' and the $_GET['q'] checking.

    strstr($_SERVER['PHP_SELF'], 'update.php') ||
    (isset($_GET['q']) && (
      in_array($_GET['q'], array( 'admin/content/node-settings/rebuild')) ||
      substr($_GET['q'], 0, strlen('system/files')) == 'system/files' ||
      substr($_GET['q'], 0, strlen('batch')) == 'batch' ||
      substr($_GET['q'], 0, strlen('file/ajax')) == 'file/ajax')
    );


You can do that with Firebug or any other browser that has a console. You need to go to edit page of the WYSIWYG profile and on this page, open Firebug or your browser's web developer tool. And in the console enter this line and run:

jQuery('#edit-buttons input.form-checkbox').attr('checked', 'checked');

This will set all the checkboxes under 'Edit buttons' section and you can save your setings.


Adding PHP function code to a node returns Eval error

You can try adding declaration of the function in your module.
But call it using php filter.

Moreover, in this case you will be able to edit code of your function with less chance of break the site.


Render block programmatically in Drupal 8 returns 0

For display only your block in your templates with preprocess the best way is

$block = Block::load('my_block_id');
$variables['My_region'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

And in your page.html.twig or node.html.twig or xxx.html.twig use your variable My_region like this :

{% if page.My_region %}
    {{ page.My_region }}
{% endif %}

And in rendable array (custom module) by exemple into an controller custom in content():

public function content() {
    $block = Block::load('my_block_id');
    $block_content = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($block);

          return array(
            '#type' => 'container',
            '#attributes' => array(
            'class' => array("Myclass"),
          ),
           "element-content" => $block_content,
           '#weight' => 0,
  );
}

drupal_render is not usefull drupal already assume the render in D8 and this is deprecated (https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_render/8)

it's a bit heavy, it is better to use the maximum area system and does not add load block from the preprocess. In the case of using a controller in your modules this seems a justified use.


How can I always have the node title display on top of a background image?

There is several ways to solve this

1 make your own module

to do what you described

2 add theme templates

for each content type as you described

3 Use background_image module

The module is available for Drupal 8 promises to do just this (I meant to use it but have not actually)

According to the the project description provides a way to insert token values

  Token - Provides a way to view which tokens are available to use when
  adding overlay text for a background image.

So you can probably use it with a field token to accomplish what you need


Drush uses a different php.ini than the web server does.  The phpinfo() you are looking at above is from your web server's php.ini.  Run drush status to see the path to the php.ini that Drush is using.  Then, compare the two and copy directives from the web server php.ini, such as the directives that enable the CURL PHP extension and memory_limit, and put them in Drush's cli php.ini.  Then everything should work fine.


How to define Views filters and relationships for custom Civicrm contact fields that are indexed via Search API?

If this is about getting Membership fields showing in the ADD RELATED FIELDS selector at the bottom of admin/config/search/search_api/index//fields then I expect this is a civicrm entity issue in which case you could check at this chat channel

Otherwise you may be looking for sites/all/modules/civicrm/drupal/modules/views


RuntimeException: Unable to determine class for field type found in the configuration

One possible way is that your module is missing from the codebase or has been improperly uninstalled and you've still a field which is using that missing module.

Try the following drush/SQL commands to remove the broken field:

drush sqlq "DELETE FROM cache_config"
drush sqlq "DELETE FROM config WHERE name = 'field.storage.xxx.xxx' OR data LIKE '%field.storage.xxx.xxx%'"
drush sqlq "DELETE FROM config_snapshot  WHERE name = 'field.storage.xxx.xxx' OR data LIKE '%field.storage.xxx.xxx%'"

Warning: Don't execute above commands on master/live database. Make a backup before doing any database changes.

Where field.storage.xxx.xxx is your reported field storage type (e.g. field.storage.node.webform).

If above won't help, check for any other references by:

drush sql-dump --ordered-dump | grep field.storage.xxx.xxx

At the end you need to rebuild your caches:

drush cr


How can I add a custom form to the output of a controller class?

I think you want to return a render array, instead of markup. Because the from needs to stay as a render array, your best bet it to bring your content content to the same format instead of the other way. In your example:

public function processSingle($nid) {
  $build = [];
  $build['heading'] = [
    '#type' => 'markup',
    '#markup' => '
' . $this->t('My custom Form Is below but there will be alot more html than just the form. So this is just an example.') . '
',
  ];
  $build['form'] = $this->formBuilder()->getForm('Drupal\my_module\Form\MyFormClassGoesHere', $nid);
  return $build;
}


Drupal 7 Rules - Set value of multiple value reference field (user reference)

Install next modules:

Conditional Rules
Rules Bonus Pack

Create a rule for "Content is viewed".
Set conditions , like "content is type"
Create a loop and set its name, in the data selector choose the field(not the deltas) like [node:field-alumnos-curso]
Create an action inside the loop(do not "set data value"), just select "add item to the list" and the value will be the list name or loop name.
Remember create a action "Save an entity".


Force profile2 field display based on current user's role

Try implementing hook_profile2_view_alter(). Below is a sample code:

/**
 * Implements hook_profile2_view_alter().
 */
function example_profile2_view_alter(&$build) {
  global $user;
  $rid = <advance_user_role_id>;

  if (!array_key_exists($rid, $user->roles)) {

    $advance_fields = array(); // List of field ID's that should only be displayed
                               // for advance users.

    foreach (element_children($build) as $id) {
      if (in_array($id, $advance_fields)) {
        $build[$id]['#access'] = FALSE;
      }
    }
  }
}


How to add a form to $node in hook_node_load()?

Not entirely sure why hook_node_load does not work, but some trial and error (in contrast to the documentation) led me to a working solution using hook_node_view instead.

The example code being:

function gp_shop_node_view($node, $view_mode, $langcode) {
  if ("product" == $node->type) {
    if ($view_mode == 'full' && node_is_page($node)) {
      $node->content['gp_shop_order_button'] = drupal_get_form("gp_shop_order_button", $node);
      }
    }
  }
}

function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

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

  return $form;
}


Where are these modules - "Views Slideshow: SingleFrame" & "Views Slideshow:ThumbnailHover"?

They are packed with the Views Slideshow module.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


how to check if javascript is enabled in a module drupal7

I don't think there is a way. Because your module runs on the server and it cannot interact with the client's browser in any way.

Here's an answer on stackoverflow: Check if JavaScript is enabled with PHP


How to get value from URL in a view block using contextual filter?

Assume your article is located at node/nid (with nid the id of the node of the article), then configure your contextual filter like so:

  When the filter value is not available: Provide a default value with Type = "Content ID from URL" (that value should correspond to the nid of your article).


How to handle large select lists in content types?

Sounds like a perfect job for Simple hierarchical select

Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
The widget is available in node forms and as Views exposed filter.

You can add your locations as a hierarchical taxonomy, and SHS will AJAX-load child terms into a new inline select, then children of those in a new select, and so on. Something like


How to submit a field collection from a form into a created node

You need the id of the field collection item (grand one) which you can find inside the node object. Then you load the field collection by that id as an entity. Edit this field collection and save it as an entity. The point is that you have to load the field collectin entity, make changes and save it.


Show all values for a field collection in node.tpl.php

/**
 * @Show all field collection values from node object
 *  Example field collection name: "field_helloworld"
 *  Example fields within a field collection:
 *  - field_title       (string)
 *  - field_image       (image)
 *  - field_description (string)
 */

// get field collections from node
$field_helloworld = field_get_items('node', $node, 'field_helloworld');

// get all fields values if collection exists
if (!empty($field_helloworld)){
    $field = field_view_value('node',$node, 'field_helloworld', $field_helloworld[0]);
    foreach ($field['entity']['field_collection_item'] as $id => $field_collection){

        // load the field collection item entity
        $field_collection_item = field_collection_item_load($id);
        // wrap the entity and make it easier to get the values of fields
        $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

        // all values from a field collection
        $field_title        = $field_wrapper->field_title->value();
        $field_image        = $field_wrapper->field_image->value(); // an array of image data
        $field_description  = $field_wrapper->field_description->value();

        // an example of getting image url from field_image
        $image_url          = $field_image['uri'] ? file_create_url($field_image['uri']) : '';
    }
}

Notice that there is no ['und']['0'][value].


Different way for users to add content on pages

Yes. You can use the built in content types and the default 'node' page which allows this for just the front page or if you want more complex uses with multiple pages you will need something like views and a custom content type with a taxonomy term to tie the content pages to the view.


If you want to make a View of node teasers, all you have to do is set the view format to Rendered Content, and select the teaser display mode.

From here, you can customize node--node-type--teaser.html.twig template to your exact specifications to satisfy phplist.

After this change, all the nodes that the View returns will be rendered in the teaser display mode using that template.

You can also create new modes under Admin > Structure > Display Modes if you want to create new ones for this purpose, especially if you are already using teaser display mode elsewhere on the site. You can still provide the markup and theme it with the pattern node--node-type--display-mode.html.twig.

If for some reason this is not enough, you may have to resort to creating a custom Views plugin to render your result rows. I think this should suffice based on what you asked, though.


Drupal 6 Form fields not displaying if nested too deep.

So I found out why its not working, very simple mistake on my part. I was declaring            $form['goals_fieldset']['goal_'.$gid]['recommendations'] later in the form, erasing everything else. Sorry for wasting time!


Is it possible in Drupal Commerce to have 2 price fields according to role?

Are you looking to have a different price depending on the role of the user? If you want to have a price based on user role then the Commerce Pricelist module can help with that.

From the module list

  Different prices for different roles or individual users

  Different prices for different quantities

  Different prices based on order date (like a time-limited discount)


How to enter text in a fieldset's summary?

See vertical_tabs_example_form_alter(), there it's written:

  Vertical tabs provide its most usable appearance when they are used to
  include a summary of the information contained in the fieldset. To do
  this, we attach additional JavaScript to handle changing the summary
  when form settings are changed.

  '#attached' => array(
    'js' => array(
      'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
    ),
  ),

In vertical_tabs_example.js it then goes on like so:

  Use the fieldset class to identify the vertical tab element. Depending
  on the checkbox status, the settings will be customized, so update the
  summary with the custom setting textfield string or a use a default
  string.

$('fieldset#edit-vertical-tabs-example', context).drupalSetSummary(function (context) {
  if ($('#edit-vertical-tabs-example-enabled', context).attr('checked')) {
    return Drupal.checkPlain($('#edit-vertical-tabs-example-custom-setting', context).val());
  }
  else {
    return Drupal.t('Using default');
  }
});


You could use a preprocess functions in your theme for this. You can add preprocess in your template.php.

function mytheme_preprocess_textfield(&$vars) { // OR preprocess_field.

  $vars['#attributes']['class'][] = 'test' ;
}

Check the $vars parameter for values that may help you determine the logic. For examples, just search your code base for preprocess_textfield or preprocess_field. For more inf


How to limit drush tar-options="--exclude pattern matching to be specific and not recursive

I've found that you can use the current working directory, as the starting point, to force relative urls. It was a matter of getting the syntax correct.

For example if you have your site root in public_html, and you are in that location cd ~/public_html, you can use drush:

[user public_html]$ drush ard tar-options="--exclude=public_html/images" --destination=~/.backups/[date].tar.gz

The key is to navigate to that starting point root folder first.

For example, if your site root was in a subdirectory subdirectory/siteone,
 go to that location first cd ~/subdirectory/siteone
and then use drush:

[user siteone]$ drush ard tar-options="--exclude= siteone/images" --destination=~/.backups/[date].tar.gz


The update.php doesn't want to run it's complete course

Happened to me too. One update took a lot of memory on my shared host. I tried it several times during the Day until I got Lucky.  Maybe a glance in the Apache log Files will help?


How to embed fields from a view to another view´s exposed filter

I think you made a mistake in the foreach loop:

foreach ($my_value as $key => $result) { //trying to assing results to $key
}
foreach ($links as $tid => $term_name) {
if (taxonomy_term_depth_get_by_tid($tid) == 1) {
   $newlinks[] = array('data' => '' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '', 'class' => array('pop-filter-label'));
}

should be something like

$view_results = array_keys($my_value);
foreach ($links as $tid => $term_name) {
  if (taxonomy_term_depth_get_by_tid($tid) == 1) {
    $key = each($view_results);
    $newlinks[] = array('data' => '' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '', 'class' => array('pop-filter-label'));
  }
}


Reorder the Basic page list in views .How?

In Drupal 7 you use VIEWS SORT CRITERIA

If you want to sort based of Content: Post date OR Content: Updated date just use these fields in VIEWS SORT CRITERIA.
If you want to sort based on your requirement then, just add one more extra field to basic page like weight.

Edit your VIEW and just add this field in the Views SORT CRITERIA and sort is as per
your requirement.


Add html widget programmatically to the list “Add fields” in views in Drupal 7

This documentation will help you, just add a field handler then you are done! Click here


Load a page with only the form, no drupal theme/element around

I know it's possible to have a Controller action return raw HTML, by returning a Symfony\Component\HttpFoundation\Response object with the html string as an argument. IE

namespace Drupal\my_module\MyController;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

class MyController extends ControllerBase {
  public function content() {
    $markup = '
Behold my markup!
';
    return new Response($markup);
  }
}

If that's what you are going for, you could hard code the form instead of using the drupal form api. It does mean abandoning the functionality of the form api as well though - you are basically creating a route to a plain html page.


Easiest method for conditional fields in a form

The magic is using the #ahah/#ajax property with form elements, that way you can define what should trigger the modification and what should be modified as a result, plus it integrates seamlessly with jQuery.

This is the important part from the example below:

'#ajax' => array(
    'event' => 'change',
    'callback' => 'myajax_ajax_callback',
    'wrapper' => 'dropdown_second_replace',
),

Here is an example that shows a form-based page with two dropdowns: the list of options in the second dropdown depend on the selection in the first dropdown.

<?php

/**
 * Implementation of hook_menu().
 * Registers a form-based page that you can access at "http://localhost/myajax"
 */
function myajax_menu(){
    return array(
        'myajax' => array(
            'title' => 'A page to test ajax',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('myajax_page'),
            'access arguments' => array('access content'),
        )
    );
}

/**
 * A form with a dropdown whose options are dependent on a
 * choice made in a previous dropdown.
 *
 * On changing the first dropdown, the options in the second are updated.
 */
function myajax_page($form, &$form_state) {
    // Get the list of options to populate the first dropdown.
    $options_first = myajax_first_dropdown_options();

    // If we have a value for the first dropdown from $form_state['values'] we use
    // this both as the default value for the first dropdown and also as a
    // parameter to pass to the function that retrieves the options for the
    // second dropdown.
    $value_dropdown_first = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

    $form['dropdown_first'] = array(
        '#type' => 'select',
        '#title' => 'First Dropdown',
        '#options' => $options_first,
        '#default_value' => $value_dropdown_first,

        // Bind an ajax callback to the change event (which is the default for the
        // select form type) of the first dropdown. It will replace the second
        // dropdown when rebuilt
        '#ajax' => array(
            // When 'event' occurs, Drupal will perform an ajax request in the
            // background. Usually the default value is sufficient (eg. change for
            // select elements), but valid values include any jQuery event,
            // most notably 'mousedown', 'blur', and 'submit'.
            'event' => 'change',
            'callback' => 'myajax_ajax_callback',
            'wrapper' => 'dropdown_second_replace',
        ),
    );
    $form['dropdown_second'] = array(
        '#type' => 'select',
        '#title' => 'Second Dropdown',
        // The entire enclosing div created here gets replaced when dropdown_first
        // is changed.
        '#prefix' => '
',
        '#suffix' => '
',
        // when the form is rebuilt during ajax processing, the $value_dropdown_first variable
        // will now have the new value and so the options will change
        '#options' => myajax_second_dropdown_options($value_dropdown_first),
        '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    );
    return $form;
}

/**
 * Selects just the second dropdown to be returned for re-rendering
 *
 * Since the controlling logic for populating the form is in the form builder
 * function, all we do here is select the element and return it to be updated.
 *
 * @return renderable array (the second dropdown)
 */
function myajax_ajax_callback($form, $form_state) {
    return $form['dropdown_second'];
}

/**
 * Helper function to populate the first dropdown. This would normally be
 * pulling data from the database.
 *
 * @return array of options
 */
function myajax_first_dropdown_options() {
    return array(
        'colors' => 'Names of colors',
        'cities' => 'Names of cities',
        'animals' => 'Names of animals',
    );
}

/**
 * Helper function to populate the second dropdown. This would normally be
 * pulling data from the database.
 *
 * @param key. This will determine which set of options is returned.
 *
 * @return array of options
 */
function myajax_second_dropdown_options($key = '') {
    $options = array(
        'colors' => array(
            'red' => 'Red',
            'green' => 'Green',
            'blue' => 'Blue'
        ),
        'cities' => array(
            'paris' => 'Paris, France',
            'tokyo' => 'Tokyo, Japan',
            'newyork' => 'New York, US'
        ),
        'animals' => array(
            'dog' => 'Dog',
            'cat' => 'Cat',
            'bird' => 'Bird'
        ),
    );
    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}


You can allow your users to filter the view data by "exposing" your filters. See screenshot:


D7 - field_update_instance requiring manual refresh after node save to view new values

the theme function occurs towards the end of the page request lifecyle in the theme layer of a drupal request.

Whereas, the field_update_instance call is updating the database values for this Node's promotion image. The node is already loaded and being used as variables within in the theme at this time. When you refresh the page you're requesting the Node from the database again -- which is "refreshing" the data.


Why we go for template files and why we go for theme function?

I always think of it like this:

If you need to write a fair bit of HTML for your theme then you want a template file. This way you can maintain as much separation HTML and PHP as you'd like.

If you theme is just accepting data and putting that data through (say) another theme function, then you're not going to be writing any/much HTML. In this case a theme_* function is more appropriate in my opinion.

I don't think there really is an "all time best way", both methods are appropriate for different situations.


Access By Term(abt) is not work in SOLR search Drupal 7

I have found a solution. If the Solr server want to obey node access means, we must index the Status and Author field to the server. I have done this, now the node access is perfectly worked even with the search also.


Node that current_path() returns the URL path of the current page, not the URL. So on the http://www.example.com/latest-deals page it will return just latest-deals.

If you need to convert that to an actual URL, use url(current_path()), which will return /latest-deals. Or url(current_path(), array('absolute' => TRUE)) if you need the absolute URL.


Programmatic filefield value/Default Filefield value

The new version of the file should be saved as a managed file. This will provide a file object that has a fid which in turn can be used by the file field.

Here are the docs for the function used to save a managed file.

https://api.drupal.org/api/drupal/includes%21file.inc/function/file_save_data/7

The value for a file field contains the following

fid - The fid property of the file object returned by file_save_data.

description - The description may be used as the label of the link to the file.

display - Determines whether a file should be displayed when outputting field content.


Drupal 8 Link Autocomplete Filter by Bundle

You can now use the following contributed module to solve the issue:

Link Field Autocomplete Filter

  This module adds a Link Field configuration for filtering the allowed
  content types in the autocomplete field.


You need to use tokens and custom CSS in the view.  Takes a little fiddling to get it perfect, because Drupal throws in a bit of it's XHTML.


Drupal #attached doesn't work with some themes

The example code you are giving indicates, that you want to have this CSS included on every page. In this case do not bother using #attached at all and just call drupal_add_css from hook_page_build. An even better option is to include the CSS in the module-info file with the following line:

stylesheets[all][] = css/mymodule_default.css

In contrast if the asset is to be added to the page only when a given element is rendered (e.g. a form), then use #attached on that element. This way the path to the asset gets stored along with the render-array if the element is cacheable. On subsequent page requests, the element will be retrieved from the cache and the asset is attached to the page. If you would use drupal_add_css together with cacheable elements, the asset would be missing on subsequent page builds.

Note that even when using #attached, drupal_add_css is called internally from within drupal_process_attached. The responsible code, but actually boils down to this excerpt:

// Add both the JavaScript and the CSS.
// The parameters for drupal_add_js() and drupal_add_css() require special
// handling.
foreach (array('js', 'css') as $type) {
  foreach ($elements['#attached'][$type] as $data => $options) {
    // [...]
    call_user_func('drupal_add_' . $type, $data, $options);
  }
  unset($elements['#attached'][$type]);
}

The call_user_func will invoke either drupal_add_js and drupal_add_css respectively, depending the value of $type. It follows that there is no additional benefit from using #attached unless the asset is used by a render-array which is to be stored in the cache. Assets specified via #attached are guaranteed to be loaded if the associated render-array is rendered. They will not be added to the page when the associated render-array is not rendered.

In your specific situation you are attaching the CSS not to an element but to a page region. However the header-region apparently is not rendered by every theme, probably because it is not widely used. The header-region is rendered in page.tpl.php. If a theme chooses to ignore a region, like the Versatile and the Corporate Clean do, the CSS will not be attached.

To sum up:

Use #attached when adding assets to cacheable render-arrays (especially forms and form elements)
Add stylesheets / scripts to the module-info file or call drupal_add_js and drupal_add_css whenever adding assets globally.


You may can use this module
Overlay Paths

This is a simple module that enables administrators to use the built-in Overlay for non-admin pages.

This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.

This module is designed to be used by module developers comfortable with writing code to define which pages should appear in the overlay.


Can you filter views user list result based on the current users role

As I understand, you want to create a view which list users which lists only those users who has a specific role or roles that the current user also has. The below approach can be a solution :

Add a field 'User: Uid' in your view (Let the view is of type 'Users').
Make the field as 'Exclude from display'.
Add a 'global php' field and add some code as below under 'VALUE CODE' :

$user_load = user_load($data->uid);
$data->user_role = $user_load->roles;
return ($data->user_role);

Here, we are getting the roles of each user being rendered.

Here used '$data->uid' instead of '$row->uid' to avoide issue of returning NID with $row in D7. Although in this case '$row->uid' returns correct information.
Make the field as 'Exclude from display' as well.
Under Filter Criteria add a 'global php' field and add the below codes :

i) Under 'Setup Code' :

 global $user;
 $roles = array();
 $view->roles = $user->roles;

Here we are getting all the roles of the current user.

ii) User 'Filter Code' :

 // Suppose you have five roles in the instance with the 'rid's as saved in
 // 'role' table as : 1 (anonymous user), 2(authenticated user), 3(administrator), 4(hr), 5(web admin)
 // Suppose ROLE you want be matched has RID = 4
 if (isset($view->roles[4])) {// Checking if the current user has the role that you want to be matched with
   if (!isset($data->user_role[4])) {// If the user getting rendered doesn't have that role
     return TRUE;// If TRUE is returned, then that row is NOT shown
   }
 }

Note : Considering, 'views_php' module is installed.

Note : If the current user doesn't have the role that you want be filtered for, then the view will list the default list of users based on other conditions.

Note : Instead of writing the 'rid' in the filter code directly, we can provide an admin menu which will render a custom form with a text field and, admin or user with required access permission, can set any role(s) through that form and save it in a drupal variable, and we can render the role information we want be matched from the variable inside our filter code.

Hope it helps


How to add an Ajax call to an element that already has callback set?

I doubt that the array you've found really assigns 2 callbacks. It's rather an array defining a class and a method for a single callback:
'callback' => ['Drupal\foo\BarClass', 'ajaxCallback']

In fact, you can only set one callback in an #ajax element. If you want to override a callback you have to include the overridden callback in your code:
Drupal\foo\BarClass::ajaxCallback($form, $form_state)

and add your ajax commands to the returned ajax response (or in case the original method returns a render array you can either add your own content to the array or transform the render array into an ajax command which you return with your own commands in an ajax response).
Caveat: This only works if the overridden callback is static. If it runs in an instantiated object you have to override the class method itself.


How can I alter a query adding an OR clause for a relational field?

My solution:

Add a relationship for content referenced from the entity reference field.
Add a contextual filter for the entity reference field, using the content ID from the URL as the value. This includes events that have the location set directly.
Add a contextual filter for the entity reference field, using the content ID from the URL as the value, using the relationship. This includes events are related to an event that has the location set.

Unfortunately, the contextual filter WHERE group uses AND by default, so no results are returned, so we have to change the type in the WHERE clause.
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(ViewExecutable $view, Sql $query) {
  if ($view->id() === 'events') {
    if ($view->current_display === 'block_2') {
      $query->where[0]['type'] = 'OR';
    }
  }
}

If there are more contextual filters, you have to create a new OR where group with the fields, and remove them from group 0.
$group0 = &$query->where[0];

// Create a new OR group.
$group_id = $query->setWhereGroup('OR');

// Copy the conditions to the new where group.
$query->addWhereExpression(
    $group_id,
    $group0['conditions'][1]['field'],
    $group0['conditions'][1]['value']
);
$query->addWhereExpression(
    $group_id,
    $group0['conditions'][2]['field'],
    $group0['conditions'][2]['value']
);

// Remove from group 0
unset($group0['conditions'][1]);
unset($group0['conditions'][2]);


You can use truncate command which is faster than Delete. And try using this command directly from Terminal rather than doing "clear log" option available in Recent Log Messages in Drupal 7.

You can find more details on Truncate vs Delete on here.

Hope this helps.


How to override the default zen html template depending on a node type?

Jonathan, your missing an underscore...

function test_preprocess_html(&$vars){
  if (!empty($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'html__node__' . $vars['node']->type;
  }
}

Your get it if you see whats suggested already be doing a var_dump($vars).

This has nothing to do with the Zen theme, it's just core functionality.

To understand how this is formed you can take a look at the theme_get_suggestions() function in theme.inc

/**
 * Generate an array of suggestions from path arguments.
 *
 * This is typically called for adding to the 'theme_hook_suggestions' or
 * 'classes_array' variables from within preprocess functions, when wanting to
 * base the additional suggestions on the path of the current page.
 *
 * @param $args
 *   An array of path arguments, such as from function arg().
 * @param $base
 *   A string identifying the base 'thing' from which more specific suggestions
 *   are derived. For example, 'page' or 'html'.
 * @param $delimiter
 *   The string used to delimit increasingly specific information. The default
 *   of '__' is appropriate for theme hook suggestions. '-' is appropriate for
 *   extra classes.
 *
 * @return
 *   An array of suggestions, suitable for adding to
 *   $variables['theme_hook_suggestions'] within a preprocess function or to
 *   $variables['classes_array'] if the suggestions represent extra CSS classes.
 */
function theme_get_suggestions($args, $base, $delimiter = '__') {

  // Build a list of suggested theme hooks or body classes in order of
  // specificity. One suggestion is made for every element of the current path,
  // though numeric elements are not carried to subsequent suggestions. For
  // example, for $base='page', http://www.example.com/node/1/edit would result
  // in the following suggestions and body classes:
  //
  // page__node              page-node
  // page__node__%           page-node-%
  // page__node__1           page-node-1
  // page__node__edit        page-node-edit

  $suggestions = array();
  $prefix = $base;
  foreach ($args as $arg) {
    // Remove slashes or null per SA-CORE-2009-003 and change - (hyphen) to _
    // (underscore).
    //
    // When we discover templates in @see drupal_find_theme_templates,
    // hyphens (-) are converted to underscores (_) before the theme hook
    // is registered. We do this because the hyphens used for delimiters
    // in hook suggestions cannot be used in the function names of the
    // associated preprocess functions. Any page templates designed to be used
    // on paths that contain a hyphen are also registered with these hyphens
    // converted to underscores so here we must convert any hyphens in path
    // arguments to underscores here before fetching theme hook suggestions
    // to ensure the templates are appropriately recognized.
    $arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);
    // The percent acts as a wildcard for numeric arguments since
    // asterisks are not valid filename characters on many filesystems.
    if (is_numeric($arg)) {
      $suggestions[] = $prefix . $delimiter . '%';
    }
    $suggestions[] = $prefix . $delimiter . $arg;
    if (!is_numeric($arg)) {
      $prefix .= $delimiter . $arg;
    }
  }
  if (drupal_is_front_page()) {
    // Front templates should be based on root only, not prefixed arguments.
    $suggestions[] = $base . $delimiter . 'front';
  }

  return $suggestions;
}

Have a look at the $delimter argument. The default is '__' for theme_hook_suggestions().


How to setup session sharing for language subdomains (URL language detection set to domain prefix)

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

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

Source


You can do that in a module/theme by adding a region preprocess hook:

function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $vars['classes_array'][] = 'foo';
  }
}


Drupal 7, Dev Site, will not Aggregate Javascript or CSS

This could really be a myriad of problems.  More than likely, your files directory isn't writable.  Browse to the Status Report (admin/reports/status) and make sure the File System section says Writable.  While you are at it, make sure everything on the report is green.

Running a second Drupal site in a subdirectory of the first site is a tricky situation.  The main concern is the way Apache handles .htaccess files in a directory tree.  htaccess rules apply to the directory that the file is in, plus all subdirectories.  This means that your site in /drupaldev is going to inherit the directives from the root htaccess file.  This may or may not cause problems, but in general, this is a big red-flag.


Unfortunately the relation.api.php file included with the module is empty, so it doesn't appear that there's any official API documentation yet. There's the standard documentation but I don't think that covers code.

In this situation I normally head straight for the .test files included with the module. If they've been done properly (and it looks like they have for Relation), you should find all the code examples you need in there.

To find out what hooks (if any) the module provides, I usually just grep the module folder for module_implements( and see what hooks are actually invoked. If any are provided by the module you should be able to find them that way.

If that doesn't help it might be wise to re-think your question and make it more specific to what you're actually trying to accomplish in the first instance.


Creating mulitple contact forms in drupal 7

Did you consider using Webform Module. I generally prefer this over contact forms on my websites.


How to use custom tokens in view header Drupal 8

One possible soliton is to simply when declaring your custom tokens in hook_token_info()

use $info['tokens']['view']

Ex:

$info['tokens'] = [
    'view' => [
       'my-custom-token' => [
          'name' => t('Custom Token'),
          'description' => t('A custom token I created.'),
       ],
       // 'my-second-custom-token' => [...
    ],
];


Show progress of code executed on form submit

Surely you need to implement Batch API to achieve what you need, and keep the user notified for what's happening in the background.

Very similar question that will help you more. Read it carefully.

These modules will help you:

Progerss This is an attempt to implement a generic framework for keeping track of any progress
Background progress takes over the existing Batch API and runs batch jobs in a background process


Instead of using .po-files, install the Localization Update module.  It provides a much better interface for downloading, updating and managing translations.


Blocks are cached by default. A block class with this build method:

public function build() {
    return [
      '#markup' => 'Block content',
    ];
  }

gets cached indefinitely or as long as you set in cache max-age.

If you add cache tags to the block that doesn't change whether the block is cached or not. The cache tags are used to invalidate cache items, not to store them. That is what cache keys are used for.

If the block gets cached, this is for logged in users, because the cache for anonymous users doesn't cache blocks, only pages.


Hide 'successfully added to cart' message

I'm pretty sure that's just set by a rule called "Display an Add to Cart message".

You should be able to delete/disable that rule in the UI and the message will disappear.


How do I use AND condition in Rules to add shipping to sales tax?

NB: As so often happens with Drupal, apparently I was asking the wrong question. IMO this is such a -basic- part of any eCommerce system used in USA/Canada, but the answer is buried in a support request on Drupal.org. This is -terrible- documentation and I hope the Commerce Guys are duly ashamed. Doesn't matter how cool the code is if one can't easily figure it out.

Apparently what one has to do is add the rule into

Admin -> Store Settings -> Shipping  (Calculation Rules) -> Configure Component

Please see here (#29)
https://www.drupal.org/node/1243218#comment-6732098

...and also (#42).

What one does is add a new Rule to Shipping
Event: Calculate Shipping
Condition: Order Address Component Comparison
Actions: (Your Salestax Component Rule goes here)

For the Action you simply use the same sales tax component rule you used for

Admin -> Taxes -> Configure Component

...in my case 'Sales Tax WA'

So I suppose if you live in a jurisdiction with many possible taxes, you'd create a separate component rule for each under shipping, using exactly the same Order Address Comparison and Action Rule you used for the Taxes section.

What confused -me- was that I thought one could use use the IF/AND/OR under Taxes to differentiate between Shipping and Product line items. Apparently this does not work. That would be a MUCH better solution (reduce duplication of effort, cut down on errors.) If someone knows how to do this, PLEASE post here!

So, in one sentence, you have to apply all the same sales tax component rules in two places: in Taxes (for product line items) and then in Shipping under Calculate Rules to apply tax to the freight.

And here is the exported rule:

{ "rules_apply_taxes_to_shipping" : {
"LABEL" : "Apply Taxes to Shipping",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"IF" : [
  { "commerce_order_compare_address" : {
      "commerce_order" : [ "commerce-line-item:order" ],
      "address_field" : "commerce_customer_billing|commerce_customer_address",
      "address_component" : "administrative_area",
      "value" : "WA"
     }
   }
 ],
 "DO" : [
   { "component_commerce_tax_rate_state_of_washington" : { "commerce_line_item" :
     [  "commerce-line-item" ] } }
       ]
   }
}


Drupal Gardens: is it possible to install a new theme?

Drupal Gardens is really limited and you cannot install a theme from drupal.org but what you can do is to customize the possible "layouts" that Gardens give to you.

If you click on the layout button on the panel you will see different layouts (columns and sidebars) and from this basic structure you can start applying custom CSS. Check more here http://www.drupalgardens.com/documentation/themebuilder/layout-tab and http://www.drupalgardens.com/documentation/themebuilder/advanced-tab


Try out Daylight saving time module.

  This module intended to work with Daylight saving time. It replaces
  system time offset and has preferences for each user and full site.

  Used to display correct time of creation of documents etc.


How to specify subdirectory for uploads in files dir when adding file field to content type via module?

It seems to me that your directory does not exists (or at least is not writable).
You can make a function to test/create your custom folder:

function create_directory($folder) {
   // Constructs a URI to Drupal's default files location given a relative path
   $dir = file_build_uri($folder);
   // Checks that the directory exists and is writable.
   // Indicate if the directory should be created if it does not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only (FILE_MODIFY_PERMISSIONS)
   $res = file_prepare_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
   if (!$res) {
     watchdog('file system', 'The directory %directory does not exist or is not writable.', array('%directory' => $dir), WATCHDOG_ERROR);
   }
   return $res;

}

Then call this function with $type as parameter: create_directory($type);


(Field type) Link autocompletion for media entities

The short answer: Currently not supported, unfortunately:

  // @todo Support entity types other than 'node'. Will be fixed in
  //    https://www.drupal.org/node/2423093.

Until https://www.drupal.org/node/2423093 is done, the link field widget can only support a single entity type; so you can have a widget for linking to nodes or to media entities, but not both.

Worse, until https://www.drupal.org/node/2427803 is done, the entity type is hardcoded as node and not configurable.

The good news: It's still possible, if you're prepared to write a bit of code.

Other than three lines in LinkWidget that contain a hardcoded reference to node, nothing stops the code from working with a different entity type in principle. So as a workaround, you could duplicate the core LinkWidget in a custom module, change the relevant lines to media (I made a patch for this at https://gist.github.com/cburschka/b214a52bdb1fdf7349ef3b0afe56b950), and thus create an alternate widget for media links.

This still means you have to choose between either a Node or Media link field, unfortunately. If you don't want to create two different fields, you could use the Paragraphs module in order to create a single Paragraph field that can be filled with one of two paragraph types (one of which exposes the link field with the original widget, and the other with your custom Media widget). It's a bit more complex, but should still provide a decent user experience.

Edit: Alternatively, instead of using the Link module you could use a Dynamic Entity Reference field: https://www.drupal.org/project/dynamic_entity_reference

The downside is that this field could then only reference entities; external links and non-entity links wouldn't be possible anymore.


Here's what I would do.

First I'd enable the CTools Page Manager and Views content panes and create a page (admin/structure/pages) for that display that has arguments in it's path.

Then I'd create three views with display type "content pane": one that lists nodes based on a contextual filter (A), one that shows only one node (B) and one that lists dates (C).

Then I'd create the column layout in the page's content and would provide the arguments with Page Manager.

Here's a really nice tutorial from NodeOne that addresses most of the tricky parts here:
http://dev.nodeone.se/en/learn-page-manager-part-5-views-content-panes-basics


How to edit misc/print.css without changing core

You don't need to edit any core file, to achieve what you are trying to do. Since you are talking of a theme, you just need to replace the template file used from the Book module. This is what done from the Stable theme, which has its own book-export-html.html.twig.

The only reference to the misc/print.css file is in book-export-html.html.twig; there isn't any core library with a reference to that file, and this makes things easier for a theme.
book-export-html.html.twig contains the following code.

  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
    <link type="text/css" rel="stylesheet" href="misc/print.css" />
  </head>

In the template file for your theme, you just replace it with the following, if you don't want to use any print.css file.

  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
  </head>

If you just need to use a different print.css file for your theme, then you can simply edit the file path, and provide your own CSS file.

  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
    <link type="text/css" rel="stylesheet" href="the_path_relative_to_the_theme_folder/print.css" />
  </head>


Add to cart link for product that sends user directly to checkout?

The Ubercart Cart Links Builder turned out to provide the exact functionality I needed.


Where are templates from hook_theme stored in the database

Normally, db_set_active() is used to query external data.  I have never heard about it being used to switch between two full Drupal databases from within the same active codebase / website.

I suspect one or two things is happening: you are having cache problems and/or you are having registry problems.

When you clear caches via the UI or drush, the full registry gets rebuilt, which includes theme functions and their template files.  That information will get stored in whatever database is active at the time.

If you switch databases, the cache and registry will be pulled from the newly active database.   In addition, any new cache entries will be written to the new database.

So, I think your problem is that the wrong cache and/or the wrong registry is being queried when you use the Drupal API and you are getting stale data.

The proper way to accomplish this is to set up a dev/staging/live environment, where code goes forward from dev -> staging -> live, and databases go backwards from live -> staging -> dev.  There are lots of articles on the net, and a few questions here, about how to do this.


How do I  keep the sum of related nodes' specific field values in a field?

I managed to do this with Rules module, to keep it short.

By default, gave 0 to the value of integer for Parent content type.
Added a rule to calculate the value of Parent's integer field by summing up the values of child nodes and setting it to Parent's integer value. Event is creating new content
Added a rule to recalculate the value of Parent's integer field when adding or updating a Child content. For this, I am calculating the difference of new and old integer values of Child node. Then, adding this value to Parent's integer value.

If anyone is interested, I can also give the details of the rules.

Below is an export of the second rule:

{ "rules___aa_test" : {
"LABEL" : "__aa_test",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_update" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_parent_story" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_time_left" } },
  { "entity_has_field" : { "entity" : [ "node:field-parent-story" ], "field" : "field_time_left" } }
],
"DO" : [
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-time-left" ],
        "op" : "-",
        "input_2" : [ "node-unchanged:field-time-left" ]
      },
      "PROVIDE" : { "result" : { "difference" : "Difference" } }
    }
  },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-parent-story:field-time-left" ],
        "op" : "+",
        "input_2" : [ "difference" ]
      },
      "PROVIDE" : { "result" : { "result" : "Calculation result" } }
    }
  },
  { "data_set" : {
      "data" : [ "node:field-parent-story:field-time-left" ],
      "value" : [ "result" ]
    }
  }
]

}
}


How to build an Email Diggest using Rules

You may want to consider Notifications or Subscriptions. Both modules offer either immediate or digest notifications for content updates. Be aware that Notifications currently requires PHP 5.3.


How to pass information by reference from a hook to Feeds?

The hook hook_feeds_before_update() doesn't support skip items. You could use the hook hook_feeds_presave() instead. Set $entity->feeds_item->skip to TRUE if you want to skip saving the entity. See feeds.api.php for an example.

You could also use the hook hook_feeds_after_parse() to remove items from the list to be imported. The items are in $result->items. This hook is invoked before processing happens, so at this point it is still unknown to which entities the items will be imported (you have no entity ids). Feeds Tamper uses this hook to modify the data to be imported.


Permissions not working with Tabs menus?

Try to remove 'content' word from 'access arguments' in hook_menu, because you custom permissions don't contain it. Clear cache.

'access arguments' => array('access one_type_titles'),


Why is there a convention to use test-specific namespaces for unit tests?

There are few reasons why tests are in different namespaces.

Drupal have several different types of tests

WebTestBase (WTB), aka simpletests or integration tests
BrowsertestBase (BTB), integration tests (all WTB will eventually be replaced by equivalent BTB)
KernelTestBase (KTB), a barely bootstrapped version of Drupal, not an integration test but a lot more than a true unit test
JavascriptTestBase (JSTB), an integration test that is Javascript aware
UnitTestCase and PHPUnit_Framework_TestCase, unit tests

Note that integration are also called functional tests. I am going to ignore the difference between UnitTestCase and PHPUnit_Framework_TestCase right now and lump them together as unit tests.

The five different test types are all in different namespaces so the test discovery process can find them and place them into five groups.  The test runner allows the various test groups to be run together, and also invoke them properly during runs.

For example, if making a big change, you can run all unit tests locally as a sanity check (running all of the take about a minute on a normalish local machine).

Tests associated with a particular module are also in the modules namespace, so you can easily run all tests for that module, and they won't be discovered if that module is disabled.  For example, integration tests take along time (usually between 30 seconds and 4 minutes each).  You can just run all of the Field UI tests at ones if you are doing work there.

The test runner also allows you to run all of the tests in a particular directory.  This allows you to target a particular core subsystem that isn't in a module.  For example, you can run all of the database kernel tests at once this way.

Some subsystems also define their own test bases.  For example, the migration system defines its own test bases to centralize common functionality and to to have a common setup.

Tests also make frequent use of traits to share code between different types of tests.

The particular case you mention is an oddity.  In a perfect world, the t() function wouldn't be used in object oriented code; the injected translation service would be used which could then be mocked in unit tests instead of needing to use shenanigans like shadowed globals.


you have to update your database by using the drush commands :

drush updb -y

and

drush entities-update

If you dont have drush, you can use the /update.php page.
Regards,


How to embed a view or a rendered node into a field group

I'm not sure your general strategy is the absolute best way to go, but I don't see any major problems, I think hook_preprocess_page is too broad as it runs everywhere and would suggest template_preprocess_node instead (even though this is a template preprocess it can be run like a normal hook preprocess in a module)

In regards to getting the content you will need to do a EntityFieldQuery using the nid of the page being viewed as a fieldCondition, the only problem I can see is when there is more than one secondary type assigned to the same main type.

An alternative approach would be to see whether it's possible to write a View which takes the nid as a Contextual Filter and then builds all the content, I think you'd need to add a Relatonship to the secondary type, etc. and if it's possible this would cut down on the amount of custom coding needed.


Is it possible to run functional tests without creating test tables?

I have found the answer there. But don't do that !

It's better to move the database on a tmpfs folder (it's > 5x faster), because not only a "dirty" environment does not work, but it will broke your website with a serious error (just happened to me).
Hints to tweak the database on this question.

It's there but don't do it :

  // for our functional testing, we want to test the pages and code that
  // we've been generating in the real database. to do this, we need to
  // ignore SimpleTest's normal fake database creation and fake data
  // deletion by overriding it with our own setUp and tearDown. NOTE that
  // if we make our own fake data, we're responsible for cleaning it up!
  function setUp() {
    // support existing database prefixes. if we didn't,
    // the prefix would be set as '', causing failures.
    $this->setup = TRUE; // Drupal 7 way
  }
  function tearDown() { }


Almost a whole week of hitting my head on this. Yeah it helps if in the callback function I call back the correct form name... sigh


How to do integrate javascript in drupal way

The Managing JavaScript in Drupal 7 guide provides the information to add JavaScript to Drupal. The techniques presented there apply to both themes and (custom) modules:

Add a scripts[] = somescript.js to your module or theme's .info file
Use drupal_add_js() in your module or theme's code
Use the #attached['js'] property in a From API or renderable array.
Note that Drupal already include jQuery, jQuery UI and a bunch of other libraries so you don't, and shouldn't, add them yourself. Instead you should use drupal_add_library() or the #attached['library'] property.

The Working with CSS guide provides the information to add CSS to Drupal. Again, the techniques presented there apply to both themes and (custom) modules. With an exception: addition of style sheets from an .info files only works for a theme and not a module.

Add stylesheets[all][] = somestylesheet.css to a theme's .info file.
Use drupal_add_css() from module or theme's code.
Use #attached[css] property in a From API or renderable array.


I think you can achieve this using an entity field, in this case the user entity, and some PHP Code.

Add a Field that counts the numebr of editions. Then, alter the entity edit form (in this case again, the user edit form) and:

Hide the field (with #access FALSE, for example).
Add your custom submit handler to the entity edit form.
If the field value is minor than the max edit count allow to edit
then increment the field value in a custom submit handler.
If the field value is equal to the max edit count then deny the
edition (deny the edit form, hide the field or whatever you want and
fit your needs).

Also don't forget to hide the field when the entity is shown (check the entity display settings page).


Drupal.attachBehaviours() on Block that got rendered via ajax call

Ok, there are a few things that need to be done:

Create a custom ajax command
Create the JS to handle that custom command
Return an AjaxResponse from getWebformBlockHtml(), that contains that custom command from step 1
Ajaxify the response when your ajax is complete

You can do that as follows:

Step 1 - Create a custom ajax command

namespace Drupal\[MODULENAME]\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class MODULENAMELoadFormCommand implements CommandInterface
{
  protected $form;

  public function __construct($form)
  {
    $this->form = $form;
  }

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

Step 2 - Create the JS to handle that custom command

Add the following to your JavaScript that you're loading on page load:

Drupal.AjaxCommands.prototype.MODULENAMELoadFormCommand = function(ajax, response)
{
  $modal.find('.modal-content').first().html(response.form);
  $modal.foundation('open');
  Drupal.attachBehaviors($('#modal')[0], settings);
};

Step 3 - Return an AjaxResponse from getWebformBlockHtml() that contains that custom command from step 1

use Drupal\Core\Ajax\AjaxResponse;

public function getWebformBlockHtml($webformid) {
  $response = new Ajaxresponse();

  $webform = Webform::load($webformid);
  $renderable = $this->entityTypeManager()->getViewBuilder('webform')->view($webform);

  $rendered_form = \Drupal::service('renderer')->renderRoot($renderable);
  $response->setAttachments($renderable['#attached']);

  $response->addCommand(new MODULENAMELoadFormCommand($rendered_form));

  return $response;
}

Step 4 - Ajaxify the response when your ajax is complete

Modify your original Ajax Call to look like this:

$.ajax({
  url: '/contact_bridge/webform/' + targetForm,
  success:function(response) {
    var ajaxObject = Drupal.ajax({
      url: "",
      base: false,
      element: false,
      progress: false
    });

    // Simulate an AJAX response having arrived, and let the Ajax
    // system handle it.
    ajaxObject.success(response, "success");
  }
});


How can I load a javascript file into a Drupal 7 page using the Code per Node module?

Code per node module is  intented to use to have a custom JS for each node. The JS code must be placed inline, in the node add / edit form. You have this tutorial to see how it works.

If you want to add the same js to a specific content type you can create a module custom where you invoke preprocess node hook:

function YOUR_MODULE_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js('path/to/somescript.js');
  }
}

You can also do this in a custom theme, there are examples in this answer.

If you want see a module with drupal_add_js examples and a nice documenttion, you can see the module js_example , which is a module inside Examples 7.x.


hook_menu implementation producing error page

I've got this noted down as my starting point for a  module .

function helloworld_menu() {

$menu['helloworld/hello'] = array(
    'title' => 'Hello World',
    'page callback' => 'helloworld_hello',
'access callback' => TRUE,
);
   return $menu;
  }

function helloworld_hello() {
   return 'Hello World';
 };

do you still get an error if you take it back to this point.


Simply add 3 rows in the flexible layout by clicking 'Column' > 'Add row to top/bottom' in the layout designer to stack the page. Add fluid or fixed regions afterwards in every row.

(Special thanks to @Letharion!)

You can also achieve this without the flexible layouts and do it programatically like @Andrew Welch said. This video can help you in doing that.


My Form folder in my module was named "Forms". Be carefull with your file structure. Too bad the error is not very explicit. It should be "not exist" instead of "not valid".


There are two basic approaches for doing locations in D7:

the location and gmap modules
the addressfield, geocoder, and openlayers modules

According to Karen Stevenson's presentation at Do It With Drupal 2011, only location/gmap currently has location proximity search working in D7... but not very well.

Based on this presentation and the book Mapping with Drupal, I set up proximity search on my own site using the location module.  It works, but it's not terribly user friendly, it's a pain to theme, and it's still clearly under development.  However, it's a far better solution than I would have been able to arrive at rolling my own.


Even though you didn't mention it, this is clearly a multilingual site. Which implies that "language detection" is involved (to decide each time in which language a page (or webform) needs to be displayed.

Your problem related to the usage of French or English language might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: experiment a bit with the correct order that should be used. Often times, this should be changed to something like 'URL, Default, User', and not something like 'Default, URL, User' (which I assume you're currently using, and which might explain the difference in the language used in different browsers).

The browser differences to display the errors (red boxes, etc) might be some browser dependency and/or something in your sub-theme (custom or not?). With the few details provided it is hard to tell what might help to resolve that part of your question. I recommend you move that part to a different (new) question, or enhance your question to provide more details about the sub-theme.