Getting "Fatal error: Class not found" by bootstrapping external script and executing user_save function I have a problem i've struggled with for a long time, and it's starting to really piss me off, so i hope you can help me.

The thing is i'm writing a custom script (not a module) that needs access to the drupal user object, and it's profile2 fields, so i found out i could use the bootstrapper for this purpose.

Loading fields from the users profile works just fine, but when i try to make changes programmatically (user_save function for example), it fails with the following error, which makes absolutely no sense to me:

Fatal error: Class 'Drupal\gmap\GmapDefaults' not found in (root directory)\sites\all\modules\gmap\gmap.module on line 32

A function that would return this error could be something like this:

function custom_add_role_to_user($user, $role_name) {
              // For convenience, we'll allow user ids as well as full user objects.

              // If the user doesn't already have the role, add the role to that user.
              $key = array_search($role_name, $user->roles);
              if ($key == FALSE) {
                // Get the rid from the roles table.
                $roles = user_roles(TRUE);
                $rid = array_search($role_name, $roles);
                if ($rid != FALSE) {
                  $new_role[$rid] = $role_name;
                  $all_roles = $user->roles + $new_role; // Add new role to existing roles.
                  user_save($user, array('roles' => $all_roles)); // <---- This function throws the above error...
                }
              }
            }

If i don't call user_save(), everything works just fine, and until now i have been doing fine with direct sql queries, but i need to know why this doesn't work.

I've tried navigating to the GMap class to see what's actually going on at line 32
(Still not knowing why my simple script keeps referring to some random Google Map Module..?)

Here it is:

function gmap_defaults() {
 include_once(drupal_get_path('module', 'gmap') . '/lib/Drupal/gmap/GmapDefaults.php');
 return GmapDefaults::getInstance()->getDefaults();
}

So why is the bootstrapper calling this random module, and what is wrong with the module first of all???

It seems like it doesn't get to create the namespace required correctly. But i don't see where it goes wrong?

drupal_get_path returns the right path... I've tried to put a static path instead, to see if that made any difference... It didn't...

Thanks in advance for your help.

The correct answer could be to also use the necessary namespacing when instantiating the GmapDefaults class:

include_once(DRUPAL_ROOT . base_path() . drupal_get_path('module', 'gmap') . '/lib/Drupal/gmap/GmapDefaults.php');

$macro = !empty($field['settings']['gmap_macro']) ? $field['settings']['gmap_macro'] : '[gmap ]';
$map = array_merge(Drupal\gmap\GmapDefaults::getInstance()->getDefaults(), gmap_parse_macro($macro));

Note that I also converted the original include to an absolute path based include to make sure the path is correct...

I just prepended the necessary namespace before "GmapDefaults::" and it works.


Disable transition effect field slideshow I have installed the Field Slideshow module.

I want to set the transition effect to none in manage displays (content type).
How can this be done, I tried to set the interval to 0 but the slideshow keeps going.

Set "Transition speed" to 0 (zero) and it won't have any transition effect, just the direct change of image.

If you want to stop automatic changing of images, set "Timeout" to 0 (zero).


Setting a URL alias breaks the relative image paths on those pages. Is there a way to fix this? I set a URL alias for one of my content type pages. So now every 'newsroom' content type is at http://myurl.com/newsroom/name-of-article. That's perfect. But that page also has blocks that contain images and now the paths to those images are broken.

my block contains: scr="sites/default/files/mobile-nav.png">
but the page is trying to find the image at src="NEWSROOM/sites/default/files/mobile_nav.png"

The block that contains the image is on every page of the site because it's the mobile nav.

How do I change my url alias? Or what do I need to do to tell drupal how to find the images correctly while keeping the image path relative?

src="sites/default/files/mobile-nav.png"> should be src="/sites/default/files/mobile-nav.png">

Please note the additional "/" before "sites." Without the forward slash the image will always be called from wherever you're at on the site so if you were at say site.com/news/ it would look for the images in site.com/news/sites/default.... if you don't have the forward slash before sites.


Override html.tpl.php by content/node type I'm trying to build a new template for PPC landing pages. The template design is very different than the main template, therefore I'm trying to override html.tlp.php for a specific content type.

The content type machine name is "landing_page".

I've created the following:

html--landing_page.tpl.php (everything in the header and footer)
page--landing_page.tpl.php (everything in the content area)

I got Drupal to read page--landing_page.tpl.php, but can't get it to read html--landing_page.tpl.php instead of the default html.tpl.php.

I've already tried the code at Override html.tpl.php per node type, but it doesn't work even after clearing the cache multiple times.

Here's what my preprocess_html function in template.php looks like:

  function bartik_preprocess_html(&$variables) {

  $node = menu_get_object();

  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
  }

 /* if ($vars['node']->type == 'landing_page'){
     $vars['theme_hook_suggestions'][] = 'html__landing_page';
  }
*/

  if (!empty($variables['page']['promo'])) {
    $variables['classes_array'][] = 'promo';
  }

  if (!empty($variables['page']['triptych_first'])
    || !empty($variables['page']['triptych_middle'])
    || !empty($variables['page']['triptych_last'])) {
    $variables['classes_array'][] = 'triptych';
  }

  if (!empty($variables['page']['footer_firstcolumn'])
    || !empty($variables['page']['footer_secondcolumn'])
    || !empty($variables['page']['footer_thirdcolumn'])
    || !empty($variables['page']['footer_fourthcolumn'])
    || !empty($variables['page']['footer_fivecolumn'])
    ) {
    $variables['classes_array'][] = 'footer-columns';
  }

  drupal_add_js(path_to_theme().'/js/jquery.actual.js');
  drupal_add_js(path_to_theme().'/js/custom.js');

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}

replace

$vars['theme_hook_suggestions'][] = 'html__' . $node->type;

with

$variables['theme_hook_suggestions'][] = 'html__' . $node->type;


node access by related fields I have created the following List field type of checkboxes to allow users to select their own content's privacy settings when creating a node called RideShares:

1|me only
2|any registered site member
3|users on the same flights as me
4|users arriving at the same airport during the same week as me.
5|public

I can use the exposed filter to manually select any matching nodes, but do not know how to automatically filter the queried RideShares to the current user's data in other bundle/content types. For example, whether the current user has entered a Flight into where the destination airpor catches one of the existing RideShares.

It seems this cannot be done with context filters in Views.

I can use the exposed filter to manually select any matching nodes,
  but do not know how to automatically filter the queried RideShares to
  the current user's data in other bundle/content types. For example,
  whether the current user has entered a Flight into where the
  destination airpor catches one of the existing RideShares.

Views is a simple query builder. Typically this would be SQL like Select * From RideShares Where city = 'denver'. Your question cannot be expressed in single SQL expression you would need JOINs in SQL of PHP and multiple queries to arrive at an answer.

Your talking about relating a set of results with additional logic or data-sources.

This can be done in Drupal using a combination of Views Relationships perhaps Attachment Views to build results you want.

For example I might create a Nodequeue of uids that are users on the same flights as me and examine a View result that uses the Nodequeue as a Filter against the current user to see if that logic produces any results.

You could then place many view blocks on a single page that acts as a search results page. Each block can be a View with many view-attachments, etc.


drupal_goto argument retrival I am redirecting my users with the following code:

drupal_goto("event/registration/failed",
    array(
      'query' => array('nid'=>$submission->nid, 'sid'=>$submission->sid),
    )
);

On the target page I am executing the following function:

function _event_registration_failed($nid, $sid){
  dsm($_REQUEST);

  drupal_set_message("TESTING NID: {$nid}");
  drupal_set_message("TESTING SID: {$sid}");
}

My the variables in the drupal_set_message calls do not have any data.
But, the $_REQUEST object above has the data I expected.

Is there a correct way to access argument passed with drupal_goto or is it correct to use the $_REQUEST object array?

Query arguments are available in $_GET. Drupal doesn't handle those query arguments for your menu callback; the only query argument Drupal automatically handles is $_GET['q'], which is the path for the requested page.

By default, $_REQUEST contains the contents of $_GET, $_POST and $_COOKIE. Drupal uses $_GET for the requested page path, and I would rather use $_GET also in this case, just to avoid possible conflicts.

In your case, those query arguments are accessible with $_GET['nid'], and $_GET['sid'].

If you define the menu handler with code similar to the following one, then your menu callback gets those values as arguments.

function event_menu() {
  $items["event/registration/failed/%/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($nid, $sid) {
  // …
}

You could get the node object, instead of the node ID, if you use the following code.

function event_menu() {
  $items["event/registration/failed/%node/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($node, $sid) {
  // …
}


Different Terms&Conditions on multi-site I use Legal module to display terms & conditions to the user, but now I need to create different T&C text for different sites created with Domain Access. Is it possible?

In Drupal 7 Domain Variable module will help you, in Drupal 6 this is not supported probably.
Domain Variable:

This module aims to be a replacement variable handling module for Domain Access, allowing mixed variable realms (domain x language) to be configured.
In other words, it allows setting different variable values for each domain and for each language at the same time.
This module supports almost all of the functionality provided by Domain Configuration, Domain Settings and Domain Theme. Differences are listed in the documentation.


Number items in a grouped view, resetting counter with each group I've got a view (D7, Views3) that is grouped by a relationship-based title field (set in Format: settings), and I'm using a Global: View result counter to give each item a number. This is how output currently looks:

Some group

1...An item

2...Another item

Another group

3...More items

4...Still more items

5...Even more items

It's counting rows regardless of position in groups. I want it to reset the counter with each group, to look like this:

Some group

1...An item

2...Another item

Another group

1...More items

2...Still more items

3...Even more items

Seems like a simple enough task - but I can't find any options relevant to this. I don't mind writing some code to achieve this, but Views is so dense I have no idea where to start.

Can this be done without coding up some hooks? If so how?

If not, where and how in the thicket of data that is a views object could I identify where within a grouping each Global: View result counter field row is?

EDIT: looking at the very simplistic code in views/handlers/views_handler_field_counter.inc, it looks like a custom module based on this code would be the best option, creating a new global field that uses groups instead of the pager. This would need to find data about each group (probably in $this->view somewhere?), and would identify its own row's position in the appropriate group. Is this possible? Again, not really sure where to start.

EDIT 2: No sign of useful grouping data in the view object that I can see, but this thread suggests that maybe it's sorting data that should be used for this?

You can use the HTML List format. In the settings of this format, you can set the grouping field and then set the list to an ordered list.
By doing this, you won't need any global counter.
See in the following screenshot how the list would be rendered.


Error after upgrading ecommerce kickstart is breaking my start I'm working on someone else's project that hasn't updated its "Commerce Kickstart" (commerce_kickstart) module in a long time.  After I upgrade it using Drush, the site breaks and I'm left with the message when I navigate to the (development) website:

Fatal error: Call to undefined function commerce_info_fields() in C:\xampp\htdocs\amherstcopy\sites\all\modules\commerce_price_table\commerce_price_table.module on line 560

I googled around for the answer, but had no luck.  Anyone know how to fix this?  Thanks.

The only reason commerce_info_fields() should have gone AWOL is if the commerce.module file was removed from your server or the module was somehow disabled during your update process. Check those two things: if it's missing, put it back. If it got disabled, try to re-enable it. No clue what about a drush based update would have caused the issue, but I also am unfamiliar with how drush updates distributions. For reference, we document how to update here:

https://drupalcommerce.org/commerce-kickstart-2/install


Get the default image for a profile2 image field with code I need to get the fid of the image specified as the default for an image field in a profile2 profile.

There is a field_get_default_value function, but it is not clear to me how to use it.

I'm using Drupal 7.

You don't need to bother with the field_get_default_value function, you can use the field_info_field function. For image fields, it will provide the fid for the default image in ['settings']['default_image'].

Suppose your field is "field_picture", then this will get you the fid and file:

$info = field_info_field('field_picture');
if (!empty($info) && $info['settings']['default_image'] > 0) {
    $default_img_fid  = $info['settings']['default_image'];
    $default_img_file = file_load($default_img_fid);
}


How to use rules to store field value? I am writing a rule to store Tenant field's value to Previous tenant field whenever the Tenant field is updated and saved. The following are apartment and tenant content types.

Apartment content type:

Room
Tenant (entity reference to Tenant content type)
Previous Tenant (unlimited number of values is set for this field)

Tenant content type:

Name
Phone

And this is my rule:

{ "rules_tenant_records" : {
"LABEL" : "Tenant records",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--apartment" : { "bundle" : "apartment" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "node-unchanged:field-tenant" ], "field" : "field_tenant" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-previous-tenant" ],
      "value" : { "value" : [ "[node:field-tenant]" ] }
    }
  }
]

}
}

It does not work, any suggestion?

Do following steps:

Instead of Set data value use Add an item to a list in action. In List field select node:field-previous-tenant, in Item to add field select node-unchanged:field-tenant. At last add an action Save entity and select node in Entity field.


Is it possible to edit Views code instead of the ui? I'm aware that I can export and import a Views code. I'm wondering if there is a way to edit and add relationships or contextual filters of a current view within the code instead of the UI.

The reason is sometimes its just easier to add the code rather than drilling down to the relationship within the UI.

If not, I guess the workaround would be to export, then change, then import and overwrite. Not sure how this will effect the site if the views were created from a module installation.

An easy way to do this would be if you had the features module that will contain the code of the view.  Otherwise this information is stored in the database.  Simply enable the module, create a new feature and add your view to it.  Then it will be stored in code for you to alter.


How to display picture from field near every blog entry When I go into mywebsite/blog I have blog entries displayed. What I want to do, is display a picture uploaded to every blog entry left to the entries displayed on this page. How can I achieve this? Is there some code to display uploaded picture in page--blog.tpl.php? I also would like to NOT display picture when someone actually click and goes to some single blog entry.

You should be able to do this with standard field visibility.

Add an image field to your blog type.

Then click on display fields, you can have it displaying for teaser view, and hidden in the full view.


rules - check if email is in use I would like to create user account using rules, after anonymous user creates a node and inputs his email to a email field. Before that I need to run a condition if the email is already in use.
What would be the easiest way of doing this? Using fetch entity by email or using custom php?
I read about user_authenticate function but I do not know how to use it.
Thank you for advice.

$check=db_select('users','u')
    ->fields('u',array('uid'))
    ->condition('mail','user email comes here','=')
    ->execute()
    ->fetchField();

if($check!='')
{
    form_set_error('mail','Email Already Exists');
}

You can use this.


Redirect on Custom page after one time login link I created password reset link using user_pass_reset_url function. This is redirecting to user/uid/edit page after click login.

How to redirect on custom url?

Since the form builder for user/reset/%/%/% (user_pass_reset()) is using the following code to redirect the user, you can only replace the form builder with one that redirects the users where you want.

      $token = drupal_hash_base64(drupal_random_bytes(55));
      $_SESSION['pass_reset_' . $user->uid] = $token;
      drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));

If you do that (which means implementing hook_menu_alter()), be careful of how the workflow is modified. If you need to change that radically, and you want to be sure not to introduce security risks, I would rather:

Alter the URL returned from user_pass_reset_url(), so that users are redirected to your page
Implement a form builder for your page using the code used by user_pass_reset() as guideline


Dynamic local tasks to the same route with slug I have a route set up with a slug accepting taxonomy terms (routing.yml):

example.column:
  path: '/column/{taxonomy_term}'

I would like to add (secondary, although that's not important) local task tabs on a page, one for each possible term of the vocabulary used (links.task.yml):

example.column_list:
  deriver: 'Drupal\example\Plugin\Derivative\ColumnTasks'
  parent_id: example.parent

The deriver is pretty straightforward and simple and mentioned in a few docs on drupal.org, the relevant part is:

foreach ($columns as $column) {
  $route_name = 'example.column';
  $this->derivatives[$route_name] = [
    'title' => $column->getName(),
    'route_name' => $route_name,
    'route_parameters' => ['taxonomy_term' => $column->id()],
    'parent_id' => 'example.parent',
  ] + $base_plugin_definition;
}

The problem is that this code, obviously, doesn't generate more than one tab because all go to the same $route_name. But I'm not allowed to use any other route name (suffixing it with the term, for instance) because it complains about a non-existent route then.

Do I have any other solution than to generate all the routes separately, using a _route_callback? This would somehow feel wrong, going against the reason for the existence of slugs in the first place.

The array key is not the route name, it's the machine name of the local task. It's pretty common to use the same string but that's in no way a requirement.

Just use a different array key and this should work.


Modify bulk_views edit user message I have been trying unsuccessfully to alter the text of the message in the bulk submit.
The code, place inside _views_bulk_operations_direct_process ,producing the message is:

$context['results']['log'][] = t('Performed %operation on @items.', array(
  '%operation' => $operation->label(),
  '@items' => format_plural(count($entities), '1 item', '@count items'),
));

How can I modify this? The message is displayed on any change made on the bulk view by the edit form(hook_form_views_form_og_members_admin_default_alter).

Use the string overrides module - anything passed through t() will be caught by this and it provides an admin interface similar to the localization functionality to make it easy to look up these strings and translate or change them as you like. It also recognizes variables so you can still use the context of the function. From the module:

  Easily replace anything that's passed through t()
  Locale support, allowing you to override strings in any language
  ...
  Note that this is not a replacement to Locale as having thousands of overrides
  can cause more pain then benefit. Use this only if you need a few easy text
  changes.

You can also do this in your settings.php file with a simple array, ex:

$conf['locale_custom_strings_en'][''] = array(
   'Performed %operation on @items.'      => 'Your Changes',
);

This handbook page covers both of these methods in much more detail.


how to set date field not to display past date In a content I need a date field for which I have used Date module. Widget type used for this is popup calender. But when the calender popup appears I want to display only today's date and future dates, I don't want to display any of the previous date, not even a single day.

How could this be achieved?

You can use the Field validation module to create validation for the date field.

You can follow below step to achieve this.

Go to  Administration -> Structure -> Content types and it will
display the list of content type.
Click on 'Manage Fields' links for your content type and it will display the list of fields for your content type.
Edit your 'Date field' from the list of fields.
Select '0 years from now' from the drop down 'Starting year' under 'More settings and values'. It will not display the previous year date in the popup.
You can set the default values for the date field under 'default values' section.
Save the settings.
Edit again your fields.
Click on 'Validation' tab in top of page.
Click on 'Date range2' link in the page.
Select 'value' from the drop down 'column'
Select 'Cycle of date' as global and set '-0 day' for the 'Minimum
date' textfield. Now, it will generate the error if date is less than today's date.


Is it possible to render an Adsense Block as a custom field block in Drupal? I'm trying to add an adsense banner inside my content and Drupal's Adsense regular module doesn't do that. It can only add Adsense in one of my regions but none within articles. Would that be possible using Display Suite?

You can use Block Inject to create an arbitrary region in your node body. Then place the adsense block in that region. (Please be aware of this issue.)

On a page by page basis, you can also use Insert Block, but there are limitations.


How to allow users to create only one group using Organic Groups 7 I am trying to use OG7 to get users to create groups as companies - i.e., each group set up will be a company. I would like to to make sure that ea ch group admin can only create one group (i.e., her/his company); and the "add content>> group" link is disabled or not displayed once a company has been created.

How do I do that?

You could try Node Limit module to limit to one the number of nodes of your group content type to be created by user.


Address field "Same as above" I have 2 address fields : Res. addr and Permanant addr.
On clicking another field : same as above

I want to copy all the values entered in Res. addr to Permanant addr.

Please let me know how to do it?

Thanks,
ronforever

There is no simple solution, and therefore I'm not sure this question is good for the Drupal Stack Exchange. It's going to be a matter of custom JavaScript or AJAX Form API code, and it will be dependent on how you're using Address Field and what sort of form you're integrating it into.

Based on the comments below, though, I'd add that there's nothing particularly challenging about this. If both sets of form elements are on the same page, it's a simple matter to use JavaScript (especially with jQuery) to copy the data from one form field to the next. There just isn't a simple property to toggle within the form API code itself.


How do I fix this Configuration Directory sync error? I can't get past this error while installing drupal on my localhost.

I've chmod'ed permissions on my core /default directory. I've:

/default on 755
/default/files including all subfolders and files on 744 (or 755)
/default/themes including all subfolders and files on 755
/default/modules including all subfolders and files on 755
/default/settings.php and /default/default.settings.php on 444

I've even double checked my apache configs to prepare for drupal8 install.

I'm stumped. I'm out of room to config everything. What's the proper course of action to fix this problem?

Create the directory specified in the error. This is fixed in an upcoming release.


how to set an absolute position to a view (or div class)? I have 2 views that displays ads on both sidebars of the page. on top of one of them, is another view that displays articles. the view that displays articles can be a height of anywhere between 20px, and 200px, depending on how many articles there are at the time. I need the ads underneath it to be aligned with the ads on the other sidebar. If I use something like margin-top, it will only work if there are the same amount of articles throughout the life of the site. I was hoping to do something like anchor the view to the bottom, or to set a specific position to put the view.

If you have the div's parent element set to position: relative, you can then set the ad div to be position: relative and give it and offset from the bottom. eg. bottom: 20px;
You will need to be careful that your article list div doesn't expand over the space where your ads are as they will overlap.
Post a link if you need more help.
Hope this helps.


Empty response after a callback in form_alter I am trying to add a new field in a preexistent form and invoke a callback.
The response of the callback is alway an error with an empty response:

  An AJAX HTTP error occurred.
  HTTP Result Code: 200
  Debugging information follows.
  Path: /system/ajax
  StatusText: OK
  ResponseText:

ResponseText is always empty.

The code I use in my_form_form_alter() is the following.

$form['country_views_exposed_form'] = array(
  '#type' => 'select',
  '#title' => t('Country'),
  '#options' => array(
    'sl'  => 'Select...',
    'au'  => 'Australia',
    'nz'  => 'New Zealand'
  ),
  '#ajax' => array(
    'callback' => '__my_callback',
    'wrapper' => 'country-views-exposed-form-wrapper-',
    'method' => 'replace',
    'event' => 'change'
  ),
  '#attributes' => array('class' => 'views-exposed-widget')
);

All I put in __my_callback() produces the same result: I don't get a clean response.

function __my_callback(&$form, &$form_state) {
  return $form['states_views_exposed_form'];
}

I have resolved.
Exposed form fields don't are the same of 'normal' form fields in drupal. I have applied the patch #46 listed here: http://drupal.org/node/1183418


How can I make a read only field  form with node authors' mail address on node edit page? I would like to make a read only field form on a node edit page prepopulated with the e-mail address of the node author.
I tried Markup module but couldn't get it done.
Is there anyway to do this?

see http://drupal.org/project/field_permissions,
from module description:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


D7 Why I cannot just copy a template file from a module to my custom theme to override it? I'm using the TimeField module with a custom theme (a subtheme of the Bootstrap theme) and I want to change how the output is rendered.

There's a timefield.tpl.php file located at

  sites/all/modules/timefield/theme/timefield.tpl.php

which I want to modify copying it to

  sites/all/themes/my_theme/templates/

but when I do so the copy is ignored and the original file is loaded instead.

I'm a Drupal newbie but I like to learn, so any advice or link to a resource to understand where the problem lay is fine.

Create tpl file for field field--field-name.tpl.php. place it to your theme.

  if Field name is: field_page_photos
  then File name will: field--field-page-photos.tpl.php

copy sites/all/modules/timefield/theme/timefield.tpl.php code to above tpl file.
make changes and clear cache.


Users restricted from editing own profiles I found that non-site-admins cannot edit any of the custom fields attached to their profile. I have found the Organic Groups (fixed) feature request "Authenticated users cannot edit his custom profile fields" that appears to explain the issue, but that's not clear enough for me.

Who exactly is the Group Audience for the User (the User?) and how do I set up the settings correctly to ensure all users can access and view their custom profile fields?

Is the User a "Group" and the Custom Profile Fields "Group Content"?

It turned out that the permissions needed to be rebuilt as well as verified that that the user had the ability to edit the "Group", which are actually there own user profiles, albeit confusing with the labels.


D8 Views Template Suggestions Being Ignored I went through other questions/answers on this topic and I am still stumped. My added template suggestion for a Views Exposed form is being ignored.

function talon_theme_suggestions_views_exposed_form_alter(array &$suggestions, array $variables) {
      $suggestions[] = $variables[form]['#id']. "__ef";
}

Template name in theme: views-exposed-form-views-programs-block-1--ef.html.twig

Theme Debug lists suggestion as: views-exposed-form-views-programs-block-1--ef.html.twig

A template name suggestion has to start with the theme hook and two underscores. You find the theme hook in the twig debug output, in this case views-exposed-form:

$suggestions[] = 'views_exposed_form__' . $mycustomdata;


How to add 'Welcome {username}' in blocks with Drupal 7 I am replacing a drupal 6 website by a drupal 7 one with the same content.
On that Drupal 6 website there is a block that comes visible when you're logged in.
As  heading it shows the message 'Welcome {username}' in that block.

I'm looking for a way to do that in Drupal 7, i tried to do this with the module 'Token' but i doesn't work. What's the best way to do this?

Either in a block or in a custom module that adds a block, add the following code:

if (user_is_logged_in() == TRUE) {
    global $user;

    print "Welcome " . $user->name;
}
else {
    print "Please log in.";
}

This is more useful if you want CURRENT user information.  Possibly this as well for the user_is_logged_in function.


Any module for user to custom make a schedule from listed options? I'm looking for a module which can do something pretty specific. For a conference that our organization hosts, we have many different sessions during the day. People can pick and choose which one they want to attend.

We would like to create a page which will 1) list all the sessions available and 2) allow people to "favorite" or "pick" from these sessions which will add them to a smaller list, which they can view on a separate page. Ideally this will not require individuals to be logged in, but rely on cookies.

Does anyone know of a module with functions like these? It could really be a view with more robust features, but I can't find an extension of Views which has these features.

I haven't done it persay. But, having attended many Drupal Camp's and 1 Drupal Convention I know the Conference Organization Distribution (COD) has this basic feature-set built it.

COD include the concept of Sessions, and session collections. I know that users can select tracks to register for (typically in a day-calendar view) and then a users session list appears on the users dashboard/account page.

I would recommend either downloading the COD distribution and using it directly, or viewing the install profile of COD and the included content types, Fields, Views, Rules, etc and reverse engineering the functionality you want on a smaller scale.


How to override 'views-slideshow-pager-fields.tpl.php'? I'm taking over one of my co-workers project (i'm new to Drupal...).

I was able to override other view templates such as 'views-view--[my content type].tpl.php', 'views-view-fields--[my content type.tpl.php', but I wasn't able to override 'views-slideshow-pager-fields.tpl.php'.

What naming convention should I use to override the file?

Views Slideshow is a separate module.  This video from MustardseedMedia addresses theming for the module. I have not watched it yet, let us know if it addresses your needs.


How to add images (as entity) in ckeditor? The background: I'm creating an asset management system with Drupal, so for this purpose I've created a content type called Image which has an image (widget) attached to it. I then use module Entity Reference to link this content type with other content types (for instance, Article).

So far so far. This works for my requirements, however I'd like to:

1) Add the ability to upload a new image (therefore new node) from within Article
2) Use an existing entity (previously created) within CKEditor in Article

Is it possible? How?

I would take a look at something like Shortcode module. In general you are looking to insert a token for your image entity.


Filter by taxonymy ID with multiple field in contextual filter In drupal 8.9 I need to filter by taxonomy ID over multiple fields in the contextual filter of views.
How to do this ?

On the views edit page:

Under Advanced: Create a relation to the field that holds the refrence to the taxonomy id ("Taxonomy term referenced from field_your_field_name_that_holds_the_reference")
Under Advanced: Create a contextual filter for the Term ID and select the previous made relation as relationship. As final step click on "more" on the same page beneith, and select allow multiple.

Now you just add multiple taxonomy id's as  1+2+3 (for OR) or 1,2,3 (for AND).
And if you want to select on multiple fields:
Repeat the process to add more fields and then you can do:
/1+2+3/877,454,453/345,345,345
Each slash represents the contextual filter field
1+2+3 is contextual filter one
877,454,453 is contextual filter two
Etc.


How to render a field above the node title using omega sub-theme I am trying to render a slideshow in a node above the page title

So far I have in my template.php

function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $vars['node'] = $theme->page['node'];
  }
}

this passes a $node variable into a custom region--content.tpl.php
I was then expecting to be able to use this snippet to render the field but it fails

print render($node['field_slideshow_images']);

You might get a bit more luck using the field_view_field function:

function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $node = $theme->page['node'];

    $vars['slideshow'] = field_view_field('node', $node, 'field_slideshow_images');
  }
}

And then use print render($slideshow); in your template file.

You might need to play with the 4th parameter to field_view_field() ($display) a bit if you have custom settings on your display for that field, but it should be a good place to start.


Write to Organic groups I need option like on Facebook groups to publish something in group, and then user comment that.

Now i have only comment form which users use to post in groups.

I need something like posting nodes, but in group.

Is this possible?

Thank you!

You can allow any content type as content in the group. So if you want to set post in group you can edit post content type and make as group content.

When you edit the post content type usign admin>structure>content types>post you will find the following options to add this content type as group option.

After doing this when you  visit post create page you will find group select box. From here you can select the group.


How to disable cache on view with ID as contextual filter I've got a view (block) wich fetches images from all nodes of content type x. I use these in a slider.

When I open node y, I only want to see the image of node y. So I add a contextual filter to filter on this node.

Here's the thing... It doesn't work. It caches the image, and always shows the cashed image. I already set the view caching to 'none' and disabled page caching.

I've got no clue how to disable the caching for this. Is this view caching? Is this block caching? Is this page caching?

Found the answer: I am using slick views for the slider.

Slick itself has cashing options. After disabling that caching, it worked like a charm.

to disable:
* edit your view
* open the format settings
* Scroll down to the cache settings
* Set it to no caching


How can I get a block to display only on node view in Drupal 6 I have a block that I need displayed only on the main page of a node.

I can get it to display on node/1/view by putting node//view in the conditions, but that only works if view is in the URL. I want it to show whether I go to node/1/view or node/1, but NOTHING else. If I try node/ it shows it for every node page, not just node/1. I also tried node/*/ but that didn't work at all as it appears the ending slash is being removed.

In that case you need to to have node/*/view and node/* on separate lines.

Unless the node that users are customizing are a specific node type, then you should use the php code to check for a certain node type, regardless of node id or url.


Why are my menu items not showing under the top level menu item? I'd like my other 3 menu items to sit under Manage Instagram in my Admin/Config menu but they are all being created as individual top level menu items.

  function instagram_menu() {

  $items = array();

  // Top Level Menu Item
  $items['admin/config/instagram'] = array(
    'title' => 'Manage Instagram',
    'type' => MENU_NORMAL_ITEM,
  );

  // Secondary Level Menu Item
  $items['admin/config/instagram/pull-images'] = array(
    'title' => 'Pull Instagram Images',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('instagram_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Secondary Level Menu Item
  $items['admin/config/instagram/client_id'] = array(
    'title' => 'Set Instagram Client ID',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('instagram_client_id_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Secondary Level Menu Item
  $items['admin/config/instagram/delete'] = array(
    'title' => 'Delete Instagram Data',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('instagram_delete_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

According to Drupal menu item types you need to designate which item is the parent and designate the children as such. So in your case, I believe setting your 3 links as MENU_LOCAL_ACTION should resolve the issue. You might have to designate the top level menu item as MENU_DEFAULT_LOCAL_TASK to make it work depending on your settings.


Displaying a taxonomy term (token) in a block How do I display the name of a taxonomy term page in a block?

For example, I am on the ww.example.com/taxonomy/term page and I want a title block on that page that displays TERM. Is there any PHP already written for this out there?

I tried a couple of suggestions made here using contextual filters but they do not work, either the block doesn't show or the term displayed is not the one in the URL (The taxonomy has children.)

Thanks. :)

I will answer my own question here:

Create a block view (taxonomy term)
Add relationship: "Taxonomy term: Content using your vocabulary)
Add contextual filter "Taxonomy term: Term ID" (no depth)

Configure the filter to "Provide Default Value: Taxonomy term ID from URL"
   below,

Check "Override title" and type "%1" in the input box

Specify validation criteria: "Taxonomy Term"

check box that has your vocabulary,

Select the Filter value type: Term ID

That's it. No need to add fields or filters. You can remove all sorting criteria.

This works even if you have several levels of children. All it does is take the term of the vocabulary that is in your URL and displays it as the page title. Also works if the page or view, or whatever is there, is empty or returns no results.

Hope that helps. :)


How to limit number of files uploaded with plupload integrtion module? I'm using Plupload integration module. In my Form API form I want to use it as simple replacement for file element. However, both file and managed_file types accept one file. plupload accepts any number of files. How to limit it to only defined number of files? Or simply one?

Setting cardinality as FileField Sources Plupload does:

'#plupload_settings' => array(
  'cardinality' => 1,

does not work, and I wasn't able to find any other parameter for this.

The way I limited it to single file, was to create js file and attach it to the form. In that file, I bound a function to QueueChanged, to remove excess files and hide "Add file" button:

(function($) {

Drupal.plupload = Drupal.plupload || {};

/**
 * Attaches the Plupload behavior to each Plupload form element.
 */
Drupal.behaviors.download_plupload = {
  attach: function (context, settings) {
    $(".plupload-element", context).once('download-plupload-init', function () {
      var add_button = $(this).find('.plupload_button.plupload_add');
      var uploader = $(this).pluploadQueue();
      uploader.bind('QueueChanged', function() {
        var local_uploader_element = this;
        // Remove files exceeding the cardinality setting.
        if (local_uploader_element.files.length >= 1) {
          var i = 0;
          for (i=0;i<local_uploader_element.files.length;i++) {
            if (i >= 1) {
              $(this).removeFile(uploader.files[i]);
            }
          }
          add_button.hide();
        }
        else {
          add_button.show();
        }
      });
    });
  }
};

})(jQuery);

This is a simplified version of js found in FileField Sources Plupload, trimmed, without Field API specific parts, and made to work on all plupload elements.


Embed a node form with default values in drupal 7 How do I embed a node form and set some default values in that form in Drupal 7?

I understand that I can use this:

 $form = node_add('product_plan');
 print drupal_render($form);

That prints the form on to the page just fine, but I need help understanding how I can add default values. In Drupal 6, I would normally do this:

 function module_nodetype_form_embed( $property )
 {
     global $user;

    $node = new stdClass();
    $node->type = 'node_type';
    $node->uid = $user->uid;

    // Hidden through form alter
    $node->field_node_reference[0]['nid'] = $property->nid;
    node_object_prepare( $node );

    return drupal_get_form( 'node_type_node_form', $node );

 }

So how can I get the same functionality in Drupal 7

If you are using a 'select list' widget for the node reference you can do this:

$form = node_add('product_plan');
$form['FIELD_NAME'][$form['language']['#value']]['#value'] = 'NID';
return drupal_render($form);

'autocomplete' widget would look like:

$form = node_add('product_plan');
$element['#default_value'] = 'NID';
$form['FIELD_NAME'][$form['language']['#value']][0]['nid']['#value'] = node_reference_autocomplete_value($element, FALSE, '');
return drupal_render($form);


User resetting password, week later needing to reset it again I have a develop and a production version of a site running behind a firewall. In production the users passwords are somehow being reverted and once the user resets it, they get a random amount of time and are required to reset it again. I cannot track this down. Looking for any suggestions on what is going on. I have looked in the logs, but don't see any flags.

Setup consists of 3 servers. One for Drupal App, One for MySql DB, One for Solr.

Here are some suggestions/things to check based on your description:

If the user passwords on production are reverting after a recent deployment, check to make sure that your settings.php file on production doesn't point to the development instance's database (you may be inadvertently repointed production to a backup copy/development copy of the database by pushing changes in settings.php).
Check to see if your site is utilizing a password management module.  If so, doublecheck/resave expiration settings (as well as if any security/recommended updates are available). Common password management/expiration modules include:

Password Policy
Force Password Change

Check to see if there are any custom rules (either using Rules module or programmatically implemented with a custom module) in place that force a user to reset password after a set duration/period of time/number of logins.
Check to see if the site's user accounts are tied to an external user account provisioning/login system such as LDAP or a Single Sign On service (as well as if any security/recommended updates are available). If one of these are in place, then you may need to check password expiration policies at the account provider. Examples SSO service modules for Drupal include:

Janrain - integration with the commercial Janrain service
Google Apps Authentication
SimpleSAMLphp Auth - integration with the open source library SimpleSAMLphp
HybridAuth Social Login - integration with the HybridAuth library
Bakery - SSO among Drupal installations on the same parent domain
Account Sync - provides SSO functionality and account info synchronization among Drupal installations.


Let users review draft copies before publish Is there a way to set permissions to allow users to preview an unpublished node before our a content editor publishes it? Our working group is rather small so Workbench may exceed what we need.

Would setting up a group, giving them permission to view a Content Type but not edit (and therefore publish or un-publish) be an acceptable solution? Would there be any unforeseen drawbacks? Could anyone lend their experience to such an option?

You could accomplish this with a combination of user roles (writer, peer reviewer, editor, for example) and Field Permissions plus maybe a couple of views for users of each role. More details about Field Permissions (from project page):

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
Features:

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned based on what access the user has.
Author-level permissions allow viewing and editing of fields based on who the entity owner is.
Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
Field permissions overview

I would add a select list field to your content type that is editable only by peer reviewers and editors. You might call it publishing status or workflow status with the options of "needs major revision, needs minor revision, ready to publish" (just to give a couple examples). Use the field permissions module to make this field visible to the node author, invisible to anonymous users and authenticated users, and editable by peer reviewers, content editors, and site admins.
You could make it fancier by also using rules so that if someone with a given role (e.g. editor) selects ready to publish, the node is automatically published, and/or promoted to the front page, etc.
Hope this helps.


Taxonomy term reference field from custom database table I am trying to create a taxonomy term reference field or the equivalent in a View that uses the uuid of a field in a custom table. This field can contain multiple uuids.

My first approach after having issues with the views_handler_field_taxonomy ( because the table does not contain the vid and tid fields ) was using joins and another table that contained all the necessary taxonomy fields. Although I got it to work the multiple joins caused the results to become pretty ugly ( lots of duplicates ). I may have to use this approach and clean up the results with custom code but I would definitely prefer not to.

So the question. Is there any straightforward way I'm missing to get my custom database field of comma separated uuids treated like a taxonomy term reference field by Views? I have tried a variety of different relationship handlers as well as field handlers in my hook_views_data but no luck. I have found very limited documentation and only the simplest tutorials for custom views field and relationship handlers. Any links to good ones and/or good sample code would be greatly appreciated.

I would also be completely fine with a way to treat a custom entity property as a taxonomy term reference field.

The easiest solution would be to use some sort of system to synchronize those terms from whatever data set you have to real taxonomy terms.

It would probably function similarly to Node Auto Term.


How to set different default images in an image field per domain? I'm working on a set of similar websites (promoting products of different regions) separated by Domain Access module. I'd like to set different default image in an image field in each site. Is it possible?

Point the image to a .php file instead of a .jpg file, and then write a script to

Find the domain name (https://stackoverflow.com/a/17201254/836995)
Output the appropriate image (https://stackoverflow.com/a/1353867/836995)

Something like this should work (untested):

<?php

$img_file = NULL;

switch ($_SERVER['SERVER_NAME']) {
  case "www.a.com":
    $img_file = "filename_a.jpg";
    break;
  case "www.b.com":
    $img_file = "filename_b.jpg";
    break;
  default:
    break;
}

if (!empty($img_file)) {
  header("Content-type: image/jpeg");
  readfile($img_file);
}

This is a bare minimum script. A more elaborate version here: https://stackoverflow.com/a/9453207/836995 (although you don't need the .htaccess part to do this for only one image).


How to add classes to h2 block title tags in sidebar region I need to add a class to the h2 block titles in a sidebar.  How can I do this in pre-process?  I haven't been able to find an example that shows how to isolate certain blocks.  I'm using Omega.

template_preprocess_block()

Inspect the block object in this preprocess function. You could use either the 'module' and 'delta' properties to target a specific block or the 'region' property to target all blocks in a certain region.

H2 css-classes are listed in the title_attributes_array. The code below shows how to add a new class. This example is based on a block generated by Views:

function MYTHEME_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->module == 'views' && $block->delta == 'name_of_my_view-block') {
    $variables['title_attributes_array']['class'][] = 'my-new-class';
  }
}

Sidenote: dpm() by the Devel module is a handy tool for printing out the available data in variables:

function MYTHEME_preprocess_block(&$variables) {
  dpm($variables);
}


I'm trying to set a $page variable but it's not working. i'm studying, trying hard to understand what is show in the kpr($page) output. So as an exercise, I'm trying to change #show_messages element. by default, i get this

....(Array, 10 elements)
◦ #show_messages (Boolean) TRUE

so in the theme_hook_alter() function i did this (before the kpr() output).

$page['show_messages'] = FALSE;

but when i refresh it's not changing the output. why is that.

also, i don't really understand the difference between elements with a # before them and the ones without.

<?php

/**
 * Implements hook_preprocess_HOOK()
 *
 */
function YOURTHEME_preprocess_page(&$vars) {

    // All you need to do is to set the appropriate preprocess variable:
    $vars['show_messages'] = false;

    /**
    We also have $vars['page'] which is an array.

    $page = $vars['page'];
    This array is a Drupal Render Array which means would pass through drupal_render() function.
    In a Render Array keys starting with # are attributes and the others are children elements.
    Read more about that on @see https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_render/7

    */
}


Validate form with preprocess_user_form I'm newbie on Drupal and I try to set an validation and submit the custom user registry form but I try and validation not call.

function mymodule_theme(&$existing, $type, $theme, $path){

  $hooks = array();
   // Make user-register.tpl.php available
  $hooks['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mymodule') . '/templates',
    'template' => 'user-register',
    'preprocess functions' => array('mymodule_preprocess_user_register_form'),
  );
  return $hooks;

}

function mymodule_preprocess_user_register_form(&$vars) {

  $vars['title'] = 'Registro de candidatas';
  $vars['message_welcome'] = '
Ingresar tu correo electrónico para iniciar este proceso. Asegúrate de tener abierto dicho correo para recibir las notificaciones y realizar de manera inmediata las indicaciones que recibas.
';

  //Shortens the form variable name for easier access
  $form = $vars['form'];

  $form['account']['mail']['#attributes'] = array(
    'placeholder' => 'Escribe tu correo electrónico',
    'class' => array(
      'mymodule-form-email-input'
    )
  );
  $form['account']['mail']['#title_display'] = 'invisible';
  $form['account']['mail']['#description'] = '';

  $form['account']['pass']['pass1']['#title_display'] = 'invisible';
  $form['account']['pass']['pass1']['#attributes'] = array(
    'placeholder' => 'Escribe una contraseña',
    'class' => array(
      'mymodule-form-email-input'
    )
  );

  $form['account']['pass']['pass2']['#title_display'] = 'invisible';
  $form['account']['pass']['pass2']['#attributes'] = array(
    'placeholder' => 'Vuelve a escribir contraseña',
    'class' => array(
      'mymodule-form-email-input'
    )
  );

  $vars['mail'] = render($form['account']['mail']);
  $vars['pass'] = render($form['account']['pass']);
  $vars['captcha'] = render($form['captcha']);

}

function mymodule_user_register_form_alter(&$form, &$form_state, $form_id) {

  $form['account']['mail']['#field_prefix'] = '';
  $form['#validate'][] = 'mymodule_user_register_form_validate';

}

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

  drupal_set_message(t('AN ERROR OCURED'));

  if ($form_state['values']['mail'] !== '') {
    form_set_error('mail', t('Escribe un correo electrónico'));
  } else {
    if(valid_email_address($form_state['values']['mail'])) {
      form_set_error('mail', t('Email invalido'));
    }
  }

  if ($form_state['values']['pass']['pass1'] !== '') {
    form_set_error('mail', t('Escribe una contraseña'));
  }

  if ($form_state['values']['pass']['pass2'] !== '') {
    form_set_error('mail', t('Confirma tu contraseña'));
  }

  if ($form_state['values']['pass']['pass1'] !== $form_state['values']['pass']['pass2']) {
    form_set_error('mail', t('La contraseñas no coinciden'));
  }

  if (!$form_state['values']['sendgift']) {
    form_set_error(NULL, '', TRUE);
    drupal_get_messages();
  }

}

Something I have wrong? I look on documentation and I found few details on registration. I read about hook_form_alter() and hook_preprocess_form() but it's confusing to me.

Thanks

The most obvious issue with your code is that you are trying to override the entire form structure within a theme preprocess hook. This does not work. Such hooks will be able to alter the output of forms or any other templates by providing additional variables, altering existing (theming) variables, or adding theme wrappers. They will not be able to alter the processing logic of a form.

Instead, you should manipulate your entire form within hook_form_FORM_ID_alter().

The second issue is, that your implementation of hook_form_FORM_ID_alter() is missing the _form_ part between mymodule and the form ID.

Also, consider using the t() function with English texts for all labels and add your desired translations to Drupal I stead of using hard-coded strings.


Does drush need to be installed as root? Per http://docs.drush.org/en/master/install/

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

So I try it but get the following error:

[Michael@devserver ~]$ php -r "readfile('http://files.drush.org/drush.phar');" > drush
[Michael@devserver ~]$ php drush core-status
PHP Warning:  pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///home/Michael/drush/includes/startup.inc on line 359

Warning: pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///home/Michael/drush/includes/startup.inc on line 359
Error has occurred executing the Drush script found at /home/Michael/drush
(errno 13) Permission denied
[Michael@devserver ~]

So then I try running it as root.

[Michael@devserver ~]$ su -
Password:
[root@devserver ~]# php /home/Michael/drush core-status
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/Michael/drush
 Drush version          :  8.1.2
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

[root@devserver ~]#

So, all is good, and I just need to install it as root?  Any way I can install it as a normal user?  Thanks

NOTE The issue described in the Question has now be fixed in the latest Drush version.

No, Drush does not need to be installed as root.

I've submitted Drush pull #2246 to update the current Drush install instructions.

This install method fixes the issue as per Drush pull #2246:

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > /tmp/drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > /tmp/drush

# Test your install.
php /tmp/drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x /tmp/drush
sudo mv /tmp/drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init


Listing all entries of a specific content type within a panel I've been tasked with adding a page to an existing Drupal (version 7.15) site.  I know next to nothing about Drupal or PHP so I've been struggling a bit.

I've created a page with 2 panels and am trying to use the "custom content" option to display the title field for each entry of a specific content type in one panel. And in the other panel, I would like to display all the fields for each entry.

For instance, the first panel thus far contains:

Open Positions:

And I'd like to know what PHP code I'd need to use to make each
 tag contain the titles for my content type.  The other panel would be somewhat similarly formatted in that there would be markup enclosing each field, but I do not know how to get the entries from the database, and then display specific fields from that entry.

Thanks.

If you can at all avoid it, the direction you've started in is not the solution you want. Panels is not for handling content, but context.

What you want instead is a Views content pane. Explaining Views in detail is beyond the scope of this post, but here's the general outline.

Install Views and Ctools.
Enable "Views UI" and "Views content panes".
Create a new View
Add a filter on node type so you get only the right content type.
Add title as field. Then repeat the View creation above but add the rest of the fields.
Go into Panels and add both Views in their respective regions.

Much much more info about Views in Taming the Beast: Learn Views with NodeOne.


Displaying associative array data in twig Using drupal 8.7.x

I have an associative array that is returned to twig. However I can't seem to get the data displayed.

Associative array:

array_push($mealsArray, ["meal" =>
  [
    ['strMeal' => $mealTitle],
    ['strMealThumb' => $mealImage],
    ['mealUrl' => $mealTitleUrl]
  ]
]);

Return to twig:

return [
  '#theme' => 'recipe_search_block',
  '#meals' => $meals,
  '#ingredientList' => $ingredients,
  'form' => $form,
];

In twig I'm trying to display them like this:

    {% for meal in meals %}
      {% for fields in meal %}

{{ fields["strMeal"] }}

      {% endfor %}
    {% endfor %}

When I debug with kint this is the output I get

Any help would be appreciated, thanks in advance!

Sollution:

Associative array:

array_push($mealsArray, ["meal" =>
  [
    'strMeal' => $mealTitle,
    'strMealThumb' => $mealImage,
    'mealUrl' => $mealTitleUrl
  ]
]);

Twig:

{% for meal in meals %}
      {% for fields in meal %}

{{ fields.strMeal }}

        {% endfor %}
    {% endfor %}

The return statement remains unchanged.


Panels Page Title CSS? I have created a Panels Page but can't find out how and where to put the class for the title?
Right now it uses the core Page Title CSS but I wan't every Panels Page Title to be unique.

Edit: I've noticed that this is the way for all my panels. I can't seem to be able to set a CSS Class to Pane Titles at all.

If you have set panel title like this

you can use the class "pane-title" to write the css.


wysiwyg + ckeditor - failed to open stream sites/default/files/js/wysiwyg/wysiwyg_ckeditor_XXX.js I am using WYSiWYG with CK editor. I am getting this error whenever i am trying to access a form with ckeditor.

  file_get_contents(MYSITE/sites/default/files/js/wysiwyg/wysiwyg_ckeditor_lMF9rzHK588_LcHaW11FHc_RkSCpdKrS7MgWsyqXXEM.js)

  [function.file-get-contents]: failed to open stream: HTTP request
  failed!

  HTTP/1.1 404 Not Found in drupal_build_js_cache() (line 4846 of
  /var/www/html/dev3/wifh/includes/common.inc).

This file "wysiwyg_ckeditor_lMF9rzHK588_LcHaW11FHc_RkSCpdKrS7MgWsyqXXEM.js" exist with content

window.CKEDITOR_BASEPATH = '/MYSITE/sites/all/libraries/ckeditor/';

This bug should be fixed in the latest dev snapshot of wysiwyg:

See also http://drupal.org/node/1802394 (which essentially provides a patch for the previous response above).


drupal course module adding payment object Please Somebody help me. I have spent almost a week working on this functionality but haven't got any success yet.
I have a Learning management system in drupal7 using the course 7.1 beta2 module, the LMS has courses in it. The requirement is to have the user buy the courses in-order to take the course but I am not able to configure it. Please can any body show me a way on how to configure the payment object so that the user will have to buy before even starting the course. I need a step-wise solution on this

Thanks in advance

Here is the solution on the Course issue queue:

https://drupal.org/comment/7477856#comment-7477856


How to alter command being run by drush_invoke? When you run drush features-revert-all command, it can be altered using hook_drush_command_alter (&$command).

However during run it's invoking another command by:

drush_invoke('features-revert', $features_to_revert);

It seems I can still use drush_hook_pre_COMMAND and drush_hook_post_COMMAND to perform some additional checks.

However I'd like to alter the list of arguments (features) being passed into features-revert which are not available as part of the main command.

Is there any Drush hook which I can use to achieve that?

Drush calls command hooks via the function _drush_invoke_hooks, which unfortunately does not provide any facility to alter the arguments list from a pre or validate hook.  We are looking to provide a more flexible mechanism that would allow this in Drush 9. Currently, only the command alter hook can change the parameters to a command. Ideally, Drush commands should invoke other Drush commands via drush_invoke_process; this will also go through the command alter hook.  If a command uses drush_invoke, though, you are stuck, as drush_invoke bypasses the alter hook.


Creating mobile-applications (like Android applications) with Drupal? First, sorry if the question seems a bit basic to veteran programmers here - I'm just a newbie student for JS programming and not that of a big user of smartphone applications in general, at least not yet :) . I'm also not experienced in PHP programming (have yet to actually try that) and just in my first steps to getting to know this whole world now.

I want to know if it's possible, or at least practical to create smartphone (and maybe even web) applications with Drupal, at least with Drupal 8. Please give the most basic and general detailing you can.

Thanks,

I would recommend to take a look at DrupalGap

Also especially regarding Drupal 8 I would recommend reading this article:


List of user names and emails I have a role called "Secretary" and I would like for the role to be able to access a "view" with a list of usernames and emails. What's the easiest way to do this?

I know how to let only the secretary have access to the page, and I have the views module installed. But I'm not that good with it yet. Any ideas?

Simple - on your view, select "Page Settings" -> "Access: Permission" then chose "Role" and select your "Secretary" role.


What is the order of execution and redering of hooks and page components? In order to have a better understanding of what Drupal does, I need to find out what the order of execution of hooks and page components is.

A page layout in Drupal consists of HTML, regions, nodes, blocks, Views and ... . Every one of these components have lots of preprocess or process functions,  like hook_preprocess_node. There are also template functions, theme functions and ... that are run to build the page array.

To avoid my question to be too broad, let's only talk about the hook and preprocess functions not the core functions.

Thanks.

Consider looking at the X-ray module also. From its project page:

X-ray module gives a look at the skeletal structure of a site to help developers and site builders see how things work.
Features:

A technical summary is added to the help above the main administrative sections. For example, blocks, content types, and menus are summarized on Structure; themes on Appearance; etc.
A table of permission titles matched to their permission machine names.
A table of most* hooks which Drupal invokes (and when they are invoked) and that are available to be implemented.
The function and arguments producing each page you visit, displayed on that page.
The form ID of every form you see, displayed on the form.


How to print a Panel Page? I am using the Print module.

I have enabled the node/%node template in panels and used a selection rule to select my specific node type and added fields into the panels regions etc. That all works fine.

I need to be able to use the Print module to see a print-friendly version of this node. However when I go to /print/[nid] I just get a completely blank page.

So is it possible to have a printer friendly version of a panels page? i.e in a template file or another method?

Checkout the piece of code here. Just copying it here for reference

Create a function as follows in template.php

function get_panel_view(&$node) {
    // Load my task plugin
    $task = page_manager_get_task('node_view');

    // Load the node into a context.
    ctools_include('context');
    ctools_include('context-task-handler');
    $contexts = ctools_context_handler_get_task_contexts($task, '', array($node));

    $output = ctools_context_handler_render($task, '', $contexts, array($node->nid));
    if ($output !== FALSE) {
        return drupal_render($output['content']);
    }
    // Otherwise, fall back.
    return drupal_render(node_view(node_load($node->nid)));
}

Template should be called print--node--.tpl.php and you can print it as

print get_panel_view($print['node']); in place of print $print['content'];

Rebuild theme cache


How can I update webform_submission uid in the table, after which the anonymous user has registered? I'm a graphic design, and I just started using Drupal 7.

I have a form created with webform, which collects data entered by the user, after sending, the user is directed to the purchase page. The stages of the purchase is successful if both the user and logged in, whether the user is anonymous.

Here's my problem, from the control panel of Drupal 7 when I go to see the results of the webform, if the form has been sent by the user logged in, see the user's name, is so I know who did it then submitting the form. While it has been the anonymous user, in the results I see anonymous user even after the user has registered and recognized.

For clarity I describe what it does with this form, these are the steps that the user to fill out the form webform:

1) Fill out the form webform (in this form there two fields of the form "webform commerce")
2) after sending the form you will be directed during the cart / checkout, at this stage the user enters the email for the registration, if it is anonymous.
Everything works perfectly.

I noticed that the field in the table webform_submission uid inside the database remains at 0 even after the user has registered.

Browsing around the net in the blog / forum / drupal.org
I left this tutorials: example tutorial
so I'm starting to use hook_webform_submission_presave in a custom form.
So how do I fill the uid after the form has been sent?

This is the code:

            <?php
/**
 * @file
 * Questo modulo server per collegare utente anonimo con il webform inviato.
 */
// hook per ottenere l'ID dell'utente che ha inviato il modulo webform
function mio_modulo_webform_submission_presave($node, &$submission) {
  // Ottengo l'id dell'utente.
  //$user = user_load($submission->uid);
  global $user;

  $user->uid;

}
?>

Sorry for my english
Thanks in advance for the help

It sounds like your webform has already been submitted by the time they reach checkout. So essentially, you may need to "Update" the submission with the new user ID.

Check out webform_submission_update:
http://drupalcontrib.org/api/drupal/contributions!webform!includes!webform.submissions.inc/function/webform_submission_update/7


Code to add node add form to a custom block (not working) I am trying to use code below to display node add form for a custom content type in a custom block.

Any guidance on why the code below may not be working is sincerely appreciated.

function stories_block_info(){
  $blocks['post_story'] = array(
    'info' => t('Post a Story - Neil Block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function stories_block_view($delta = ''){
  switch ($delta) {
    case 'post_story':
      $block['content'] = drupal_get_form(stories_node_form);
      // $block['content'] = block_contents($delta);
      break;
  }

  return $block;
}

For people still having trouble with the above code when using anything AJAX-related (e.g. 500 errors) or simply trying to open up the 'blocks' tab in Panels without some error (e.g. some Entity Translation functions) you might want to try the following module code instead in Drupal 7 (but some parameters may still need to be added for your purposes).

function custom_example_block_info() {

    $blocks['example_node_form'] = array(
       'info' => t('What an example'),
    );
    return $blocks;

}

function custom_example_block_view($delta = ''){

    $block = array();

    switch ($delta) {
        case 'example_node_form':
            global $user;
                        //Note: 'type' is your node content type and 'language' must be included
            $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'example', 'language' => LANGUAGE_NONE);

            $form_state['build_info']['args'] = array($node);

            form_load_include($form_state, 'inc', 'node', 'node.pages');
            $block['content'] = drupal_build_form('example_node_form', $form_state);

            break;
    }
return $block;

}

The important difference is that drupal_get_form cannot load the $form_state so we use function form_load_include(&$form_state, $type, $module, $name = NULL) to ensure the include file is loaded whenever the form is processed and function drupal_build_form($form_id, &$form_state) instead of drupal_get_form to pass $form_state. The lines above create the $form_state.


Alter The User Login Form Into Multi Steps I want to alter my default user login form into multi step. therefore I have wrote a code which I'm pasting below. but this code is not working, whenever I click on "Next" button it will return on the first step. please help me to get rid out of this problem.
Here is my code:

function signin_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    unset($form['name']);
    unset($form['pass']);
    unset($form['actions']);
    $form['mail'] = [
      '#title'       => t('Email'),
      '#description' => t('Enter your Email'),
      '#type'        => 'textfield',
      '#required'    => 'true',
      '#maxlength'   => 40,
    ];
    $form['next'] = [
      '#name'   => 'next',
      '#value'  => t('Next'),
      '#type'   => 'submit',
      '#submit' => ['signin_step1_form_submit'],
    ];
    $form['#validate'] = ['signin_step1_form_validate'];
  }
}

function signin_step1_form_validate($form, &$form_state) {
  $mail = $form_state['values']['mail'];
  if (empty(user_load_by_mail($mail))) {
    drupal_set_message(t('The entered email is not associated with any account.'));
  }
}

function signin_step1_form_submit($form, $form_state) {
  $form_state['stored_values']['mail'] = $form_state['values']['mail'];
  return signin_step2_form($form, $form_state);
}

function signin_step2_form($form, &$form_state) {
  $form['pass'] = [
    '#title'       => t('Password'),
    '#description' => t('Enter the password'),
    '#type'        => 'password',
    #required' => 'true',
  ];
  $form['signin'] = [
    '#name'   => 'signin',
    '#value'  => t('SignIn'),
    '#type'   => 'submit',
    '#submit' => ['signin_step2_form_submit'],
  ];
  $form['#validate'] = ['signin_step2_form_validate'];
}

function signin_step2_form_validate($form, &$form_state) {
  $mail = $form_state['stored_values']['mail'];
  $user_obj = user_load_by_mail($mail);
  $name = $user_obj->name;
  $pass = $form_state['values']['pass'];
  if (!user_authenticate($name, $pass)) {
    drupal_set_message('error', t('The Password you entered is incorrect'));
  }
}

function signin_step2_form_submit($form, &$form_state) {
  $mail = $form_state['stored_values']['mail'];
  $user_obj = user_load_by_mail($mail);
  $form_state['uid'] = $user_obj->uid;
  user_login_submit($form, $form_state);
}

Finally I got it to worked. here is my code, I'm pasting this here to saves someone time.

function signin_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    unset($form['name']);
    unset($form['pass']);
    unset($form['actions']);
    if (isset($form_state['step2'])) {
      $form = signin_step2_form($form, $form_state);
      return $form;
    }
    $form['mail'] = [
      '#title'       => t('Email'),
      '#description' => t('Enter your Email'),
      '#type'        => 'textfield',
      '#required'    => 'true',
      '#maxlength'   => 40,
    ];
    $form['next'] = [
      '#name'   => 'next',
      '#value'  => t('Next'),
      '#type'   => 'submit',
      '#submit' => ['signin_form_submit'],
    ];
    $form['#validate'] = ['signin_step1_form_validate'];
    return $form;
  }
}

function signin_step1_form_validate($form, &$form_state) {
  $mail = $form_state['values']['mail'];
  if (empty(user_load_by_mail($mail))) {
    form_set_error('mail', t('The entered email is not associated with any account.'));
  }
}

function signin_step2_form($form, $form_state) {
  $form['pass'] = [
    '#title'       => t('Password'),
    '#description' => t('Enter the password'),
    '#type'        => 'password',
    #required' => 'true',
  ];
  $form['signin'] = [
    '#name'   => 'signin',
    '#value'  => t('SignIn'),
    '#type'   => 'submit',
    '#submit' => ['signin_form_submit'],
  ];
  $form['#validate'] = ['signin_step2_form_validate'];
  return $form;
}

function signin_step2_form_validate($form, &$form_state) {
  $mail = $form_state['stored_values']['mail'];
  $user_obj = user_load_by_mail($mail);
  $name = $user_obj->name;
  $pass = $form_state['values']['pass'];
  if (!user_authenticate($name, $pass)) {
    form_set_error('pass', t('The Password you entered is incorrect'));
  }
}

function signin_form_submit($form, &$form_state) {
  if ($form_state['clicked_button']['#name'] == 'next') {
    $form_state['step2'] = TRUE;
    $form_state['stored_values']['mail'] = $form_state['values']['mail'];
    $form_state["rebuild"] = TRUE;
  }
  else {
    $mail = $form_state['stored_values']['mail'];
    $user_obj = user_load_by_mail($mail);
    $form_state['uid'] = $user_obj->uid;
    user_login_submit($form, $form_state);
  }
}


How can I get an absolute path to a theme? Is there a Drupal function that returns the absolute theme path? Or is there a canonical / base practice way of doing this correctly returning the theme path?

What I've found so far is this:

<?php
// @file template.php
$template_path = DRUPAL_ROOT . drupal_get_path('theme', 'foo');

I'm looking to require_once the template path in a template.php file like so:

<?php
$template_path = DRUPAL_ROOT . drupal_get_path('theme', 'coo');
// ...
// Check file exists etc
require_once $template_path;

The base_path() function would return the base bath of the Drupal installation

  Returns the base URL path of the Drupal installation. At the very
  least, this will always default to /.

and path_to_theme() will return the path to the current theme.

  Return the path to the current themed element.

  It can point to the active theme or the module handling a themed
  implementation. For example, when invoked within the scope of a
  theming call it will depend on where the theming function is handled.
  If implemented from a module, it will point to the module. If
  implemented from the active theme, it will point to the active theme.
  When called outside the scope of a theming call, it will always point
  to the active theme.


Prevent clubbing of server side error messages on top I have inline form errors module enabled on my drupal 8 site. The server-side errors that appear on form submission are appearing as clubbed together like below:

How to change this error language and prevent clubbing for example if there would have been multiple errors the message would have been "2 errors have been found: FieldName1, FieldName2".

Is it a part of core and how to show errors in different lines?

You can disable that module to return to the more traditional line-by-line error output globally, or hook into it programatically form-by-form:

function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'foo_form') {
    $form['#disable_inline_form_errors'] = TRUE;
  }
}


Will the Search API increase performance of searches in the Views Exposed filter? How to increase the performance, if one of the main activities on a website would be searching in Views exposed filters? Will the Search API module (with Database Search/not Solr) significantly increase the performance of such searches?

It probably will, depending on the Search API backend you are using. Something generally true is if you are using any other backend than database, the querying for the search will be dispatched to this additional backend instead of the database, which is Drupal primary storage, and will avoid your database a lot of suffering.

It will also makes things easier to scale, since a lot of search engines can be replicated more easily than database. Even without this statement, you can at least put the SQL server and the search engine on different servers, which means they will eventually be faster since they won't have to share one box resources.

It doesn't mean it will be faster in all cases, it depends on your environment and configuration.

Regarding the queries themselves, if you are doing a lot of fulltext searches, using a backend such as Apache SolR (or any other search engine, Xapian, etc...) it will surely be a lot faster since they have been made for this. If you are doing facet oriented search, it will also help a lot.

But, in the end, if your views filter only are on exact strings, integers and such, it may not be faster in the end, it will just be more scalable.

You have to remember that creating an index for your data will also imply that you install a whole lot of modules in your Drupal site, you'll have to benchmark a bit. But if the primary business matter of your site is searching, I'd say give it a try.

I don't know if my answer sounds good.


CDN module - serving files from subdomain - setup Can plaease somebody point me to correct setup if I want my files to be served from subdomain?

As I understood I should choose origin pull mode.
Then create a subdomain.
Copy all files inside same structure to new subdomain.
In config details of CDN module add new subdomain

Should I add some rules inside htaccess of new subdomain?
Thank you very much for help.

If you are using the Amazon Cloudfront - You are using origin pull cdn in which case you can:

Create an custom origin in there service
http://aws.typepad.com/aws/2010/11/amazon-cloudfront-support-for-custom-origins.html
Point that url that you get from cloudfront to a cname in your dns info in you admin panel in hosting setup
Install the cdn module enable it select origin pull and add the mapping the for files

Then save and you should be good to go

If you wanted to make an attempt at file conveyor that can be found here

http://fileconveyor.org/


Using Entity reference + Views to create members select list How can  I use VIEWS + ENTITY REFERENCE to get list of active members specific to the CURRENT GROUP [created via organic groups].

I have created a view that list active members belonging to the group.

I have seen Restricting selectable entities with Views

But my question is, that is it possible with entity reference too ?

If yes how can I achieve this case ?

The view will need to know which group, which means a Context Filter.  So options there are usually the current url or the current signed in user.  Depending on where your entity reference is, and how you are getting to it, there might be a context available to fill your filter.  Then the view will be usable to limit the options in your reference field.  The more details you can provide about the use case, the better I can make this answer.


Best way to integrate "customization" to the front page #First question

We are making a Drupal 7 theme for one of our customers.
The company wants to be able to edit the frontpage easily, without any coding skills.

Atm we got this:

Image 1

Image 2

But this is totally not user friendly.
We made a block, and put block content in it, for this one it was just html.
But what we want is more like a wordpress "customizer" or something?

Maybe this is something that is totally basic in Drupal 7 but we just missed it?

#Second Question

The people (Employes of our client) that will manage the website when launched. Will they have to work in de basic Drupal 7 dashboard, or is there a way to make your own dashboard in the style of your website?

As a possible starting point, you might use the Panels and Panelizer modules.

When you define a custom CTools page (using the Page Manager module included with the CTools module), you can define its layout and content.

Concerning your second question, it is also possible to edit the page without moving to the administrative interface, by using the IPE (In Place Editor) provided by Panels.

You should be able to find many tutorials about Panels, in drupal.org too: https://www.drupal.org/node/1857644


drupal image field the image doesn't show? My drupal site has a content type called Published which has a image field.When I migrate the site from Win2003 server to  CentOS , all the Published node's image field doesn't show. It appears like this:

when I click the image name it shows in a now tab.

I had do some google,but no result . someone said the directory sitename/default/files should be set 777

but it is 777.

Any suggestions Thanks in advance.

Download raw drupal form drupal.org  website, then copy .htaccess file from it to your root directory.


Constraint doesn't attach from BundleFieldDefinition, but does from entity_bundle_field_info_alter() I'm adding a trait to Commerce Product Variations, which applies the following

  public function buildFieldDefinitions() {
    // Builds the field definitions.
    $fields = [];
    $fields['plan_code'] = BundleFieldDefinition::create('string')
      ->setLabel(t('Recurly Plan Code'))
      ->setDescription(t('The Plan Code of the related Recurly plan.'))
      ->setCardinality(1)
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE)
      ->addConstraint('RecurlyPlanCodeExists', []);
    return $fields;
  }

The plan_code field appears on product variations as expected when the trait is enabled, but the field is not validated against RecurlyPlanCodeExists when the entity is saved. However, if I add the constraint via hook, as in the following, the constraint is attached and validation runs as expected.

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function commerce_recurly_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
    if ($bundle === 'recurly_plan_variation') {
      if (isset($fields['plan_code'])) {
        $fields['plan_code']->addConstraint('RecurlyPlanCodeExists', []);
      }
    }
}

Inspecting $fields['plan_code'] in the above hook confirms no constraints exist on the field prior to adding $fields['plan_code']->addConstraint('RecurlyPlanCodeExists', []);. Interestingly, $fields['plan_code']['description'] is also an empty string despite being defined in the BundleFieldDefinition. I'd assume that these are related. Any idea what the cause might be?

I've already tried deleting all existing variations and disabling/re-enabling the trait and it's had no effect.

EDIT: I just realized that the docs refer to adding constraints to BaseFieldDefinition, while I'm using BundleFieldDefinition. Maybe this is the reason?

Yes, both are different. In core the system to define bundle fields in code is broken from the beginning. Commerce did implement their own system (entity traits), but although it looks like the fields are defined in code, in reality they are not. Commerce adds them to config and doesn't transfer constraints in this process.


File to media migration: use node title for media title I have my files migrated from D7 to D8 (using d7_file source plugin to an entity:file destination).

I then migrated those files to media (using file_entity source plugin to an entity:media destination), based off this post.

However, the images in my Drupal 7 nodes of which I'm migrating never had alt text. Therefore, I would like to use the Drupal 7 node title as both (a) the Media title and (b) its image alt text.

My files to media migration looks like this (a portion of it):

source:
  plugin: file_entity
  type: image
  constants:
    bundle: 'image'
process:
  mid: fid
  bundle: 'constants/bundle'
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  # name: filename
  uid:
    plugin: default_value
    default_value: 1
  status: status
  created: timestamp
  changed: timestamp
  field_media_image/target_id: fid
  # field_media_image/alt: field_file_image_alt_text/0/value
destination:
  plugin: entity:media

The commented out lines are what I'd like to use the node title (name and field_media_image/alt), but I'm not sure how to pull in the original Drupal 7 node title. Any suggestions are appreciated.

Without knowing your content model, you can't answer this question directly, but what you'll need to do is query your node title for every fid entry for your source file entities table. You can do that in many places (e.g. source/process plugin) with your existing source plugin being a good place.

Using your custom file_entity source plugin as an example, you'll need to update the query() method so  its DB query joins the node table based on how you're content is modeled (e.g. entity/paragraph references) then selects the title column so it's included in the row data. You can follow that up with updating the fields() method so your source plugin will provide the title field you need.


Why did ~20k Drupal 7 websites just drop off the map? I was looking at Drupal statistics and surprised by how a bunch of sites just disappeared from the count. I'm assuming this is due to a change in the code, and not actually reflective of total count. But who knows!? Can anyone here offer any deeper insight?

https://drupal.org/project/usage/drupal

https://drupal.org/project/usage/1960640

If you look back through the statistics they fluctuate quite often really.

Looking at stats for May 26th 2013 (642,589 Drupal 7 sites) or June 9th 2013 (666,573 Drupal 7 sites) I'm not actually certain it can be taken to represent sites disappearing so much as people evaluating Drupal or indeed installing and uninstalling new development snapshot instances.

It's also well worth bearing in mind that the accuracy of the statistics is not 100% and sites which don't use the update manager module don't report in at all. (It is, in some circles, common practice to disable this component once a site goes live if it's being updated in a separate development environment).


URL Alias showing on checkout? Drupal 7.38
Organic Groups
Drupal Commerce
Commerce Node Checkout

I have everything setup and working well.  There's one strange bug.  On checkout, I have Title displayed so the logged in user can create a new group, but URL alias also shows up.  I don't want this.  I have pathauto handling all this automatically.  Screen shot attached.  I've dug through all display settings.  I'm lost.  Any help would be appreciated.  Screen shot below.

Thanks

It was a permission issue on the content type.


Page title block hidden on custom route, panel or view pages when content type is chosen in block visibility settings I defined a custom route in a custom module:

mymodule.overviewpage:
  path: '/mymodule-overview'
  defaults:
    _controller: '\Drupal\mymodule\Controller\PageOverviewController::content'
    _title: 'Overview'
  requirements:
    _permission: 'access content'

Here is the controller:

class PageOverviewController  extends ControllerBase {
  public function content() {
    return array(
      '#markup' => 'hello'
    );
  }

}

This route is working fine, I see the "hello" text when entering this path in my project but I do not see the page title. The page title "Overview" is used in the title tag in head of the HTML page but there is no page title block - it is not even rendered. Changing to Bartik theme I see the page title "Overview".

I know found out that the visibility of this block was set: there was a checkbox checked which defined the block to be hidden when on a node page of a special content type/ node bundle:

My question: why is the page title block not visible on panel or view generated pages or on custom routes? What should I add to avoid such a behavior? Is there a way to hide the block for special contenty types without hiding it elsewhere?

Because they are not a page of that node type. This filter doesn't just apply to node/*, it applies to all pages. And if there is no node object, the condition will always be false.

If you need something that is true on all non-node pages but for node pages only for a specific ype, you need to define your own condition plugin or use hook_block_access().


Moderating non stop comments I'm sick of moderating comments in my sites. Currently in Admin I'd see all comment titles with view/edit link on each.
What I want a table in which I can see each comment full text(which I can edit) along with delete/approval buttons so that I can moderate all of them at once in single screen.

Is there any module which can give me this view.

Yes - Views. :)

Just create yourself a comment-based view and configure it the way you want. I guess you won't be able to have an in-place editing here, but everything else should be easy achievable.


Unable to create an admin menu link I am trying to create a menu link in Drupal 8. I am following this document: https://api.drupal.org/api/drupal/core!includes!menu.inc/group/menu/8

My module name is twitter_pull and I was able to create the path fine, and it loads a form on that page, I just can't get it display a menu link. I have tried flushing the caches but that didn't do anything.
Here is my code:

Inside my twitter_pull.routing.yml

twitter_pull.settings:
  path: 'admin/config/services/twitter-settings'
  defaults:
    _form: '\Drupal\twitter_pull\Form\TwitterSettingsForm'
  requirements:
    _permission: 'administer site configuration'

Inside my twitter_pull.links.menu.yml

twitter_pull.settings:
  title: 'Twitter settings'
  description: 'Twitter settings for your site'
  parent: system.admin_config_services
  route_name: twitter_pull.settings
  weight: 100
  #Use menu_name when you want to add your link to a non-system menu.
  #menu_name: devel

It looks like you are using an older version of Drupal core. Upgrade to one of the betas or the latest 8.0.x from Git and it should work fine.

In the latest versions the filenames have been changed, as reported in YAML files for menu links, contextual links, local tasks, and local actions have been renamed. 8.0.0-alpha14 is the first tagged release with the filename change.


How to display search block in a modal dialog What I would like to accomplish is to display the search block in a modal dialog when the user clicks on a search button that I have created. I have created a search button block (basically an image with a link) and now I would like to point to the search block and have it appear in a modal dialog. I just don't know to go from here, or if it is even possible to go this route. Can someone provide some pointers on what I need to do?

You can use Lightbox or Colorbox (there are modules for both).

Each has the ability to display inline content in a modal.

All you would need to do is add your search block to the page and hide it with CSS, then adjust your search button link to trigger the lightbox/colorbox.

If using colorbox, you would do something like the following:

  Load content in a Colorbox

  Check the "Enable Colorbox load" option in Colorbox settings.

  This enables custom links that can open content in a Colorbox. Add the
  class "colorbox-load" to the link and build the url like this
  "[path]?width=500&height=500&iframe=true" or
  "[path]?width=500&height=500" if you don't want an iframe.

  If you want to pass the width and height of the Colorbox as a
  percentage (useful for responsive designs), you can format the link
  like this "[path]?width=90%25&height=90%25&iframe=true" or
  "[path]?width=90%25&height=90%25", where the "%25" is the HTML entity
  for "%".

  Other modules may activate this for easy Colorbox integration.


View a log of administration configuration changes for Drupal 7? I'm working on a Drupal 7 site and we have multiple developers and administrators accessing the site. Many times when the site breaks I can't see what was changed previously and by whom. Is there a log tracker where I can see what things were changed on the site? I know I can goto admin/content to see what content has been updated, but this isn't the case for configuration changes.

There's nothing in core, no.

One option from contrib is to use the Journal module

  Journal module adds additional fields to all forms in a Drupal site to allow developers and site administrators to record and track all changes that have been performed to setup a site or alter its configuration.

It's not automatic (that would be too complicated, forms can obviously do just about anything and it's not obvious enough from context what every action is to be able to label it automagically), so you need to trust that your editors will fill it out correctly.

But you can make it required/able to be bypassed based on user roles, so it's a good solution to the problem.