drush 8.1.9 on php 7 not giving any "drush status" in docroot folder I just setup a fresh install of drupal 7, ubuntu 16.04, installed php 7.0 and git cloned the drush repo which checkout of 8.1.9 drush. When I do a drush status on the docroot of my drupal folder it shows the following and when doing a drush dl it fetches only drupal 8 modules.

 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /vendor/drush/drush/drush.php
 Drush version          :  8.1.12
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/ubuntu/.drush/hotsite.aliases.drushrc.php

When I used to run php 5.6, it would give me all the details of my install. What did I do wrong here?

---- updated with drush status in the sites/default folder:

$:/var/www/hotsite_d7/docroot/sites/default$ drush status
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /vendor/drush/drush/drush.php
 Drush version          :  8.1.12
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/ubuntu/.drush/aliases.drushrc.php

$/var/www/hotsite_d7/docroot/sites/default$ drush @hotsite status
 Drupal version                  :  7.57-dev
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  127.0.0.1
 Database port                   :
 Database username               :  xxx
 Database name                   :  xxx
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  bootstrap
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php/7.0/cli/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /vendor/drush/drush/drush.php
 Drush version                   :  8.1.12
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :  /home/ubuntu/.drush/aliases.drushrc.php
 Install profile                 :  standard
 Drupal root                     :  /var/www/hotsite_d7/docroot
 Drupal Settings File            :  sites/default/settings.php
 Site path                       :  sites/default
 File directory path             :
 Temporary file directory path   :  /tmp

$/var/www/hotsite_d7/docroot/sites/default$

Drush usually does this when it cannot find a Drupal installation, which happens when it cannot find a settings.php. Did you go through the installation process yet? (visiting install.php on the browser or doing drush site-install)


override theme function in facetapi module I am trying to change the markup of links created by the facetapi module.  The theme function is here

function theme_facetapi_link_inactive($variables) {
  $accessible_vars = array(
    'text' => $variables['text'],
    'active' => FALSE,
  );
  $accessible_markup = theme('facetapi_accessible_markup', $accessible_vars);
  $sanitize = empty($variables['options']['html']);
  $variables['text'] = ($sanitize) ? check_plain($variables['text']) : $variables['text'];
  if (isset($variables['count'])) {
    $variables['text'] .= ' ' . theme('facetapi_count', $variables);
  }
  $variables['text'] .= $accessible_markup;
  $variables['options']['html'] = TRUE;
  return theme_link($variables);
}

I am trying to override this function so I can change the markup without editing the module files.  I've tried MYTHEME_preprocess_facetapi_link_inactive and using a custom module but both times I can print the variables and they are correct but the links are still displayed wrong.

function MYTHEME_preprocess_facetapi_link_inactive($variables) {
  $accessible_vars = array(
    'text' => $variables['text'],
    'active' => FALSE,
  );
  $accessible_markup = theme('facetapi_accessible_markup', $accessible_vars);
  $sanitize = empty($variables['options']['html']);
  $variables['text'] = ($sanitize) ? check_plain($variables['text']) : $variables['text'];
  if (isset($variables['count'])) {
    $variables['text'] .= ' <strong>' . theme('facetapi_count', $variables) . '!!!</strong>';
  }
  $variables['text'] .= $accessible_markup;
  $variables['options']['html'] = TRUE;
  return theme_link($variables);
}

Am I going about this the wrong way?

You're nearly there, but a preprocess function doesn't look applicable to what you're trying to do. A preprocess function is used to set up variables for a theme function, not to actually produce the markup.

What it looks like you're trying to do is to override theme_facetapi_link_inactive() completely, in which case you don't use a preprocess function, but instead you call the function MYTHEME_theme_function_name() and the theme engine will use that instead of the original function.

So all you need to is change the name of your function like so:

function MYTHEME_facetapi_link_inactive($variables) {
  // Same code as in your example
}

After you clear the caches Drupal will start using that function in place of theme_facetapi_link_inactive() whenever it's called.


Environment dependend workflow with configuration management When using Drupal 7 with larger projects, we used a Custom module together with Features, Environment and Environment Indicator modules to keep special environment settings apart. We had at least one feature module for each environment containing something like this:

Production

no dblog module active
no devel modules
all sorts of caching enabled
red coloring on Environment Indicator

Staging / Testing

dblog module active
no devel modules
some caching disabled
yellow coloring on Environment Indicator

Staging / Testing

dblog module active
all sorts of devel modules active
caching disabled
green coloring on Environment Indicator

When developing we used to push new code to production when it was finished and tested. After successful deployment, we cloned the database down to staging and development environments to be sync with the state of production in terms of new content. After that we would run commands like drush env-switch staging to tell Drupal to set environment to Staging and run some custom hooks that would enable the Staging feature module and its settings and dependencies. This way Production, Staging and Develop had different sets of modules and configuration but the same state of content.

After reading and testing into Configuration Management, i fail to see how i could accomplish such a workflow. When using drush config-export staging it exports all current settings into staging directory, which i can check into git and deploy it on my server. Features for D8 lacks of some things that have been in D7. I miss a settings we had in D7 and i am not able to add a dependency without additional settings. I don't depend on Features if there is another way of doing things like this in D8.

What am i missing in D8? What would be the current workflow to get such environment dependent settings and modules active and different environments in Drupal 8?

Thanks for you help!

Drupal 7

Have you considered adding some intelligence to settings.php? You could test $_SERVER['HTTP_HOST'] there, and set $conf['some_variable'] accordingly. Below are some examples from Pantheon. They use their own environment variables to test which environment is running, but you can achieve the same by testing $_SERVER['HTTP_HOST'] or maybe testing file_exists('some_file_which_identifies_environment') - whatever is convenient.

// All Pantheon Environments.
if (defined('PANTHEON_ENVIRONMENT')) {
  // Drupal caching in test and live environments.
  if (in_array(PANTHEON_ENVIRONMENT, array('test', 'live'))) {
    // Anonymous caching - enabled.
    $conf['cache'] = 1;
    // Block caching - enabled.
    $conf['block_cache'] = 1;
    // Expiration of cached pages - 15 minutes.
    $conf['page_cache_maximum_age'] = 900;
    // Aggregate and compress CSS files in Drupal - on.
    $conf['preprocess_css'] = 1;
    // Aggregate JavaScript files in Drupal - on.
    $conf['preprocess_js'] = 1;
  }
  // Drupal caching on dev environment, and all multidevs
  else {
    // Anonymous caching.
    $conf['cache'] = 0;
    // Block caching - disabled.
    $conf['block_cache'] = 0;
    // Expiration of cached pages - none.
    $conf['page_cache_maximum_age'] = 0;
    // Aggregate and compress CSS files in Drupal - off.
    $conf['preprocess_css'] = 0;
    // Aggregate JavaScript files in Drupal - off.
    $conf['preprocess_js'] = 0;
  }

  // Minimum cache lifetime - always none.
  $conf['cache_lifetime'] = 0;
  // Cached page compression - always off.
  $conf['page_compression'] = 0;

  if (PANTHEON_ENVIRONMENT == 'dev') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-X';
  }
  else if (PANTHEON_ENVIRONMENT == 'test') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Y';
  }
  else if (PANTHEON_ENVIRONMENT == 'live') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Z';
  }
}

Drupal 8

The same approach can work in Drupal 8, except that the global configuration variable is named $config. This is documented here: Configuration override system and that page shows the example:

$config['system.maintenance']['message'] = 'Sorry, our site is down now.';


How to allow multiple email addresses on webform module? The version of webform module im running doesn't support sending to multiple email addresses. Ideal users should be able to add all the different emails they what to send to in one box. Dose anyone have a workaround for this. Even if that means adding the emails in a "cc" form or separating the emails with a semicolon or comma.

-Thanks

Are you able to upgrade to the latest version of webform?

On your webform page, click the "webform" tab, and then the "e-mails" tab.
Add a single e-mail address, and click add.
Either click edit, or after adding an email, you should see a settings page. The first label is "E-mail to address".
Make sure the custom field is selected, and enter a comma separated list of emails in this field.


How do I migrate the basic page content to another site? I have nearly 250  basic pages content and I want to migrate the same content to another Drupal website. I tried using the Backup and Migrate  module, but it doesn't work well. How can I do this?

As far as I understand from your short question, you want to export only some content to another Drupal installation. In this case Backup and Migrate module will not do any good for you, because it is mainly designed for backing up migrating at database level.

Node Export will allow you to export and import nodes to another Drupal installation.

  Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.


When does hook_field_storage_details_alter() fire? I need to modify the field storage details so some additional data can be stored with a form field. I found hook_field_storage_details_alter(), but it doesn't seem to fire. When is this hook used?

The function that invokes both hook_field_storage_details() and hook_field_storage_details_alter() is _field_info_prepare_field(), which is indirectly called from the following functions:

field_info_cache_clear()
field_info_extra_fields()
field_info_field()
field_info_fields()
field_info_field_by_id()
field_info_field_by_ids()
field_info_instance()
field_info_instances()

In other words, all times information about a field is required, that hook is used.
As Clive points out, _field_info_collate_fields(), the function that directly calls  _field_info_prepare_field(), caches the information returned by those hooks, which means they are not always invoked; they are invoked when the cached data don't exist, or have been removed. This makes hook_field_storage_details_alter() used in a similar way to hook_menu_alter(), which is called only when the menu definitions need to be rebuild, and not all times Drupal is retrieving the menu definitions given by all the enabled modules.


Change position of Drupal ajax progress throbber When you are using views built in ajax pager. When you click on any element of the pager ajax throbber appears next to the clicked button. Can i change the location of the throbber, for example outside of pager div?

You can do it by overriding the CSS in your theme CSS file. Here is the class to use for changing the position of ajax throbber:

  .ajax-progress .throbber

You can set the position to whatever you want.

Also have a look at this blog: http://www.antimath.info/css/change-throbber-in-drupal-7/


Configuration override not work from settings.php I add the following to the end of my settings.php

$config['system.site']['name'] = 'Drupal 8 DEVELOPMENT';

When I run drush cget system.site name it still displays the old site name.

Any idea why it wouldn't be overriding?

You can use the --include-overridden option to show overridden config, for example:

drush cget --include-overridden system.site name


Tracking User's Location at a certain point I've installed the Time Tracker module.

I need to track user's location when the user clicks on "Start Timer" AND when the user clicks "Stop Timer". Please help or point me in the right direction. I tried to use rules but I didn't know where to begin.

You can append a different query string to each click, which will allow you to track each one individually. Lets say your "Start Timer" is at mysite.com/start_timer (using ajax). You can create several url's with a query string that lead to the buttons. Ex:

mysite.com/start_timer (using Ajax)

mysite.com/end_timer (using Ajax)

Then you can use Google Analitics Event Tracking Module which will do your work for tracking easily.

Enjoy !


Real Estate Functionality My client wants a real estate website that links to other major sites like Trulia. He wants a way of collecting information from his visitors, and a way of telling that they went through his site to get to the major real estate sites.

How can this be achieved?

You can create an internal url system that redirects to the partner sites. Depending on what you need to do, you could create a node (content) with info about the partner site where you stored the link to it. Then instead of displaying the link directly on the site you could instead display the url: redirect/[nid]. The url would be known by your module, and you could store info that you were sending some one over to the partner site before loading the node to find the url to send them over to.

You would have to create a custom module for this, but the above method could be a way of doing this.

You could also use tools like Google Analytics to track outgoing links instead. It depends where you want the data and what you need to do with it.


How to get new password by mail instead of password reset url (Forgot password) When we click on "Forgot your password" and enter email id, Drupal will send password reset URL by mail.

But is it possible Drupal send any random password by email instead of URL?

I have checked Registration Password Token but this will helpful for new user registration only.

Is there any module available?

You can use Recovery Password (Email New Password) module.

  Recovery Password module makes it possible for Drupal to send any
  random generated password(new password) by email instead of URL to the
  user.

Refer to the module page for detailed description. Feel free to contact me, in case of any issue. I'm maintainer of this module.


What are all the directories for in the new Drupal 8 structure? Drupal 8 re-arranged all the directories and locations of modules/themes etc. Where do things go now?

/core - All files provided by core, that doesn't have an explicit reason to be in the / directory. More details futher down.
/libraries - 3rd party libraries, eg. a wysiwyg editor. Not included by core, but common enough to warrant inclusion here.
/modules - The directory into which all custom and contrib modules go.

Splitting this up into the sub-directories contrib and custom can make it easier to keep track of the modules.
enough to warrant mention here.

/profiles - contributed and custom profiles.
/themes - contributed and custom (sub)themes
sites/[domain OR default]/{modules,themes} - Site specific modules and themes can be moved into these directories to avoid them showing up on every site.
sites/[domain OR default]/files - Site specific files tend to go here. This could be files uploaded by users, such as images, but also includes the configuration, active as well as staged config. The configuration is read and written by Drupal, and should have the minimal amount of privileges required for the webserver, and the only the webserver, to read and modify them.
/vendor - Backend libraries that Drupal Core depends on. (Symfony, Twig, etc)

Details on the /core directory, primarily useful to know for new core hackers:

/core/assets - Various external libraries used by Core. jQuery, underscore, modernizer etc.
/core/misc - Frontend code that Drupal Core depends on.
/core/includes - Functionality that is to low level to be modular. Such as the module system itself.
/core/lib - Drupal Core classes.
/core/modules - Drupal Core modules.
/core/profiles - Drupal Core installation profiles. Minimal, Standard, Testing and Testing multilingual installation profiles by default.
/core/scripts - Various CLI scripts, mostly used by developers.
/core/tests - Drupal Core tests.
/core/themes - Drupal Core themes.


How to get the field values with EntityQuery? I am working on a query filtering form that lists entities. I have various 'range' fields and I would like to display the min and max values. Is it possible to retrieve field values with EntityQuery?

For example I want to filter nodes whose NIDs are between 10 and 50 but I would also like to see which NID is the lowest and which is the highest so I can change my input accordingly.

Or better, imagine a commerce product price. I would like to see products whose price is between 10€ and 50€ but I would like to see what is the range that I can operate with(ie. from 0.99€ for the cheapest product, up to 150€ for the most expensive product).

I am thinking that with EQ this is possible only by having two queries - one for the min value and one for the max value, sort it by desired field, load a single entity and retrieve the value from the entity object. This solution is very ineffective(< performance) and since I am already using EQ I don't want to move back to basic queries just for this since that would make EQ obsolete for me.

No, it is not possible.

There is no API to get values of specific fields. Views also doesn't do that anymore, it always loads entities as well.


Drupal 7 Views - Add a wrapper around rows for unformatted list from admin panel I have a views which rendered html like this

Some Text here

Some Text here

Some Text here

Now I want to wrap the rows using a wrapper div like so.

Some Text here

Some Text here

Some Text here

Assuming you know how to override theme templates (that would be a separate question) you can override the views_view_unformatted.tpl.php template and make your override something like this:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>

  <?php foreach ($rows as $id => $row): ?>
    <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } ?>>
      <?php print $row; ?>

  <?php endforeach; ?>

You could also override the views-view.tpl.php template instead and in the part that says:

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

do something like

<?php if ($rows): ?>

      <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

It's up to you which way you want to do it.


Best way to get module and commit meta data from drupal.org This is a broader question, but related to: get-more-drupal-org-project-usage-information

Goal: I'd like to get richer stats about modules.

Choosing a module has become a very complicated process.  Things like recent commits, usage growth/decline, number of maintainers, etc. all factor in but drupal.org has (frankly) lousy tools for finding modules and http://drupalmodules.com/ is basically abandoned.

Current Approach: Screen-scrape limited available stats like https://www.drupal.org/project/usage

I've been grabbing some stats to help me make an informed decision but scraping seems archaic given the openness of drupal.

Ideal Approach: Use published drupal.org API to query in JSON

Does such a thing exist to harvest module info or is it necessary to scrape?  Even better would be to create a database or spreadsheet.

I have seen a thread discussing this, but looking for an implementation or concrete plan to implement.

IMO there is a desperate need to improve module transparency and data to help system builders better select appropriate modules.

It took me a while to find but this is what I was looking for:

https://www.drupal.org/api

  The following node types currently exist on drupal.org:

  book book_listing casestudy changenotice forum image organization
  packaging_whitelist page project_issue project_core
  project_distribution project_drupalorg project_module project_release
  project_theme project_theme_engine project_translation story Of
  particular interest is interacting with the issue queues. Some of the
  field values returned by the api are the numeric representations in
  the database. The following mappings are used for some key fields on
  project_issue nodes:

  field_issue_priority

  400,"Critical” 300,"Major” 200,"Normal” 100,"Minor" field_issue_status

  1,active 2,fixed 3,closed (duplicate) 4,postponed 5,closed (won't fix)
  6,closed (works as designed) 7,closed (fixed) 8,needs review 13,needs
  work 14,reviewed & tested by the community 15,patch (to be ported)
  16,postponed (maintainer needs more info) 18,closed (cannot reproduce)
  field_issue_category

  1,'Bug report' 2,'Task' 3,'Feature request' 4,'Support request'

  Available Taxonomy Vocabularies

  1,Forums 2,Screenshots 3,Module categories 5,Drupal version 6,Core
  compatibility 7,Release type 9,Issue tags 31,Page status 34,Front page
  news 38,Audience 44,Maintenance status 46,Development status
  48,Services 50,Sectors 52,Locations 54,Keywords 56,Level 58,License
  60,Book availability 62,Book format


How theming off-line page? I read API and put files theme folder.

maintenance-page.tpl.php works well,

but maintenance-page--offline.tpl.php don't work.

How theming off-line page ?

Are you sure that your database server was offline when you tested ? The API description says

  "maintenance-page--offline.tpl.php" can be used when the database is offline to hide errors and completely replace the content.


How do I copy the values of one field collection field to another content type with the same field collection? I have one content type with a multi-value field collection entity on it.

On the event that this content type is flagged I would like to fire a rule that will create a new piece of content and copy all of the field collection lines to the same field collection type on the new content type.

The rule I have included bellow fires and creates the new content however the field collection is not copied.

{ "rules_generate_pal" : {
"LABEL" : "Generate PAL",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "flag" ],
"ON" : [ "flag_flagged_generate_pal" ],
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "flagged-node" ],
      "field" : "field_project_personnel_needed"
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "project_activity_log",
        "param_title" : "[site:current-date]",
        "param_author" : [ "flagging-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created_pal" : "Created PAL" } }
    }
  },
  { "drupal_message" : { "message" : "BOOM!" } },
  { "LOOP" : {
      "USING" : { "list" : [ "flagged-node:field-project-personnel-needed" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "list_add" : {
            "list" : [ "entity-created-pal:field-project-personnel-needed" ],
            "item" : [ "flagged-node:field-project-personnel-needed:0" ]
          }
        }
      ]
    }
  }
]

}
}

I have used the "set data value" action in Rules to make one field collection equal another field collection. It just dumps the whole field collection in at once, so you don't have to loop through each item one at a time.


Not getting complete URL parameters My url is node/3?filter-value=67&filter-value=80 and when i try to do this code:

$param = \Drupal::request()->query->all();`

$param['filter-value']

It shows the value 80 only. I want to get both of them.

if you don't want to change the structure of your url.

you can use Explode function

I have made a helper function try it out:

function getParamsOfUrlWithSameKey(){
  $current_uri = \Drupal::request()->getRequestUri();
  $items = explode('?', $current_uri);
  $res_param = [];
  if (isset($items[1])) {
    $params = explode('&', $items[1]);
    foreach ($params as $param) {
      $param_value = explode('=', $param);
      $key = $param_value[0];
      $value = $param_value[1];
      $res_param[$key][] = $value;
    }
  }
  return $res_param;
}

The return of this function will be something like:

array:1 [▼
   "filter-value" => array:2 [▼
     0 => "67"
     1 => "80"
   ]
 ]


Can you use basic FAPI without drupal_build_form? is there any way to use simple FAPI (such as dropdown selection box) without processing it with drupal_build_form?

The thing is, I have a page with a custom table view and a drop-down selection widget that limits the view. The only thing that I need the selection widget to do is to redirect me to '...the_page/id_of_selected_item' (or 'the_page?gid=id_of_selected_item). And it seems to me that using full form support for such a simple task (which a basic redirect surely is) is a bit of a overkill...

I know I can render the selection widget easily without the form support but then neither AJAX nor simple submit button (that would send the data trough PHP POST) works.

BTW: Is there any way to do simple PHP forms in Drupal?

From https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/7.x :

  This function should be used instead of drupal_build_form() when $form_state is not needed (i.e., when initially rendering the form) and is often used as a menu callback.

It still does a drupal_build_form under the hood, though, but at least you don't have to do it. Mind you, it may or may not work in your specific case, depending on where / how you create and call your form.


How to create tagadelic page in view? How can I create a Tagadelic page in a view? I create a tagadelic page in a view, but all tags display as a column.  See the below screenshot

But I want to display them in the following style:

Would you please tell me, how to change this style?
Many thanks

You can edit the field and then click on REWRITE RESULTS and check off the box strip HTML which will strip out all the html that is creating a line break between each tag. If you need more control you can use "Rewrite the output of this field" and wrap your field in its own element.


Create entity form as a table I am looking for a way to create a table entry form for an entity type. We are trying to create an invoice form.  I am currently using a field collection for each invoice line.

Order (node)
  Invoice (node)
    Invoice line (field collection)

I am currently using the field_collection module along with field_collection_table.  I am using entity reference to connect the invoice to the order and invoice line This works great except when we have more than roughly 75 rows.  At that point we are unable to add new rows to the table. Users are getting a 500 AJAX error.

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Internal Server Error
ResponseText:

Originally I received an error about max_imput_vars limit of 1000 when we got to about 50 lines.  I have since changed the limit to 100000.  Now nothing shows up in the server error log or the Drupal recent log messages.  My PHP settings are:

memory_limit = 256M
max_execution_time = 120
max_imput_time = 120
post_max_size = 160M
upload_max_filesize = 128M
max_input_vars = 100000

My thought now is to create a custom entity for invoice line.  The trouble is how to display this entity as a table and allow users to edit multiple items at once.  Some invoices could have 500 rows and I need a way for users to be able to quickly move from line to line.  For non-Drupal forms I have used jQuery to dynamically add new rows to a table.  Not sure how this would work for Drupal since each field in the table has an id that is specific to each row (e.g. edit-field-desc-und-31-value).

Any suggestions?  A separate but important issue is a need to regularly autosave.  Users would not be happy if they added 300 rows and lost power, computer froze, or something else happened.

We ended up going the route of a custom field collection table module combined with batch processing.  The problem was the standard Drupal way of adding rows using ajax.  Instead we created the rows dynamically using Javascript to duplicate the last row and all associated features tied to each field.  We then used a batch process to save the data.  This resolved the issue of the server timing out with lots of rows.


How do I filter a view within a view based on an Enity Reference field when NID is not in the URL of the container view's page? I have 2 content types: Artist & Artwork

Artwork contains an Entity reference field pointing to a single Artist called "Artist"

I have 2 views:

Artist Detail - A page view showing a single artist using title (artist's name) as contextual filter so url is human readable. eg. myexhibit/pablo-picasso
All artwork by an artist - A block view listing art by a specific artist using the "Artist" Entity reference field as contextual filter

I want to embed view #2 into the header of view #1 so that art tied to that artist appears on the Artist Detail page view.

I can get it to work if I change my filter on #1 to filter by Node ID and then pass that Contextual Filter to the embedded view. But I don't really want my URL to be myexhibit/213.

Is there a way to pass the node ID of the node matching the argument "pablo-picasso" to the embedded view?
Or a way to get the embedded view's contextual filter to work using a node title rather than the NID referenced in the Entity Reference field?

You can use myexhibit/NID url for this view page and then set up an alias (for example myexhibit/TITLE). If you want to make this page only for certain artists you can filter them by node ID.


Attach a particular profile2 form to user registration form I have about 3 profile types each with their own registration path. But there's one without a path.  I want to attach this to the main registration form. So that it shows when adding user on the main user add page but not other pages.

i got it to show with the code below but error when saving the user.

Recoverable fatal error: Argument 1 passed to profile2_save() must be an instance of Profile, instance of ProfileType given,, called in C://....

function short_fixes_form_user_register_form_alter(&$form, &$form_state) {
  global $user;
  $current_user_role = in_array('family',$user->roles);
  $form['account']['status']['#access'] = FALSE ;
  if($_GET['q'] == 'admin/people/create' && $current_user_role){
      $form_state['profiles'] = array(
        'family' => profile2_get_types('family')
      );
      profile2_attach_form($form, $form_state);
    }
}

try this,

$user_register_form = drupal_get_form('user_register_form');
$form_state['profiles'] = array(
'CUSTOM_PROFILE_TYPE_NAME' => profile2_get_types('CUSTOM_PROFILE_TYPE_NAME')
);
profile2_attach_form($user_register_form, $form_state);
print(drupal_render($user_register_form));


Views Table Grouping not working if group field is blank I'm using Drupal 7. In a field collection view, I have data in a table that has field groups. I have 3 fields I want to group on, the first two are required, the third is optional. Everything worked until I added the 3rd field. When there are records with no data in that field, the record shows up as a row of empty table cells. Can anyone suggest a fix for this?

I had a similar issue. If the field I was grouping by was empty in all the nodes under another grouping, no results would show. In my case it was State->Administrative Area, and if none of the nodes in the state had administrative areas no results would show under the state.

The solution that ended up working for me was to uncheck the 'Hide rewriting if empty' box in the Configure field: Content: Administrative Area->No Results Behavior section. 'Hide if empty' was already unchecked so I didn't fool about with it.


How to make an existing private OG group and its nodes public? I use Drupal Commons 7.x-3.12 (uses OG 7.x-2.7). There, I have a private group with private posts. (Means, the group node uses privacy settings "Joining requires admin approval" and "Hide contributed content from non-members").

I want to make this private OG group public, and all content nodes in it.

So I tried and set "Privacy settings: Any site member can contribute" when editing the group node, and rebuilt the permissions. This made the group node publicly visible, but none of its content nodes – neither those created before nor after this change.

How to make your private OG group public, and existing posts in it:

Make the group node public. Edit the group node and set "Privacy settings: Any site member can contribute". You did that already. It should be all there is to do, but due to bugs we have some more steps:
Make existing content nodes public. Set the group_content_access field of existing posts to "Public - accessible to all site users". For that, run the following command, replacing 3183 with the node ID(s) of your own affected group node(s). We use drush here, but you could also run it in the database directly.

drush sql-query "UPDATE field_data_group_content_access
  SET group_content_access_value = 1
  WHERE entity_type = 'node' AND entity_id IN (
    SELECT etid
    FROM og_membership
    WHERE entity_type = 'node' AND group_type = 'node' AND gid IN (3183)
  )"

(Note to self: Don't copy&paste such commands to a Freemind rich text node for adapting before executing. Saving, re-editing and then copying the node content will convert spaces to non-breaking spaces, making the SQL commands fail with confusing error messages.)
Check results. Check that the group_content_access field is now 1 for all nodes in your group. To do that, execute this, again replacing 3183 with your group node ID(s):

drush sql-query "SELECT entity_id, group_content_access_value
  FROM field_data_group_content_access
  WHERE entity_type = 'node' AND entity_id IN (
    SELECT etid
    FROM og_membership
    WHERE entity_type = 'node' AND group_type = 'node' AND gid IN (3183)
  )"

Make future content nodes public. Due to a bug, the Drupal Commons setting "Any site member can contribute" that we changed above does not properly change the relevant OG setting. This causes new posts to be still "Private - accessible only to group members" (value 1, in this case). So we have to change the OG setting ourselves. To do that, execute this, again replacing 3183 with your group node ID(s):

drush sql-query "UPDATE field_data_field_og_access_default_value
  SET field_og_access_default_value_value = 0
  WHERE entity_type = 'node' AND entity_id IN (3183)"

Rebuild permissions. Either do click the button in admin/reports/status/rebuild, or run:

drush php-eval "node_access_rebuild();"

Background knowledge and details

Setting the group node to "Privacy settings: Any site member can contribute" as you did does not affect already existing group content nodes because they have a separate field group_content_access that has been set at node creation to value 2, according to the then-active group settings (2 means "Private - accessible only to group members", as can be seen when editing a content type's group_content_access field via the Drupal CCK interface). So you have to set this field somehow manually to 1, which means "Public - accessible to all site users".
In order to change the group_content_access field, when using vanilla OG modules you can just change that in the node create / edit form as the field shows there. In your version of Drupal Commons however, it does not show there. This is a tweak via a hook, since Commons wants to simplify the group visibility logic by introducing the group-wide "Privacy setting" field. It means we had to resort to direct database manipulation above.
The "Group content visibility" (group_content_access) field has a third value 0, meaning  "Use group defaults". Using it leads to a fallback to the value of the "Group visibility" (group_access) field of the containing group, as confirmed here. It does not mean a fallback to group_content_access field of the containing group, as confirmed here (that field only exists if the group is simultaneously group content). Anyway, this fallback behavior is confusing and inflexible, as the fallback value does not allow to have a publicly visible group node with private content nodes. A rework is under discussion.
Drupal Commons 3.x-3.12 and newer has a workaround for this that enables having a publicly visible group node with private group content nodes. It's done with the combination of the group's privacy settings you used ("Joining requires admin approval" plus "Hide contributed content from non-members"). This is only a workaround however, since it means that all group content nodes have to set their "Group content visibility" field to an explicit value (1 or 2) rather than the fallback (0). It leads to the manual effort when wanting to change a group from private to public later, as you tried. This should be considered a bug that is still awaiting its real fix. I want to report this to Drupal Commons, but have to re-test with the newest release 7.x-3.19 first.


white page in taxonomy terms url I am using drupal 7, when I am going to path of  terms I see only white page, no error and nothing in another page I have not this problem,
 some php properties are :

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_WARNING
max_execution_time = 360
max_input_time = 120
memory_limit = 32M
upload_max_filesize = 32M
post_max_size = 32M
mbstring.func_overload = 2
mbstring.internal_encoding = UTF-8

where is the problem? and how can I solve it?

One thing to do when you get the WSOD is to turn on all error reporting to see what led up to the failure to produce output.  The error_reporting setting you show is turning of a lot of reporting.

You'll get more runtime error reporting by adding this to the start of settings.php on your site (you add it just below <?php):

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

In addition, navigate to: Administration→ Configuration→ Development → logging and errors and select All messages. This sets $conf['error_level'] = 2;.

Also, check the logs (in particular most recent log messages).

If I should try to guess, I would say you're out of memory.  Having a 32M memory_limit when running Drupal 7 does sound like a source for trouble (I've no Drupal 7 site with less than 128M).


How do I drush vset a number with decimals? drush vset latest_version 6.34a
latest_version was set to "6.34a"

So far so good.

drush vset latest_version 6.34
latest_version was set to 6.

Hmm...

drush vset latest_version '6.34'
latest_version was set to 6.
drush vset latest_version "6.34"
latest_version was set to 6.

Turns out that calling Drush as follows does the trick.

<-- language: lang-bsh -->

drush php-eval "variable_set('latest_version', '6.34');"

It also turns out that this is a bug, and that awesome greg_1_anderson fixed it within hours of me asking the question.


Form API, drupal_add_js() and setting a JS variable Consider

drupal_add_js(array(
  'radio86_media' => array('barfoo' => 'booboo')), 'setting'
);

and

$form['#attached']['js'] = array(
  drupal_get_path('module', 'radio86_media') . '/select_media.js',
);

These two 'lines' work well separately, but I think they could (and should) be combined so that the variable setting is set on the second line, combining the logic.

I've been fumbling around it and just can't get it to work. With this current way, I can console.log the barfoo variable via JS by using Drupal.settings.radio86_media.barfoo so it does work, but I really would like to have it combined.

Any suggestions greatly appreciated!

I never tried, but I guess you can do it like that :

$form['#attached']['js'] = array(
  array(
    'data' => drupal_get_path('module', 'radio86_media') . '/select_media.js',
    'type' => 'file'
  ),
  array(
    'data' => array('radio86_media' => array('barfoo' => 'booboo')),
    'type' => 'setting'
  )
);

According the documentation you should be able to add settings and files.


Notice: Trying to get property of non-object in function MY_MODULE_form_comment_form_alter() I have an error Notice: Trying to get property of non-object in function MY_MODULE_form_comment_form_alter()
This error is related to the line if ($node->nid == $comment->nid)  and I think to $comment->nid

I suppose that it is needed to describe $comment->nid  as an object like for $node->nid an expression $node = menu_get_object() was used. I was searching for this similar program code and with no success.
I have to use $form['#attributes']['class'][] = 'new-comment-form';  and that is why hook_form_alter is used.
Maybe there is another solution to this problem?

The code is:

function MY_MODULE_form_comment_form_alter(&$form, &$form_state, &$comment_count, &$comment) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(arg(1));
      if (isset($node->uid, $GLOBALS['user']->uid) && $GLOBALS['user']->uid == $node->uid && $GLOBALS['user']->uid > 0) {
        $form['#attached']['css'] = array(
          drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css.');
        }
    }

    $node = menu_get_object();

        if ($form['#node']->comment_count == 0 ){
        // hide a field
            drupal_add_css(drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE2.css.');
        }

        if ($node->nid == $comment->nid) {
            $form['#attributes']['class'][] = 'new-comment-form';
        }

}

You have the wrong function signature. It is supposed to be:

hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

In your function, $comment_count is set as the form_id, and $comment will always be null.

Set it to the signature above, then use $form['nid'] and $form['cid']. To get the comment count on the node, inspect at $form['#node']->comment_count

Here is a replacement code for what you are trying to do:

function MY_MODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->comment_count){
    // node has comments
    $form['#attached']['css'] = array(
        drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css.', 'file');
  }
  else {
    // no comments on the node
    $form['#attached']['css'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE2.css.', 'file');
    $form['#attributes']['class'][] = 'new-comment-form';
  }
}


Apply a ranged contextual filter to a date in Views I have an entity with a timestamp field that I would like to filter based on date. I can add a standard filter "between two date", type in two dates, and everything works great. However, contextual ranges do not work. I've read online that Drupal 7 allowed 2016-01-10--2017-01-01 or 20160101--20170101 as input and would display all results in 2016. These do not seem to work in Drupal 8. Is there a way to do range contextual filters in D8?

I've tried using a datetime field instead of a timestamp, and I am unable to filter this either.

Views Contextual Range Filter might do the trick for you. Install the latest beta and then see if you need to apply this patch. It's got just the functionality you're looking for.


Importing data into specific fields from CSV - into pre-existing nodes? I've used the Feeds module before to import nodes and users. I need to import data into new fields on pre-existing nodes - is that possible?

Feeds requires you to map a unique identifier in order to update existing content; I've not tried this but presumably if your existing content has a unique field/property which you can map to your import then you will be able to update existing content.


How do I get all the users in an organic group with specific role programatically? I'm trying to use rules to send an email to all users with a specific role in an organic group when someone requests to join the group.

This code almost works. It returns all users from a specific group ($GID) with the specified role ($RID), but it doesn't restrict the role to that group. In other words, if they have the appropriate role in another group, they're included in the results.

$current_members = db_select('og_membership', 'om');
$current_members->join('og_users_roles', 'ogur', 'om.etid = ogur.uid');
$current_members->condition('om.gid', $GID);
$current_members->condition('om.entity_type', 'user');
$current_members->condition('ogur.rid', $RID);

$result = $current_members->execute();
while ($res = $result->fetchAssoc()) { $members[] = $res['etid']; }

// Remove duplicate items.
$members = array_keys(array_flip($members));

What do I need to change to restrict the results so that it only returns users with the specified role ID within the specified group?

It's just a simple sql query, no joins needed:

ie. select uid from og_users_roles where rid=3 and gid=835;

  $members = array();
  $current_members = db_select('og_users_roles', 'ogur');
  $current_members->fields('ogur', array('uid'));
  $current_members->condition('ogur.rid', $rid);
  $current_members->condition('ogur.gid', $gid);

  $result = $current_members->execute();
  while ($res = $result->fetchAssoc()) { $members[] = $res['uid'];}

  // Remove duplicate items.
  $members = array_keys(array_flip($members));


YourTheme_links doesn't work on sub theme I have tried the way described in http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_link/7#comment-24463

But as it seems it works on the main theme but not on a subtheme.

function MYTHEME_link($variables) {
    print_r($variables);
    die;
}

Yeilds no result.

Applied on Zen theme which results the menus.

But on a subtheme it shows nothing. Anyone knows why?

I believe it is a typo, the function should be MYTHEME_link and not MYTHEME_links.Possible other ways to identify is use theme engine phptemplate_link instead of your theme name.

Try clearing your theme registry. Also Check whether you have spelled your theme machine name correctly.

function MYTHEME_link($variables) {
    print_r($variables);
    die;
}


how to disable and delete correctly the boost module in the last days Im having serious problems with the module boost, for some reason it is not loading the Javascript files, and CSS files. My site looks horrible for anonymous users its not loading the slider, but if I log in as admin then the site is displayed correctly, also after logout the site works correctly, but after clear browser's chache the sites looks horrible again

this is the errors that the console of Chrome shows me

Im almost sure that this problems are coused by the boost module, I need to reset it, or uninstall it, but need to know the correct steps for delete all the traces of this module that its causing me problems. Thank you

You have to delete the added boost code from .htaccess

In setting up the module you create this.

If you skipped that step you might check the htaccess tab in boost config and add those lines.

If you did not skip that step...

disable and uninstall the module then delete that added htaccess lines and directory.


How to customize the input phase of a custom field i'v created a custom field using this tutorial (http://www.slideshare.net/zugec/fields-in-core-how-to-create-a-custom-field). everything went ok and i successfully created a custom field which consists of three different text-inputs.

Now i'd like to customize the way the user inputs this field and can add another field: instead of the standard drupal visualization, i'd like to implement something like when you add your language proficency in the euroCV.eu, where each 'field' is a row and the custom inputs are cell, and when you add another field, you add another row.

i think i have to modify this hook

function instruction_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $base = $element;
  if ($instance['widget']['type'] == 'instruction_instruction_form') {
    $widget = $instance['widget'];
    $settings = $widget['settings'];

    $element['titolo_studio'] = array(
      '#type' => 'textfield',
      '#title' => t('Titolo di studio'),
      '#default_value' => isset($items[$delta]['titolo_studio']) ? $items[$delta]['titolo_studio'] : NULL,
    );
    $element['descrizione'] = array(
      '#type' => 'textfield',
      '#title' => t('Descrizione'),
      '#default_value' => isset($items[$delta]['descrizione']) ? $items[$delta]['descrizione'] : NULL,
    );
    $element['votazione'] = array(
      '#type' => 'textfield',
      '#title' => t('Votazione'),
      '#default_value' => isset($items[$delta]['votazione']) ? $items[$delta]['votazione'] : NULL,

    );

  }
  return $element;
}

but i'm not sure. Is there any tutorial on this?

If you are building a curriculum vitae type website you might want to see the eRecruiter distribution profile.

What is does is makes separate groups of fields as entities with the Field Collection module. Keep in mind that taxonomy vocabularies are fieldable in D7 so they can be attached to an entity such as a field collection. The made a module called Term Level that gives an option to add superlatives to the taxonomy terms that are just an entity in a field collection that are added to a node as a field.

It's just another way to look at the same problem.


hook_mail dosen't work? I have these two functions,
the first is to send the email via drupal_mail() function :

function example_function_name($what) {
  drupal_mail('MYMODULE', 'some_mail_key', 'myaddress@gmail.com', language_default());
}

And the second is the hook_mail function :

function MYMODULE_mail($key, $message, $params){
    switch ($key){
        case 'some_mail_key':
            $message['subject'] = 'test subject';
            $message['body'] = 'test body message';
            break;
    }
}

But I recieve a blank email in spam without neither subject, or body message.
Is there somthing missing here ?

Thanks in advance.

hook_mail is supposed to take message by reference. The way you do it, you are modifying a local copy, and your modifications cannot ever leave the function's body. It should look like this:

function MYMODULE_mail($key, &$message, $params){
    switch ($key){
        case 'some_mail_key':
            $message['subject'] = 'test subject';
            $message['body'] = 'test body message';
            break;
    }
}

This little ampersand is what makes all the difference. You cannot omit them. If API defined hook with reference argument, keep it a reference argument, or expect problems.


How do I access a custom variable in block.tpl.php? I created a custom module that defines a block. In hook_block_view(), I have the following code.

$block['content'] = theme('item_list', array( 'count' => $count));

How can I get the value of $count in block.tpl.php?

You have defined your block with hook_block_info(). Now you need to use hook_block_view() to add your variables to the content array which can be called in your template file.


Why does Views PHP give me NULL for $row->path? I have a views block to display only the titles of some few nodes. Titles linked to the single node. I want to have a CSS class .active added to the title's links when the linked path matches the actual called path. As mentioned in the comments below, I didn't got that class by default.

So I added a Global: PHP field right after I added and excluded a Content: Path field to access $row->path in the Global: PHP's output code field. But $row->path seems to be empty. dpm($row) gives me a path: NULL. Content: Path displayed gives me the right paths. But where's the path gone in the PHP field??? When was the moment it got nulled?

I still managed to do what I want with the nid. Though without the beautiful alias paths I'ld like to have.

Found a workaround for using the alias path in Views PHP: [SOLVED] Views PHP $row->path showing Null

drupal_lookup_path('alias', 'node/' . $data->nid)

Question still unanswered. Will report issue.


Find current layout name for a Panels Node? I'm using Panel Nodes for a layout, one of which is a specialized layout that will change the overall theme design (Namely hiding the header and footer).

However, I cannot seem to find a way to detect what the current layout being used is -- at least with Panel Nodes (panels_page_get_current() works only with Panels Pages, not Panels Nodes). See: http://groups.drupal.org/node/12565

Anyone have a clue how to detect whether a specific layout is being used by Panels -- and then, preferably, pass that on to theme suggestions?

Thanks!

The function panels_get_current_page_display() is what you're looking for:

$panel = panels_get_current_page_display();
$layout = $panel->layout;


How to set kint() to be closed by default? I find that when expanding Kint widgets, if the object is sufficiently large, the loading time can be quite slow. It appears, when you expand the root level, it also expands child objects. I would prefer that it keeps all children closed until I decide to expand; although I'm not sure if this will have any impact on performance.

Where can I configure Kint for Drupal?

I know this is an old question, but I just figured this out and this question comes up first on google.

The option is already there. What you need to do is click next to the plus sign (the text next to it) not the actual plus sign itself. Clicking the plus sign will expand everything, clicking the title, path or array key will just expand the immediate node below it.

I went through almost a whole project thinking Kint() unusable when it's really just a confusing UI choice.


In drupal 7 views, can views data be cached for logged in authenticated users? For drupal 7 views 3.x, can you cache the data for logged in authenticated users? And where would this setting be located? A screenshot would be great! thanks!

You click on the Caching link (here shown in the lower portion of the right column) and click Time-based (or whatever other cache()ing you have implemented on your system).

Then you can tell Views how long you want the cache()ing to be on the next menu presented:


Drupal Views pager shows last page when higher pager value is entered manually instead of page not found I have a view with pager. The views pager is not AJAX and the pager id comes is the URL as
http://d7.local?page=3
There are total of 15 pages in the view.
So the last page is http://d7.local?page=14
Now if I manually enter a pager number which is higher that 14 say 30 it redirects to the last page
Need to redirect the user to a 404 page under this situation.

Found a way out!!..
I used theme_pager and global variable $pager_total

Here is the code

/**
 * Implements theme_pager
 */
function theme_pager($variables) {
  global $pager_total;
  if ($_GET['page'] > $pager_total[0]) {
    drupal_not_found();
    exit;
  }
}


How to put drop down list of content type page in to another content type pages I have crated two content type like A and B .some of field are similar .I don't want to repeat that field .I want to put drop down list on any one of A or B.

YOU should use the entity reference module for the above purpose.

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field Four widgets: Two implemented on top
  of the Options module (Select and Radios/Checkboxes), Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field) Two formatters: A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.) A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode Integration with Views (for both forward and
  backward references) Integration with Entity Metadata (and as a
  consequence with Search API and the like) Integration with Devel
  generate Integration with Feeds and Migrate (>= 2.3) for painless data
  import This modules depends on Entity API and CTools.

  Modules extending Entity reference functionality:

Earlier answer deleted following comments :
If you want to use the existing field then just go to manage fields tab under Home » Administration » Structure » Content types » A and use existing field option where you will get the existing field of other content type
Check the image below for existing field option :

Or else you can do it in the following way :

You can get your dropdown list for content type in $form_state['values']['your_field_name_for_dropdown'] and

and Save that value in $_SESSION['module_name']['your_field_name_for_dropdown']
After saving that value you can use that value to insert into another content type in the hook_form_alter function or your custom_form itself.


"Source database does not contain a recognizable Drupal version." I have installed two Drupal sites in my local Ubuntu desktop 15.10 Apache2 (2.4.12) environment: One is a fresh install of Drupal 8 and The second is a copy of an existing working site built with Drupal 7 (which is mostly core-modules based, very humble by means of pages). Both sites are working fine without any problem, anywhere.

My aim is first and foremost upgrading the Drupal 7 site to Drupal 8. I did all the preliminary stages like configuring the same languages, Keep minimal by means of modules (uninstalling any modules in the D7 site that I could easily bring back after the Upgrade), making sure the same modules are installed in both sites, etc, and now I just want to "Transcend" (hope its a good phrasing) my Drupal 7 site into the fresh Drupal 8 one.

To achieve my aim I've installed the Drupal Upgrade module in my Drupal 8 site, went to localhost/sitename/upgrade, and filled in all the details of the Drupal 7 site.

When I clicked the "Review upgrade" button I got the error:

  Source database does not contain a recognizable Drupal version.

I've googled this error as an exact phrase ("Error") and found very few results; Most of them seem to me to require a PHP programming knowledge that I've yet acquired, so I can't determine if the error is due to a bug (especially since this module is still under heavy development) or due to my mistake in understanding the concept\functionality of this module.

What reasons are there that the D8 Drupal upgrade module wont "like" the D7 database I provided? Especially while the Drupal 7 site is working fine both online and locally.
Would migrating be a decent alternative for upgrading, if upgrading isn't possible for whatever reason? If so, what is the best most simple solution You could think of for migration?

I went to /var/www/html/benia/modules/migrate_upgrade/src/MigrationCreationTrait.php and did:

-- return $version_string ? substr($version_string, 0, 1) : FALSE;

++ return 7;
++ return $version_string ? substr($version_string, 0, 1) : FALSE;

Than got this error in top of the screen.

At this stage, I don't think there is a simple option to upgrade from 7 to 8. As you can see on the release note:

  Once you are ready, Drupal 8 core also includes the Migrate module to
  update existing Drupal 7 and 6 sites to Drupal 8 directly. Migrate is
  marked "experimental" in Drupal 8.0.0, but will be fully supported in
  an upcoming release.
  https://www.drupal.org/news/drupal-8.0.0-released

A little bit technical behind the scene:
From 7 to 8 version, they keep the same concept when building site (like node, entity, permission, views...) but not the core. I would say: they changed everything to OOP, Symfony component, architecture...
So there is no way to upgrade your drupal site directly from decent version to 8.0, you have to migrate. Here is how the migrating process should look:

Recreate the site with the same functionality to your d7 site.
Recreate the theme (using twig template)
Migrate content over

The cost to this process is (unfortunately) same to recreate a new site or more.
With the no 3, take a look at this article by Phase 2: https://www.phase2technology.com/blog/upgrading-to-a-drupal-8-site/


Does a new site installation run through hook_updates of every module? I have an existing D7 website for which i write hook_updates whenever i have to make any changes to the schema. Now, i have altered the taxonomy_term_data table using one such update. My question is if I install this website in another Schema(Database) will it automatically make those changes to taxonomy_term_data?
Or, do i need to make those changes again explicitly?

When you install a module, the largest number found in hook_update_N hook will be stored in the system table's schema_version field. It will not run the function. Just stored in the table.

When you copy a module to a new site, any of the hook_update_N hooks will not be executed for you. However, if you would like to make any change, you can implement hook_install to make the necessary database or any other changes.


Set location country based on coordinates Is there a way to have Location pick the appropriate country based on the latitude/longitude entered when the node is saved?

I believe Location has the ability to be added with a CCK field. The coords can then be converted into a long address. From there you should be able to pull out the country.

If you want to get even fancier you can use OpenLayers to show the location on a map. Does that answer your question?


update shipping profile on user update I use drupal commerce, I want if user info update if there is exist shipping profile update it else create new.

function mymodule_user_update(&$edit, $account, $category){
    $def_id=commerce_addressbook_get_default_profile_id($account->uid,'shipping');
    if($def_id){
       $profile=commerce_customer_profile_load($def_id);
       }
    else{
         $profile = commerce_customer_profile_new('shipping', $account->uid);
    }
        // Add the address value.
        $profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);
        $profile_wrapper->phone_mobile=$edit['field_mobile']['und'][0]['value'];;
        $profile_wrapper->phone_home=$edit['field_telephone']['und'][0]['value'];
        $profile_wrapper->field_user_addres = array_merge(addressfield_default_values(), array(
        'country' => $edit['field_user_addres']['und'][0]['country'],
        'thoroughfare' => $edit['field_user_addres']['und'][0]['thoroughfare'],
        'postal_code' => $edit['field_user_addres']['und'][0]['postal_code'],
        'locality' => $edit['field_user_addres']['und'][0]['locality'],
        'name_line' => $edit['field_name']['und'][0]['value'] . '  ' .$edit['field_last_name']['und'][0]['value'],
        'first_name' => $edit['field_name']['und'][0]['value'],
        'last_name' => $edit['field_last_name']['und'][0]['value'],
       ));
        // Save the profile.
        $profile_wrapper->save();
        //ym($profile,'message');
    //ym($account,'message');
}

but when I submit it in any manner ( even thought default exists) $profile filled by shipping default profile and create new shipping profile,
where is my fault? how can I update shipping profile?

Thanks Clive for get clue me about this prblem.
according  https://drupalcommerce.org/user-guide/configuring-creating-customer-profiles
`EDIT CUSTOMER PROFILE
Here we are editing the customer profile. Normally this might need to be updated to account for a customer who needs to change their shipping address or other kinds of updates. Note that the original customer profile does not get lost, we simply clone a copy of the original and make the changes. We are doing this action to show you how this process works. Note that this means, by default, if you edit a customer profile it does not change the original order.'


How do I print the output of a field as a link on node.tpl.php? How do I print the output of a field as a link on node.tpl.php? I'm able to print the raw output of a field using this:

<?php $display = array('label' => 'hidden');
$view = field_view_field('node', $node, 'field_podcast_url', $display);
print drupal_render($view);?><?php $display = array('label' => 'hidden');?>

The problem occurs when I try to make it as a link using this method:

<?php $display = array('label' => 'hidden');
$view = field_view_field('node', $node, 'field_podcast_url', $display); ?>
<a href="<?php print drupal_render($view); ?>">text

The output looks like this:

http://www.podtrac.com/pts/redirect.mp3/feeds.soundcloud.com/stream/211653270-scott-johnson-27-tms-846.mp3
">text

and the link points to this:

http://controldaily.dev/<div class=

I've looked around at solving this issue and can't find a solution. Anything else just shows nothing.

This looks like it's happening because you are trying to input the entire rendered field (including styling) into the links href.

As per the description:

  The field_view_value() function can be used to output a single formatted field  value, without label or wrapping field markup.

To use field_view_field, try something like:

if($node->type == 'article')
{
    $link_field = field_view_field('node', $node, 'field_href');
    print l(t($link_field['#items'][0]['safe_value']), $link_field['#items'][0]['safe_value']);
}

This example assumes a node of article type, and a field with a machine name field_href. running it through l() (despite using the safe value) will help ensure it is sanitised properly before being output.

You can also take a look at the Link field module:

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


How to edit and theme Comments & Comments form? I am building a drupal site using drupal 7 and the adaptivetheme.

I created some a content type called recipes. Than I created a content pane in views to present recipes in panels. I add the comments and comments form to the same panel.

Now I want to present beneath any recipe a comment form and all other comments.
My problem is that I  don't know how to edit the presentation of the comment form. When I checked the comment fields on my content type, I saw only the field "comment_body".

How can I edit the fields and the way they will show on Comments & Comments form?

Below is a screenshot.
I want to remove the field "your name", and change the button "save" to "post comment". How can I do that?

Thanks!

You can copy the file called comment.tpl.php from the folder where base AT theme is located (something like adaptivetheme\at_core\templates) and paste it into sites\all\themes\YOUR_AT_SUBTHEME\templates.

Assuming recipes is the machine name of your content type, you can also name it comment--recipes.tpl.php if you want to theme specifically comments for recipes.

Then with the help of comment.tpl.php API (you can also find a lot of information in the php file itself), you can edit the way your comments will be displayed.

I.e instead of

print render($content);

You can display specific fields :

print render($content['comment_body']);

or hide specific fields

hide($content['author']);
print render($content);

To alter the form itself, you need to use hook_form_alter() in a custom module.

/**
 * Implements hook_form_alter().
 */
function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //get the form id
  drupal_set_message("Form ID is : " . $form_id);
  $print = '
' . print_r($form, TRUE) . '
';
  drupal_set_message($print);

  switch($form_id){
    case 'YOUR_COMMENT_FORM_ID':
      //alter your form (with the complete correct fields names)
      $form['YOUR_FIELD_YOUR_NAME']['#type'] = 'hidden';
      $form['YOUR_FIELD_SUBMIT']['#value'] = t('Post comment');
    break;
  }
}

You can also use dpm($form) if you have Devel installed, or make a

$print = '
' . print_r($form, TRUE) . '
';
drupal_set_message($print);

in order to retrieve the exact form fields


How do I display multilingual logos in D7? I have read almost every tutorial on the net about how to setup multilingual logos. Yet, I cannot get anything to work.

How do I get multilingual logos to display in D7? I have added

$conf['i18n_variables'] = array(
    'logo_path',
    'theme_XXX_settings',
);

I have also uploaded using the form for the theme settings while in the langauge of the logo I want to display. All languages are set to whatever file I upload last.

Do I need to use a different variable in the conf array? Do I need to print a different variable other than $logo in the theme?

Can someone who's done this give some very specific instructions or provide a link to a recent d7 tutorial?

For D7, this is very painless.

In i18n, enable 'Variable Translation' module. To do so, be sure to have at least variable 7.x.2.x, else this module is not available. Here is the text from the module page:

Multilingual variables that switch language depending on page language.
Requires: Internationalization (enabled), Locale (enabled), Variable
(enabled), Variable store (7.x-2.x) (incompatible with version 7.x-1.2),
Variable realm (7.x-2.x) (incompatible with version 7.x-1.2)

After that, go to:

configuration->Multilingual settings->variables (tab)->Theme settings. check the boxes. Then go to your theme and set a logo for each language.

That's it!


Hide/show a custom block I have created a custom block of id downloadourapp and I would like to show/hide it base on certain statements.

I have create my custom module along with .module file where the code should be, however, I failed to find the right function to be used for that matter.

is hook_block_view_alter is the right function and how to hide or show this downloadourapp specific block.

Plugin ID doesn't equal Block ID, example.

isForbidden is not a static function, need to use forbidden.

if ($block->id() == 'downloadourapp') {

    // If the user's phone is Android.
    if(preg_match("/(android)/i", $_SERVER["HTTP_USER_AGENT"])) {

    return AccessResult::forbidden()->addCacheableDependency($block);

    }
}


Entity Background 'parallax image' positioning 'top' value issue when DOM is manipulated by other modules I am having an issue where the calculated value for the 'top' property that applied to the parallax-slider image is excessively large and pushing the image outside of the viewport.

In my case as you can see the 'top' property is 34946px which is 5X the height of my page content (6502px). After some testing I (believe) I have narrowed it down to a result of other modules manipulating the DOM and giving a miscalculation.

I am using the Responsive Menu module as well as the Adminimal Theme and Menu modules which both manipulate the DOM and create various wrapping and spacing elements. Disabling these modules give me slightly different results (however still and issue) This seems like it must be a jQuery firing order issue and these other DOM changes are interfering with the parallax.js calculations?

To confirm I have tested the following:

I have tested with versions 1.3.1 and the most recent 1.4.2 of the
parallax.js library with the same result
it is not a background colour issue :-p
Disabling the Responsive Menu module and viewing as an anonymous user  the parallax image is still being miscalculated but the number is about 15K pixels less than my initial test.

Can anyone else confirm having issues with these or similar DOM altering modules?

Also How can I alter the module firing weight?

For anyone coming across this issue, the real problem was not having a value in the 'speed' field.


How to I hide menu items based on its access to different roles? I have a site with the following users

Administrator
Author
Normal user(authenticated user)

and the modules used for the following task are Nice Menu, Menu token and Print.

The site contains of books and the option shown for every book page is shown in fig.

Administrator and Authors will have access to every option.
Authenticated user is not able to Edit Page and access the Page History.

By configuring the print module and using tokens I have accomplished the task, but it shows an "Access Denied" error when an authenticated user tries to select that option.

Is there a way to hide the "Edit Page" and "Page History" option for authenticated user and keep it visible to Admin and Authors?

Thank you in advance,
Ajit

We do this with the Menu Per Role module.

  This module allows you to restrict access to menu items1 based on user roles. It depends on the Drupal core menu.module—just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.


Why does updating the description of a custom block not update the block title? When creating a custom block, an editor is required to complete a description field. The description is then used as the block title (if displayed), as well as being used also for admin purposes on the block layout page.

If the description is later changed, the block title does not update and to do so requires a separate action of also updating the block configuration.

This seems like bad UX and is very confusing for editors.

Is there a valid reason for why blocks work like this?

There isn't really a reason, that's just how it works, the title of the block_content entity is an internal administrative title and while used as a suggestion for the initial block title, will then afterwards no longer have any effect on that.

You can place the same content block multiple times with different block titles.

While you think it's a bug, someone else might rely on it, it's not something that can be changed now, not by default anyway.


Views contexual filter based on nid (not from URL) I am using Viewfield module to display taxonomy terms of a node is referencing to. I am not using the default taxonomy field available in views because I want more freedom on manipulating the rendered taxonomy terms.

When I am in the node page I use contextual filters and I provide the default value from the URL. Easy. But...

For listing nodes of a taxonomy term I use views also and I want the same functionality in there.

The only way I can do this is by providing the default value from the nid of every node (row). So how can I get the nid as a contextual filter in such case?

Thanks

Use the Views Field View module and add Content: Nid as a field and check mark ☑ exclude from display.

Add Global: View a field and pass [%nid] token/replacement pattern as an argument as contextual filter.

Note: make sure it's arranged above your View field view so you have access to the [%nid] replacement pattern/token.


Is there a way to add the comment section to the node edit page? I am developing a site which will be used for information gathering.  All views are designed to send users to node edit pages (instead of node view pages) so that they can see and update information at the same time.  I would like to use the comment system, but I have not been able to figure out (yet) how to enable the comment section on a node edit page.  This section show up on the node view. I would like to know if there is a way to make it show up on the node edit page as well.

Take a look at this for setting up a custom edit template if you don't want it site wide: http://www.nybergtechnology.com/blog/2013/11/11/how-create-edit-tpl-node-type-drupal-7

then you should be able to add:

<?php print render($content['links']); ?>  // only if you want the links to show

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

to the bottom, to produce the comments. (I didn't test this, so it may be gibberish)


Path Redirect Import module getting "Line 1 contains invalid status code" I created a CSV file without the headers:

From URL    To URL  Redirect Status Redirect Language

But the file doesn't import and I get error messages:

  "Line 1 contains invalid status code"

My CSV file:

“file/sitemap.xml”, “sitemap.xml”,  “301”,  “en”

Looking at the csv row you provided, it looks like that the syntax is not correct:

Try to separate fields only with ',' and not with ', ' (comma + whitespace)
Use regular double " quotes or single quotes ', not these opening “ and closing ” double quotes you get when using word processors. I guess for the last two columns (status code and language) you won't need quotes at all.
You may also remove the headers line from the csv and check the "no headers" option if it contains non-ascii bytes.

See also this tutorial: Module of the Day: Path Redirect Import.


How to solve a situation where two or more routes with different controllers point to the same path ? For example, we have two routes, which points to the same path.

And each route has its own controller.

For example, I have defined a route with controller, which has a path "node/1", whereas a node with id=1 is already added to the site.

How can we determine, which controller will be started ?

And how can we select and assign forcibly controller to start, which we need ? For example, in my case for path "node/1" we don't want to start the NodeController, but we want to use the controller, defined in our module. Or Vice versa.

Drupal uses always the most specific route. If you define for the path /node/1

mymodule.routing.yml

route.for.node.1:
  path: '/node/1'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::content'
    _title: 'Override of node 1'
  requirements:
    _permission: 'access content'

then the custom controller \Drupal\mymodule\Controller\MyController::content is used instead of the node controller \Drupal\node\Controller\NodeViewController::view.

But I don't understand "Or Vice versa". For that you would have to remove the more specific route, so that the less specific node route for /node/{node} can take over again.

If you want a dynamic solution, you can route all nodes to your custom controller and then decide in this controller what to do, display the node or your own content.

For this you can extend the NodeViewController class and define a new view() function, in which you call parent::view() for the original node content. Then replace the class in a route subscriber:

$route->setDefault('_controller', '\Drupal\mymodule\Controller\MyController::view');

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


No content but empty row outputted by view I have a view as follows:

Display: Master
Format: Unformatted list
Fields: Content: Images
Filter criteria: Content type, published
Contextual filter: Content: Nid with 'Provide default value' set to 'Content ID from URL'

The view is placed on the node using Panels and Panalizer modules.

The node in question had no images uploaded to the image field but the view is outputting an empty row as follows:

I have checked and unchecked the 'Count the number 0 as empty' and ' Hide if empty' on the 'Content: Images' field but the view still shows.

How can I hide the view (by removing this empty row) if there are no images on a node?

Happy to attach any additional information you require to this post. Thanks.

You need to set a filter value on the image field.

Open your view, then edit as follows:

Enable 'Use Aggregation'.

Make sure that the image field is aggregating on 'Group Result together', using Group column 'Entity ID'. Sometimes views gives an error here, so just remove and re-add the image field with these settings.

Add a Filter criteria using 'field_image:fid', set its aggregation to COUNT, and choose the operator 'Is greater than' with value 0.

You might have to remove all of your sort criteria and re-add them as switching on aggregation mid stream can cause issues with sorting.

Basically, what you have done is to do a count on the image primary key (fid) for each node, and if the count is 0 to exclude the record from the result.

This should work for an image field that has either a single, or multiple values.

I you are uncomfortable working with aggregation, then have a look at the Field Count Formatter module. It adds a views field that simply count the number of values contained in a multi-value field. I would imagine it providing a filter in views as well.


Create referral url for user and add UID to hidden field when url used I need to create referral url for authenticated user. This url should be url for webform, and it should include user UID.

When user shares this url and someone uses it to fill webform it should set UID to the hidden field in webform - so admin can see whose referral url was used.

How to create this url?
How to set referred user UID to hidden field?

Can someone point me to the right direction where to start implementing this?

If I understand the question correctly, you want something like:

h(tt)p://www.example.com/register?uid=25

where register is a webform that the incoming person can access?

I would start by creating the form at the correct location with all of the elements you want
use some javascript (or form override) to hide the relevant form item that will hold the uid
override the form submit function to assign the uid in the url to the hidden element

take a look at the documenation for webform, and the Drupal Form API for specifics.


Drupal Webform Customization I'm using drupal 7, and I'm having a lot of trouble using the webforms.

I have a set of radio buttons, but each radio button needs to have an associated input field with it.

Code example:

<input type="radio" name="derp" /> option 1 : option 1 quantity desired: <input type="number" />

Note that this would span multiple rows, and is just to show the "layout" I am trying to achieve.

How can I add a "set" of input elements to a webforms radio select field?

Optional to answer but extra question: when I try to inject javascript into the webform using the markup option, my code is simply printed out onto the screen instead of being interpreted. Anybody know why?

You'll have to create your own webform component to ensure that validation and saving work as you intend. Look at an exisiting webform component to see how its done.


Custom entries in entity view modes? Background + question

I want to port entdispfieldui to Drupal 8. (issue)

The module allows a site builder to add new entries into an entity view mode, configure and position them among the regular fields. These entries exist per view mode / bundle / entity type.

I am wondering what would be the best way to achieve this in Drupal 8. Is one of the ideas below suitable? Why would I use one over the other?

Ideas so far

Idea 1: Extra fields + config entities

hook_entity_extra_field_info() allows to insert "pseudo" fields per entity bundle, but across view modes. The idea would be to use hook_form_alter() to remove the items from those view modes where they don't belong.

I found some documentation on extra fields here: https://www.webomelette.com/creating-pseudo-fields-drupal-8

Entries would be stored as config entities, with keys to determine to which view mode they belong.

For this, I started looking at https://www.drupal.org/docs/8/api/configuration-api/creating-a-configuration-entity-type-in-drupal-8

Idea 2: Learn from field_group and Display suite

field_group does something similar to what I am trying to do. Except that the entries are not pseudo fields, but groups. But still, these are entries or "things" that exist per view mode, and can be created and deleted.

But I found that field_group does not use a config entity type for this. Instead, in field_group.entity_display.schema.yml, I find this:

core.entity_view_display.*.*.*.third_party.field_group:
  type: sequence
  label: 'Field group settings on entity view'

Similar lines can be found in ds.entity_display.schema.yml or field_layout.schema.yml. Although these do not use type: sequence. I think this is because they store settings for the view mode itself, not for entries within the view mode.

So I wonder, what does the core.entity_view_display.*.*.*.third_party... mean, and why would I use this + type: sequence, instead of a config entity type?

And if I use this method, would it still make sense to work with hook_entity_extra_field_info() ?

I made it work!

There are many details to consider, so here is just a rough overview.

Storing the entries.

I decided to store the entries not in config entities, but as raw config entries. This seems easier, and prevents recursion with hook_entity_extra_field_info().

For each entry, we store:

Configuration that tells us how the item should be displayed when viewing the entity.
Optionally, an administrative label and/or a label for visitor consumption.

We do NOT store the weight (order / position between other fields). Thanks to hook_entity_extra_field_info(), Drupal will do this for us!

We do NOT store an id or machine name as a value within the entry. Instead, the machine name is part of the key referencing the config entry.

Each entry is identified by a key of the format "entdisp.vme.$entity_type_id.$bundle.$view_mode.$entry_machine_name".

entdisp.view_mode_entry.schema.yml:

entdisp.vme.*.*.*.*:
  type: ignore

Obviously this could be more sophisticated, but it works for me.

Crud forms for add + delete

Similar to field_group module, create forms to add and delete view mode entries.

E.g. admin/structure/types/manage/article/display/full will have an action link "Add EntDisP entry" leading to admin/structure/types/manage/article/display/full/entdisp/add.

hook_entity_extra_field_info()

Register extra fields per bundle, with placeholders for the label and other settings.

/**
 * Implements hook_entity_extra_field_info().
 */
function entdisp_entity_extra_field_info() {

  $ids = \Drupal::configFactory()->listAll('entdisp.vme.');

  $fill = ['', '', '', '', '', ''];

  $defaults = [
    'label' => '_',
    'visible' => FALSE,
  ];

  $extra = [];
  foreach ($ids as $id) {
    $pieces = explode('.', $id) + $fill;
    if (in_array('', $pieces, TRUE)) {
      continue;
    }
    list(,,$entity_type_id, $bundle, $view_mode, $vme_name) = $pieces;
    // $view_mode is not used!
    $extra[$entity_type_id][$bundle]['display']['entdisp_' . $vme_name] = $defaults;
  }

  return $extra;
}

hook_form_entity_view_display_edit_form_alter()

Alter the entity_view_display_edit_form.

In $form['fields'] and in $form['#extra'], we already find one entry for each extra field that we previously registered.

For each of the entry in $form['#extra'] that begins with 'entdisp_', do the following:

Check if the a corresponding entry exists in the settings.
If not, remove the entry from $form['fields'] and from $form['#extra'].
If yes, modify the element in $form['fields'][$name], to give it a label and configuration controls. Have a look at field_group_field_ui_display_form_alter() and at EntityViewDisplayEditForm in core.

This is all a bit tricky and more work than can be explained here. But it is easier than in field_group, thanks to the trick with hook_entity_extra_field_info().

hook_entity_view()

In this hook, for each item in $display->getComponents(), we

look up the corresponding config entry.
add a render element to $build.

It can look somehow like this: https://www.webomelette.com/creating-pseudo-fields-drupal-8


Give some users (e.g., teachers) access to nodes created by a unique subset of other users (that teacher's students) My site has roles for administrators, students, and teachers. Students create nodes, and each student has exactly one teacher. Teachers should be able to view all content created by their students, but no content created by other students. In other words, I'd like to have some kind of per-user setting that allows me to select one specific other user who can access the first user's nodes.

This seems like a pretty common situation, but I can't figure out how to do it. I'm open to any suggestions. Here are some things I've looked at so far:

I started out by using references to link each student to a teacher. However, I couldn't find a way to use that relationship for access control.
The subuser module looks appropriate, but I'm leery since the D7 version is still in alpha. Has anyone used it for this purpose?
Taxonomy access control looks like another possibility. The list of teachers is static, so it could be made into a vocabulary. But if Teacher is a per-student setting, is there a reasonable way to make that propagate down to the nodes created by that student?
Any other suggestions about how to do this?

I've had success with multiple node authors using
nodeaccess_userreference

Gives content access permissions to users for content that references
the users with User reference or Entity reference.

and also with
nodeaccess_nodereference

Gives content access permissions to users if they have access to
content that is referenced with Node reference or Entity reference.
Checks view, update, and delete grant operations, and can pass those
on to the referencing content, or trigger a different grant
configuration according to settings.

In combination with field_permissions or hook_field_access, for restricting access to the reference field, that should enable the feature you're looking for there.
You may want to look at using Rules to set the reference field value on node save as well.


Add some extra text(html+content) before start view. (Within the div from the view) I'm trying to put some extra hard coded HTML into a view before the sum of the view starts.

www.peace-in-the-city.be

On the homepage you see a section 'visitors'... it shows 4 recent visitors. If my client add a new visitor in the backend... This new visitor will show up a older one is disappearing...

But now my client wants to show one visitor (kermit the kicker) always on the left.

So i want to put that visitor hard coded in...
First i tried to put into the home.tpl...
But then it shows up out of the div around the view, and that f*** up my design. I used the classes from the view to style...

So now I want to put the HTML-code into the view self (within the divs from the view), put i don't find the solution...

Anybody? I tried some options "HEADER" in the view, but there is no space showing up where i can put the HTML-Code in...

Thanks for reading and support :-)

Kristof

In the header add the type Global: Unfiltered text and enter your HTML there.

A more Drupalish way would be

Mark "Kermit the Frog" as Sticky at top of lists in it's Publishing options on it's node edit form.
Alter the Sort criteria your View to have two criteria: Content: Sticky (DESC) followed by Content: Post date (DESC).


Custom join with an external database I am trying to join two tables on the same database, db2. I am trying to join tablename to tablename2 using the condition tablename.ItemID = tablename2.ItemID. While the values from tablename are selectable from a view, those from tablename2 aren't.
Do I need to specify in what database tablename2 is?
/**
* Implementation of hook_views_data
*/

function  mydatabase_views_views_data() {
  $data['tablename']['table']['group'] = t('Title name');
  $data['tablename']['table']['base'] = array(
    'field' => 'ItemID',
    'title' => t('db2'),
    'help' => t('Autoincremented ID field, to enable views integration'),
    'database' => 'db2',
    'weight' => -10,
  );

  $data['tablename']['table']['join'] = array(
    'deals_addon' => array(
      'left_field' => 'ItemID',
      'field' => 'ItemID',
    ),
  );

  $data['tablename']['ItemID'] = array(
    'title' => t('Item ID'),
    'help' => t('Item ID'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['tablename']['ItemInfo'] = array(
    'title' => t('Item Info'),
    'help' => t('Item Info'),
    'relationship' => array(
      'base' => 'tablename2',
      'base_field' => 'ItemID',
      'handler' => 'views_handler_relationship',
      'label' => t('Label'),
      'title' => t('Title'),
      'help' => t('Help'),
    ),
  );
  return $data;
}

Some time ago (D6) I was facing the same problem but then I could not find a solution. I ended up creating database views in my original db looking to the tables of the second db. This way, I was joining tables in default drupal db, which is easy. I dont know the exact changes in the api from d6 -> d7, but this might be an easy solution for you if you cannot solve it other way.


How to pass multiple IDs to a Views exposed filter? Is there any way to pass multiple IDs to a Views exposed filter?

We need to pass an array of IDs to the filter.

Notes:

There we can see operator "=" but it not taken 1,2 etc.
We have tried regular expressions to, but it also not working.
We are not using contextual filters.

You can pass it using contextual filter,

Remember to choose multiple selection

if we have url http://example.com/test/20+10+12


How do I access a node object property, if it is an array? $node = \Drupal\node\Entity\Node::load($nid);

Having loaded a node object in Drupal 8, I know how to access a property, if it is a single value, and assign it to a variable, $test in the example below:

$test = $node->field_1->value;

However, if $node->field_1 contains an array, how do I access it so that I can assign it to $test? So $test would equal something like:

array(0 => 'apples', 1 => 'oranges')

There's no real need to convert it to an array, as you can already access members of a FieldItemList as an array:

$first = $node->field_1[0]->value;
$next = $node->field_1[1]->value;

This:

$node->field_1->value;

Is just a shortcut to the first item in the collection anyway (see FieldItemList::__get()).

If you need the values in exactly the format you specified, FieldItemList is also iterable:

foreach ($node->field_1 as $delta => $item) {
  $an_array[$delta] = $item->value;
}


What is the best module for student registration form What is the best module to use if i want to create a
student registration form for my website.

Some of the fields in this form is referred to taxonomy and content types as entities.

Im a novice user of drupal 7
and cant find any mdoule that does this, I keep getting FORM API tutorial in my seaches but I when I checked it involves a lot of programming.. :(

Thanks

Webform module is pretty popular among Drupalers for registration forms. It is quite well supported and documented. It also has many cool in-built features and a few other 3rd party modules that bring in even more sizzle to the mix.

Good-luck to you friend & welcome to drupal.stackexchange.


How do views Contextual Filters behave with Pathauto? I have Pathauto installed, so URLs to nodes are not like node/3. My question is that if I write a View with a contextual filter for looking for node/3, will it work?

Note: This contextual filter is in a block. See this question.

You would get the node id(nid) as argument. Internally the system gets its data from the unaliased url, not the browser url created with path_auto.


Noitifications about security updates keeps coming after the update is done I have updated to core version 7.52 and I also ran the database updates accordingly. So why do the notifications keep coming? I have set the update check to be done once a day, and every morning I get an email that states that a security update is available for my version of Drupal. When I click the link the page opens and says that Drupal core is up to date.

I think this is the default behavior of the Update Status module, which is part of core. Unless you turn it off or reconfigure it, the modules will be checked daily and the site administrator will get email notices.


Is there a way to remove node titles? When I make a node such as a basic page I have to give it a Title by default. However, the Title also appears on the page when I am viewing it, but I do not want every node I have to come with a title tacked unto it.  For example, on some of my nodes, they are linked to the navigation bar, so it looks funny to see the same name twice when visiting the page.

Is there a way to remove the Title being represented on the page?

Have a look at the Exclude Node Title module.

  This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers.
  It provides a checkbox on node-edit pages for easier exclusion, or you can use the admin page to manually enter a list of node id's to exclude title.
  Also provides the option to hide all titles of a certain Content type.