Search bar in main menu I would like to place the search bar in the main menu on the right. I have seen several people on the net asking for this but never encountered some information I could actually use.
I use Drupal 7 and the "Responsive Blog" by Devsaran.

As far as I understand the way to go is inserting some php into the main menu code in the main-menu part in page.tpl. This is what it looks like but I am struggeling with the exact to dos now...

<nav id="navigation" role="navigation">
  <div id="main-menu">
    <?php
      if (module_exists('i18n_menu')) {
        $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
      } else {
        $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
      }
      print drupal_render($main_menu_tree);
    ?>
  </div>
</nav>

Here is one approach:

Start by adding a new region to the theme's .info file:

regions[navigation] = Navigation
Next, render the region. Put the code below in page.tpl.php either just before or just after the </div> in your code above. You may need to experiment a little.

<?php print render($page['navigation']); ?>
Clear your cache so your site knows that the new region exists.
Next, in Admin -> Structure -> Blocks, place the Search block in the Navigation region.
Finally, style the search form so it looks the way you want.


Why is this property of the Cron service initialized in this manner? I wish someone could help me understand this code statement found on the core cRON service (\Drupal\Core\Cron), especially in the constructor method for this class.

public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountSwitcherInterface $account_switcher, LoggerInterface $logger, QueueWorkerManagerInterface $queue_manager, TimeInterface $time = NULL) {
  // Omissis
  $this->time = $time ?: \Drupal::service('datetime.time');
}

What does this line do? Why isn't $this->time = $time; instead used?

The service is already injected using arguments.

class: Drupal\Core\Cron
arguments:
  - '@module_handler'
  - '@lock'
  - '@queue'
  - '@state'
  - '@account_switcher'
  - '@logger.channel.cron'
  - '@plugin.manager.queue_worker'
  - '@datetime.time'
lazy: true

It's backward compatibility.

Strictly speaking, constructors are excluded from BC, but the reality is that it is fairly common that one has to override them to inject additional dependencies.

The fallback to the global service means that if such a child class calls the constructor without that argument, it is not going to fatal.

That's especially common for base classes like ContentEntityForm, ControllerBase and other base classes that are specifically designed to be subclassed.

It can also be helpful during updating from an old version, because when running update.php in the UI, the class might be instantiated before Drupal has a chance to rebuild the container and provide the new arguments.


print cck field using node_load I found simple code to put inside custom module that prints extra field inside cart view table

<?php
function ucaddsku_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'uc_cart_view_form') {
$form['items']['#columns']['model']['cell'] = 'SKU';
        for($i=0;$i<count(uc_cart_get_contents());$i++){
        $form['items'][$i]['model']['#value'] = node_load($form['items'][$i]['nid']['#value'])->model . ": ";

    }
}
}
?>

How can be any cck field printed like this?

You can print the cck field like this.

// Load the node.
$node = node_load($nid);

// Print the fields.
print $node->title;
print $node->field_myfield[LANGUAGE_NONE][0]['value'];

or a more decent way like this...

$myfield = field_get_items('node', $node, 'field_myfield');

https://api.drupal.org/api/drupal/modules!field!field.module/function/field_get_items/7

See this also. https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_view_value/7


how create then trigger ajax action with D7 ajax API in js i modified views_load_more module and create a custom ajax command:

Drupal.ajax.prototype.commands.custom_views_ajax_command = function(ajax, response, status) {
    //append new content has been loaded to old (scroll auto load: slimScroll + waypoints)
};

and this's my behaviors:

Drupal.behaviors.cva_autoLoad = {
    attach: function(context, settings) {
        $.each(Drupal.settings.cva_autoLoad, function(i, st) {
        //if scroll down to last row: $(views li.pager-next a).click();
    }
}

everythings work fine, but i dont know how to trigger the next link click event if height of views is shortern than window.height()

when views is initial, if its height is shortern than scroll bound height, i want to trigger ajax load automatically

i tried this, but no luck

if(/*this height < window height*/)
    $(next_link).click();

even without condition, nothing happens

i call drupal_add_js in function render($input) (views_plugin_pager)

how to fix this? or does anyone have any better ways?

sorry about my urgly english

EDIT

maybe my question is so stupid. if yes, plz let me know.

i really need help

i found this when read ajax drupal core and views:

var setting = Drupal.settings.views.ajaxViews['views_dom_id:'+st.view_dom];
setting.page = 1;
$.ajax({
    url: Drupal.settings.views.ajax_path,
    type:'POST',
    data: setting,
    dataType: "json",
    success: function(response) {
        console.log(response);
        /*call Drupal.ajax.commands here ( it should be custom_views_ajax_command above*/
    },
});

does anyone know how to call Drupal commands or some ways are more legal?

yeah. thank askibinski so much!
in this post: XHR2 upload using Drupal 7's ajax framework

and this is my solution:

if($(viewDom).height() < height ) {
    var element_settings = {};
    element_settings.progress = { 'type': 'none' };
    element_settings.event = "click";
    element_settings.setClick = false;
    element_settings.url = Drupal.settings.views.ajax_path;
    element_settings.selector = viewDom;
    var setting = Drupal.settings.views.ajaxViews['views_dom_id:'+st.view_dom];
    setting.page = setting.page || 0;
    ++setting.page;
    element_settings.submit = setting;
    new Drupal.ajax(null, $(viewDom), element_settings).eventResponse($(viewDom));
    return;
}

and my real question is: how create then trigger ajax action with D7 ajax API in js

thank everybody alot.


Drupal site moved from development to live - IE won't load stylesheets anymore Before you ask ... I have looked everywhere for a solution, even drupal.org but nothing so far seems to work.

I developed a Drupal site (custom child theme for Zen) and on the development server everything looks fine in all browsers.

I did a test migration to another server before the launch. This move went well and everything looks fine in all browsers.

Then I moved the site to its live server where everything looks fine in all browsers except Internet Explorer which is not loading the stylesheets.

I know Drupal is known for generating many stylesheets and Internet Explorer will not load them if there are more than 31 (I believe) of them, but I did set the "Aggregate and compress CSS files" feature and clear the cache. This did not seem to help.

Could the answer be in one of the two following things?

The development site and backup site are both with one hosting provider. The live site is with a different hosting provider.
The development site and backup site are in subfolders of two different portfolio sites ... ie www.portfoliosite.com/Newsite.
The live site is a subdomain of the parent site ... ie www.newsite.parentsite.com.

I have run out of ideas so if anyone has a possible solution or direction to look, please let me know. Thanks

I would start by checking two things:

Is there a difference in settings for caching and/or CSS aggregation on live vs. dev?
Have you tried clearing the cache via the button in the UI? Doing it from drush does not clear the CSS caches, and it also has some other behavior that's different from the UI button way.


avoid duplicated records with drupal_write_record I want to test drupal_write_record, the insert part is ok, but this function seem to duplicate records.

How to make a condition for if new record is already stored ?

some like db_merge with key

Thank you

This function can take 3 arguments , in this situation the third argument acts as an array of primary keys and if we pass the third argument to the function (primary key), it will update the record, if don't pass - it will insert a new record .


Add a condition to show menu link in YML how should I do if I need to show to a link menu based on a condition ?

This is my YML for my menu link :

double_vue_klesia.backuserswitch:
  title: 'Retour user précédent'
  menu_name: navigation-principale
  description: 'Switch back to your user account.'
  route_name: double_vue_klesia.backuser.switch
  weight: 1

I want to show this link only :

if (\Drupal::service('userswitch')->isSwitchUser())

This is in PHP, but I need this to be on YML (unless there a way to intercept it in php and hide it ?).

If my isSwtichUser is true (from my service), I want to show the link. But I can find a way to do it.

EDIT :

I'm using this module : https://www.drupal.org/project/userswitch

I "just" need to display a link to go back to the original user (link accessible from my frontend)

you can add custom access on route_name: double_vue_klesia.backuser.switch

double_vue_klesia.backuser.switch:
  path: '/path-of-you'
  defaults:
    _form:  '\Drupal\my_module\Form\DemoForm'
    _title: 'title'
  requirements:
    _custom_access: '\Drupal\my_module\Controller\ApplicationController::accessCustom'

Inside \Drupal\my_module\Controller\ApplicationController:

 /**
   * Check user has permission.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function accessCustom() {
    if (if (\Drupal::service('userswitch')->isSwitchUser())) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }


Add custom class to views row depending on field value I'm using views to show different fields of an entity. If the uid of the entity is the current user I would like to add a custom class to the entire row (not only to the field).

I wrote the following preprocess function that works fine if I use the entity in views, but I don't know how to change it when I use fields instead:

function my_module_preprocess_views_view_unformatted(&$variables) {

  $view = $variables['view'];

  if ($view->id() == 'my_view' && $view->current_display == 'page_1') {

    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {

      $uid = \Drupal::currentUser()->id();

      $owner = $row['content']['uid']['#object']->get('uid')->getString();

      $class = ($uid == $owner) ? 'own' : 'other';

      $custom_row_class = 'views-row-' . $class;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }

  }
}

Can you please try the following code snippet. I swapped the line to retrieve the author's user ID.
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_views_view_unformatted(&$variables) {

  $view = $variables['view'];
  if ($view->id() == 'MY_VIEW' && $view->current_display == 'MY_DISPLAY') {

    $uid = \Drupal::currentUser()->id();

    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {

      // Get user ID.
      $owner = $row['content']['#row']->_entity->get('uid')->target_id;

      $class = ($uid == $owner) ? 'own' : 'other';
      $custom_row_class = 'views-row-' . $class;

      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}


How to debug users geting automatically logged out for unknown reasons? For our Drupal 6 site, we've experienced such issue that logged-in users are getting logged out for around one week or several days.

Firstly I thought this might happen with Boost module, but it seems this issue happens as our test site that runs without boost enabled. We have already set cookie time long as following in settings.php

ini_set('session.cookie_lifetime',  2147483647);
ini_set('session.gc_maxlifetime',   200000);

This site is pretty big and includes a lot of custom modules/code, which make it difficult to debug what's going on. I greb the code, and no luck to find session_destroy code, or user logout code. Maybe I need to set session.gc_maxlifetime as large as session.cookie_lifetime?

Is there some way to debug this issue when users are logged out?

This issue is solved by updating this setting

ini_set('session.cookie_lifetime',  21474836); The original value '2147483647' is too big for some reason.


Exclude some, not all, user profiles from search engine results Is there a way to let users choose if they want their user profile to be excluded from external search engine results? Any modules or hooks known?

It should be based on the de/selection of a boolean field "Display my user profile in search engine results".

There is and there is not, there are two sides of that question.

Bad side is - external search engines are just that: external. You can send them suggestion but you cannot make sure they respect them.

Good side is - you can create a field, and if it's checked output: <meta name="robots" content="noindex" /> Some search engines, including Google, Bing and apparently Yahoo! (can't find a link for that one), will respect that.


comment body size in hook_form_comment_form_alter What is the correct syntax to alter the size of the comment form body text area?  I can't for the life of me find it in devel dpm.

$form['comment_body']....something....

You can use the #rows and #cols properties to define the height and width respectively:

$form['comment_body'][LANGUAGE_NONE][0]['#rows'] = 10;
$form['comment_body'][LANGUAGE_NONE][0]['#cols'] = 50;


How can I force a view page not to be cached? I created a few views which I use as JSON endpoints for a client application. However, they are not refreshed along with the content they serve.

What I have tried with no success:

Setting Caching to none (within the View page).
Disabled Views cache, (in Views' advanced settings).
Running drush cache-rebuild as a cronjob every 12h.

I know I can use a workaround like /api/my-endpoint?time=1234, but this is not an option for me, since I have no access to the consuming client's code anymore. Neither I plan to recreate all these endpoints in custom code.

How can I force a JSON view page not to be cached?

This is probably not related to caching inside of views, more likely on page level. You can disable page caching with the route option no_cache. Use a RouteSubscriber to alter the routes of views:

/src/Routing/RouteSubscriber.php

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {

    // no_cache for a specific view
    if ($route = $collection->get('view.testview.page_1')) {
      $route->setOption('no_cache', TRUE);
    }

    // or for all view displays of a specific type
    foreach ($collection->all() as $route) {
      if ($route->getOption('_view_display_plugin_id') == 'rest_export') {
        $route->setOption('no_cache', TRUE);
      }
    }

  }
}

mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

This would not be necessary, if the view set the correct cache tags for the content it serves, so that the render cache could be invalidated if the content is changed.


Error when activating the View Mode Page module I am trying to activate the View Mode Page module because I need to use URLs to jump from one view mode to another. From teaser to presentation to full node.
Every time I try to activate the View Mode Page it gives me an error and after that I am unable to view the Manage Display section for any of my content types. It mentions there is an error in the view_mode_page.module (or something similar).
Does anyone know if this module is incompatible with some other modules or what the problem might be?

Thanks in advance.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drp_obdcbn7hei.view_mode_page' doesn't exist:

SELECT view_mode_page.* FROM {view_mode_page} view_mode_page WHERE (content_type = :db_condition_placeholder_0) AND (view_mode = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => tu_mooc [:db_condition_placeholder_1] => default )

  en view_mode_page_get_patterns() (línea 281 de /hermes/waloraweb021/b1678/moo.blasbray/sites/all/modules/view_mode_page/view_mode_page.module).

I don't know about the View Mode Page module specifically, but here's how you can find out yourself.

Check the issue queue for the module.  You can find a link to "all issues" on the module's project page (in this case, here).  In this case, there aren't many issues; if there were a lot, you can use the search function.  If searching, make sure to set the status to all issues, not just open issues, as if you're lucky your issue will already have been reported and fixed.
If step 1 doesn't solve the problem, create a fresh install of Drupal 7 on your local machine or another server and install the Views Mode Page module and its dependencies.  Make sure it works properly by itself when you have no other modules enabled.  (For a small module like View Mode Page which has less than a few hundred installs, this step is especially important; for an extremely common module like Views itself, you can assume that someone has already done this and it's your problem.)
If step 2 doesn't solve the problem, you'll need to start disabling the modules on your site one by one.  Of course, don't do this on your live site-- do it on a backup site.  Just guess which module might be causing the problem, disable it, and then clear the cache.  Then try to enable Views Mode Page.  If it doesn't work, choose another module to disable and repeat.

Yes, this is really painful and frustrating, but sometimes it is necessary if a search of the issue queues on drupal.org doesn't turn up anything.  If you do have to do this and find the source of the problem, please don't forget to create an issue on drupal.org and report what you found!


How to display tokens on a page in D7 Drupal 7 built tokens into core. Is there a way to display tokens on a page without modifying a template?

Token Filter does the trick. After the module is enabled, you can edit or create create a text format that replaces tokens with text: admin/config/content/formats


How to override user_picture per comment? I use the facebook connect plugin. By default it downloads the 50x50 pixel facebook image. It luckily stores it as the profile ID, which I can in turn use to look up the large version of the image. So I need way to:

Get the current user_picture for a comment, and then
Override it with a new url.

I have this so far:

function capewinefarms_preprocess_comment(&$variables)
{
    $comment = $variables['elements']['#comment'];
    $variables['comment_create_date'] = format_date($comment->created->value, "custom", "d M Y, H:i:s");

    $variables['user_picture'] =  'BLA';
}

The above code replaces the user's profile pic with the words "BLA". But I don't want that. So I need a way to see what the variables object looks like, so I can see where to get the current value and to change it. But if I do this:

print_r($variables);

It just bombs out and shows a blank screen (as if the variable is blank).

How do I change the user picture?

A dump of the $variables array is probably causing out-of-memory problems as preprocess variables in D8 can have some heavy depth to them.

Anyway, you can retrieve the image url from $user_picture render array which has a reference to the comment's user:

  $comment_user = $variables['user_picture']['#user'];
  if ($user_image = $comment_user->user_picture->first()) {
    $user_image_uri = $user_image->entity->uri->value;
  }


Is there a way to show all routes used? I want to get a list (dump) of routes used?

Example:

/user/register
/user/logout
/custom/route
/node/27/some-description

If you are using the Drupal Console, you can use the command :

drupal router:debug

This will print all the routes on your site including routes from core.

The other solution is to use the Devel module and going to "devel/routes".


How to include desktop css file only on desktop & mobile css file only on mobile? I have two different css files in my theme, one for Desktop and other for Mobile version. I want to render Desktop css file only for desktop mode and Mobile css file only for mobile mode.
Do I need to make any modification in .info of my Theme?

Yes, you can do this with media queries in your info file.

Change...

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

to...

stylesheets[all and (min-width: 960px)][] = css/style.css

That being said, you can repeat a lot of work doing it that way. It might be easier to declare all of your styles that you know will change in a responsive.css style sheet, and use

@media all and (min-width: 768px) { /* all of your styles here */ }

At the bottom to change the values for a mobile version.


How to create a path alias with a query string in the target? I want to link /myownstuff to /stuff?owner=myself

It should at least be possible to do with some module, and with httpd-level configuration, but I don't know how to achieve either of them.

I think you can do this with the Redirect module (it won't provide an alias in its truest form but it will forward you on to the right page.

In .htaccess you could a custom RewriteRule before Drupal's main index.php rule:

RewriteRule ^myownstuff$ stuff?owner=myself [L,QSA,R=301] # QSA and R=301 are optional here

If neither of these work there is a quick and dirty way in a custom module:

function MYMODULE_init() {
  if ($_GET['q'] == 'myownstuff') {
    drupal_goto('stuff', array('query' => array('owner' => 'myself')));
  }
}

If you've got more than one path to forward/a pattern etc. you'll have to extend this a bit but the logic will work.

I think the .htaccess is probably the best way as it doesn't actually forward on to the URL but masks it internally which I guess is what you're after.

You might also want to look at hook_url_inbound_alter() which I believe you can use to get this kind of functionality...I've not used it before so I can't comment further though.


Connect to Intersystems Cache DB via ODBC I'm trying to connect to an external data source within out intranet site. The database is Intersystems Cache. Our web-servers are running Cent OS 6.4, so I have setup the necessary unixODBC drivers to connect to it and this is successfully working. What I'm struggling to work out is how I access this data from within Drupal.

I know I could just call odbc_connect within my code, but this isn't the Drupal way. I also loose the benefits of Memcached etc.

Would it be possible to use PDO's ODBC driver, which I think Drupal uses anyway?

Thank you.

As @Bala said you want to try to install the PHP ODBC driver. Drupal does not use this driver by default (a drupal install may use MySQL, Postgres, or I believe MsSQL on install if those drivers are found by PHP).

Once the ODBC driver is installed for PDO, you can inform Drupal of your 2nd database by following the Multiple Databases Documentation. Bala linked you to a previous example I gave using ODBC to an MsAccess database file -- you're request is simply a different DBMS vendor. The same approach should work InterSystems Cache DB by following the concepts in the documentation page linked about.

Note that ODBC is a slow interface as its essentially a wrapper to your client Database. Its not as fast as a full native DBMS driver. Keep that in mind when querying and using your data.


File in field_file disappears after saving a node Like I wrote in the title. After I upload the file it is being saved in my folder correctly, but after I save the node, it just doesn't remember I have uploaded it. The file stays in the folder I uploaded it to.

Is there any way to solve it?

The File module enables you to upload and attach files to content and to manage these uploads if you have the appropriate permissions. This module is responsible for validating file content and managing uploaded files. It also provides options for displaying file content.

As a site administrator you will be able to control what type of files can be uploaded and their maximum size.

File module provides its functionality by defining a File field type for the Field module. File attachments are defined at the content type level (or other entities). To learn how to define a field and add it to a content type, see Working with Field UI.

Uses
Adding a file field to a content type

Navigate to the "Manage fields" tab of the content type to which you wish to add the file field (Administer > Structure > Content types, and the link manage fields for your specific content type).

Select the field type file, give the field a label and machine name, click-and-drag it to the place you want to have it among your fields, and hit the save button.

As when adding any new field, you are first required to set the field specific settings. These apply for all places where you use the field. These cannot be changed per entity.

When checked, the Enable Display field option allows users to choose if a file should be shown when viewing the content.
The Files displayed by default option makes the display file option checked by default, when users upload files to this field.
The Upload destination by default only has the public files option available – making the files available right from the server (without Drupal checking any access). If you want to use private files, you must first change some settings at the file system administration page (Administer > Configuration > Media: File system). See below for details.

The next step is to set the field settings for this instance only. This can be changed between different content types (or other entities).

You can add validation options for the File field when you configure the content type. You must list all of the file extensions that the final user will need to be able to upload. The optional file directory where the files will be uploaded is a sub-directory of the file system path defined in the file system administration page (Administer > Configuration > Media: File system). You may specify a maximum file size for each file uploaded.

Managing attachment display

Once a file has been attached to content, you can specify whether it will be displayed in the list of attached files or not. Listed files are displayed automatically in a section at the bottom of the content; non-listed files can for example be embedded in your content, but are not included in the list. (Embedding a file in your content means you copy the path of the file and manually embed it where you want, for example, to insert in the content as a link tag. Note that the text format "Filtered HTML" by default refuses any image tags..)

Additional options for managing the display of the file list are available in the "Manage display" tab of the specific content type's administration page (Administer > Structure > Content types and the link field display for your content type).

For reference: Working with files in Drupal


How to convert a webform to a content type? I have a long webform with about 90 textarea fields modeling a report item. Since the requirements of my Drupal site have changed, the report is now part of the content and should have workflow and other content type functionality.

So I want to convert my webform with its 90 fields to a CT. I know this will raise some problems regarding the performance, but I was thinking to overcome them by reusing some textarea fields (e.g. by putting them in different field collections in the same content type and changing their title and description only per field instance).

Is there an easy way to convert my exported webform with its fields to a content type with the same fields? Or should I do it manually?

Unfortunately, there is no easy way to take a massive webform form and convert its form fields into a Drupal Entity + Fields. And yes when you want to re-architecture your website and do this for 50+ fields -- it sucks (been there).

Because some things like the Workbench module only work with things that are Nodes. And when you initially choose a webform to represent this data you've coded yourself into a corner.

This is kinda 1 place where Drupal is somewhat lacking -- interopability between similar tools (webform, entityform, entities, ECK, etc).

There are some tools to "move stuff around" such as:

https://drupal.org/project/bundle_copy
https://drupal.org/project/replicate

But they only work within 1 kind of architechure (Entities).


What causes 'sites/default/files is not writable' during Drupal 7 Install on Redhat w/ Apache? I am attempting to install Drupal on Linux Redhat using Apache, but it will not allow me to pass step 3 due to the fact that sites/default/files is not writable.

I have followed the instructions on Drupal.org, in their install.txt file as well as the instructions from others who have had the same error with no success.

I have granted permissions access all different ways, i.e.: root:root 777, root:apache 777.

I have also verified that Apache is the user running the Apache process, but I am still stuck.

Notes:

I have granted the user 'apache' 777 rights to the files folder with no luck.
I verified the user 'apache' is in fact the user running apache.
I was able to complete the installation of Drupal on Windows.

Any new ideas?

I thought this would be a SElinux issue with security and I am a bit surprised that your solution worked.

For users with the "common" error, use the following command to provide apache with access despite SElinux security.

chcon -R -t httpd_sys_content_rw_t yoursite/sites/default/files/


How can I use CKEditor for teaser text on a long form text field? In Drupal 8, the teaser text for a long form text field (specifically, text of type "long, formatted, with summary") does not have a CKEditor wrapper around it:

How can CKEditor be added to this textarea?

This is core limitation right now.

I would recommend that if you want an editor on a teaser/summary field, you simply create a separate field, that also gives you options like having a separate text format for it.

The text long with summary field type might eventually get removed in Drupal 9 or so.


What are the reasons that the "Show block on specific pages" settings wouldn't work? I have a site with a large number of blocks, but I just added a new one that's only supposed to show on one page but it shows on every page. If I exchange it with another block I have the same problem. If I remove a bunch of blocks the problem remains.

If I put  in show on all pages except those listed, it will still show on the front page. If I only put something like about with "Only the listed pages" selected, it will still show on the front page. This is happening with different types of blocks.

I've disabled Context, and Display Suite. I've flushed the cache tons of times. What could be overriding this setting?

It turns out that the issue was that there was, at some point, a theme with the same name but with different capitalization. It looks like this led to inconsistent results when looking up which blocks should be displayed and when. Once I removed all the entries in the block table to the old theme the problem was resolved.


Drupal View for the 10 Most Recent Items Sorted by Date ASC Is it possible to construct a view of the 10 most recent nodes sorted by date in ascending order?

This sounds simple, but it seems as if it's more complicated than I'd imagined.

I think to do this in SQL you'd need a subquery, and I can't see that views is capable of that...

...or is it possible to reverse the order of the rows in the view after they're brought back from the database?

Have a look in the following image. This is a view of the 10 most recent nodes, sorted by post date (ascending).

If you meant to something else, please clarify the question.

If its a working solution for you, you are more than welcome to accept the answer by clicking on the checkmark ✓ (and thumb up if you liked it very much).


Where to override images rendering I created my custom content type and add field called 'Image' of type Image and set the content manager can set multiple images into it. Now this field is rendered as such html

Image:&nbsp;

I cannot find where are the template(s) which render this piece of html. I'd like to override it to render list of links, similar to

Image:&nbsp;

img1.jpg

img2.jpg

The function is theme_field() which could be customized by having the right override of the field.tpl.php template in your theme (through template suggestion, see the theme_field() function documentation.

Inside this function/template, the image is rendered by a field formatter. The print render($item) statement print that rendering. The exact used function/template depends on the configured formatter. If your are usign the default formatter, that would be theme_image_formatter().

Note: See the theme() function's documentation for how to override the theme_* functions in your theme or module.


Memory usage PHP peak=40.25 MB -- too much for a single request? I am developing a multilingual - multidomain site ( using i18n and Domain Access and several extra modules - CTools, Colorbox, etc. ). I have installed Devel because I thought the site was very memory consuming. I have seen peaks of PHP peak=40.25 MB in many of the pages. Is that too much? What happens if there are many concurrent users? Will the 128 PHP memory limit be able to handle many requests, will it use hard-drive memory instead of RAM ?

The memory limit setting (often 128MB) is per process, so you're only using around third of it. If a single request needs more than 128MB of memory, it will fail. This doesn't appear likely in your case.

  What happens if there are many concurrent users?

That depends on your total amount of RAM. You can in theory handle up RAM / 128 MB users.

If you have 15 concurrent users, each using 40MB, and you have 512 MB, then you'll go over that limit, because 40 * 15 = 600.

The normal configuration is then to use the hard-drive, often called swapping. This normally means the death of all performance, and should always be avoided, to the level where it's better to out right reject more incoming connections.


How to tag content by users and filter the content in a view? I have a content type Meeting Minutes. I'd like to tag users in the minutes. There will be a view to the list of minutes only for the logged in user.

For example:

Meeting 1, tags Peter, Mary
Meeting 2, tags Paul, Mary
Meeting 3, tags Peter

When Mary logs in, the view shows:

Meeting 1
Meeting 2

When Peter logs in, the view shows:

Meeting 1
Meeting 3

Is there a user tags module for a content type and good for view-filter?

Add entity reference field in Meeting Minutes use entity type user and then tag users from there with you  content of Meeting
now in views
use Contextual filters
add Contextual filters select you user reference field like if your field name is

Content: user in meeting

then select

Provide default value

from check boxes a select list will be appear then select from them

User ID from logged in user

and done
Now when page load content should be filtered with current user id
i think this will solve your problem


Set Value to a select field by its key in webform I'm trying to set a select field to one specific default value by it's key (one country, which i retrieve from another form), and then disable the field.

I implement hook_form_alter, i get the correct field inside the $form array, but, when i want to set the select field to one value, nothing happens. I'm trying this way:

 $form['#node']->webform['component'][91]['value']['#default_value'] = $country;

But, this does not work. Any guess on how i can achieved this, and if this is possible or the right way to do it?

Thanks

This is the way I do it and it works:

// set default value to a D7 form field
$form['FIELD_NAME']['und'][0]['value'] = $country;

// prevent user from changing the field value
$form['FIELD_NAME']['#access'] = false;

Hope this helps.


When while saving nodes do I have old and new vid available at once? I'ld like to programmatically trigger some very basic email notification when a new revision of a node is being created. I want to send a link to the compare page /node/$nid/revisions/view/$old_vid/$new_vid.

But I wonder on which hook when saving a node do I have the old and the new vid available at once? hook_node_presave() looks like a dead end to me.

This question is not specifically about D7. Though it's D7 I'm using right now, I'ld prefer to find a solution for both D7 and D8.

You simply can add a custom submit callback to the node form.

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

  $node_forms = [
    'article_node_form',
  ];

  if (in_array($form_id, $node_forms)) {

    // Add a custom submit callback.
    $form['actions']['submit']['#submit'][] = '_MYMODULE_postsave';
  }
}

There you can access the original vid from the $form_state array. And when you load the freshly saved node you'll have the new vid available.

/**
 * Custom submit callback.
 */
function _MYMODULE_postsave($form, &$form_state) {

  $old_vid = $form_state['values']['vid'];
  $nid = $form_state['values']['nid'];
  $node = node_load($nid);
  $new_vid = $node->vid;

  // Voilà!
  dpm($old_vid, 'OLD_VID');
  dpm($new_vid, 'NEW_VID');

  // Do your stuff here
}

For reference: https://drupal.stackexchange.com/a/221041/15055


View per content type I'm using Drupal 7 and Views. I have 4 different content types and I want to be able to display each content type in separate view. What i did is I create a view and a page and i set the view Path to node/%

After that I'm using contextual filters to get specific node. It's working when I'm on view creator page and the preview.

I have 4 such views, each for particular content type.

When I save the view and I'm trying to load a page it takes wrong view and it gives no results found.

How to solve that issue and have multiple node/% pages? Is there something like views order or priority in loading? Shouldn't it have any filtration and pick the correct view based on content type?

Any tips will be appreciated:)

It won't work, if you give same path for different views/displays then it will load the view/display with the least id.

But why you want to give same path for all views?


Use MenulinkTree::load in page_preprocess I'm on drupal 8, and i want to get menu links from the main menu in order to create the same menu for mobile (so i need 2 same menu, with differents rendering)

I use like this :

function template_preprocess_page(&$variables) {
    $variables['menu'] = \Drupal\Core\Menu\MenuLinkTree::load('main');
}

But it's broke my website.

What do you think about that ?

It is because you don't use a second (mandatory) parameter. Look at this example:

$menu_name = 'main';
$menu_tree_service = \Drupal::service('menu.link_tree');
$menu_parameters = new \Drupal\Core\Menu\MenuTreeParameters();
$menu_parameters->setMaxDepth(1);
$tree = $menu_tree_service->load($menu_name, $menu_parameters);

You could also set a root menu item like this:

$menu_parameters->setRoot($root_menu_item->getPluginId());

To get the menu link title and url:

foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url = $item->link->getUrlObject()->toString();
}


Link manually uploaded file to files-private folder I have uploaded a large size folder via winscp to a external hosted server to the files-private folder in drupal. when i try to access the index file inside the folder in browser i get access denied. Is this because there is no entry in file_managed table ? however i could access the URL by doing same setup on a dev server without any issues.

With the private file system you cannot link direct to the file path because navigation of the private files directory is prohibited.

You have to link to drupal's private file handling url, which will then check that the current user has the correct permissions to view the private file and if so grants them access and gives them  the file.

To utilise this you need to use drupal's system/files path.

So if your private files directory is files-private and you have a file files-private/filename.txt you would link to /system/files/filename.txt and drupal will handle the rest.

[Edit]
The above is still valid information, however to answer our question, yes the files need to be in the file_managed table otherwise file_file_download(), which handles private file downloads, will skip over your files because it uses file_load_multiple() to try to load your file from the database.

file_load_multiple() uses entity load and system_entity_info() defines the database table file file entities as file_managed.


How to match a Drupal path in Apache config My D8 site uses the usual convention in .htaccess to rewrite non-file requests to index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*) index.php [L]

However, if I try to perform a location match in my Apache 2.4 httpd.conf virtualhost, it fails because it seems that REQUEST_URI is set to index.php.

<Location /foo/bar>
  #Directives that should fire when accessing /foo/bar but don't
</Location>

<Location /index.php>
  #Directives that do fire when accessing /foo/bar
</Location>

Any ideas for getting this to work?  I have tried:

<If "%{REQUEST_URI} =~ m#^/foo/bar#">
  #Directives that should fire when accessing /foo/bar but don't
</If>

<If "%{REQUEST_URI} =~ m#^/index\.php#">
  #Directives that do fire when accessing /foo/bar
</If>

The directive I was trying to insert was Require all granted.  I managed to achieve the same effect by proxy-passing requests for /foo/bar to another virtual host running on the same machine, but unreachable from outside.  That 2nd virtual host did not require auth, which achieved the same effect as Require all granted.

ProxyPass /foo/bar http://example.local/foo/bar
ProxyPassReverse /foo/bar http://example.local/foo/bar


How to hook bundle create/read/update/delete events? There's an ongoing discussion about how there should be CRUD hooks on bundle events, hook_entity_bundle_[create/load/update/delete/etc] (currently in the context of Drupal 8).

In the mean time, in Drupal 7, what's the closest thing we have to a hook_entity_bundle_create? To put it another way, how best to define a function that will be called every time an entity bundle is created, where the function can access data about that bundle?

The above link mentions the hook_field_attach hooks (the Field Attach API), but it's not clear which if any of these hooks will be called reliably on bundle editting.

It's be great to clearly get down what the current equivalent of bundle CRUD hooks are.

So here's the best I can find so far. It's not great.

Create: There's hook_field_attach_create_bundle, but it doesn't automatically get called any time a bundle is created. Seems that every module for every entity with bundles has to call field_attach_create_bundle($entity_type_name, $bundle_type_name); every time a bundle is going to be created/saved, else the hook doesn't know about it. It seems not to do anything except call the hooks - I've seen modules that forget to add this line.
Read: I can't find an equivalent here (no big deal I guess as it's not clear what 'reading' a bundle would mean - accessing info on it?)
Update: The closest I can find is hook_field_attach_rename_bundle. Not great.
Delete: There's hook_field_attach_delete_bundle. Like ..._create, it needs to be called in the code, so some modules' entities might not call it. But it appears that field_attach_delete_bundle() actually handles the deletion of field data, so it's less likely to be forgotten or overlooked.


Limiting node access to certain users based on an entity reference field. Which hook to use for when node is viewed? Scenario:

"Teams" content type has user entity reference field.

"Manager" role can add teams to nodes they have created and the teams will change often.

Members of the team can only view the nodes (and nodes that reference that node through another entity reference field) whenever their team is assigned to them.

For these content types, performance isn't an issue. What I want to do is use a series of views_get_view_result when the node is viewed and redirect away from the node if necessary. That part is easy.

What is the best hook to use for when the node is viewed and I can run my views to find out if the user should view it?

Thanks

In similar situation I used hook_entity_access. Also there is hook_ENTITY_TYPE_access so you can use the hook_node_access.


How to sort language select list on current language context I have a form with a language field with the language select list widget.
The options of this field contains an array with a pattern like

['langcode' => t('language')]

Now I want to sort these options in the right order.

The default sorting is on the value but not on the translated one.

e.g. ['de' => t('german')] which I translated into "Deutsch" will now sort under "g" instead of "d".

So I did try to do it in a form alter hook and a preprocess hook but this is not the right place to do it, because the values are still untranslated here.

So my question is how can I sort these options if the values are translated?

i think it can be done in a hook_form_alter()

if the options are in $form['languages'], you can do something like :

$language_options = $form['languages'];

then manipulate the array $language_options, until it has the order you need
then override it in form :

$form['languages'] = $language_options;


Custom language negotiation module not working I'm writing a custom module to allow the use of language a language suffix (of the form -eng or -fra) rather than the standard prefix.

I'm using the language's configured prefix and have a number of functions in place.

I've implemented hook_language_negotiation_info, and have a language selector, switcher and rewriter in place.

Paths with the suffix are working except that urls aren't being updated with the suffix when they're printed in the menus, or other places.

I confirmed that the rewriter callback is being called by placing a dsm() call in the function and it seems to be taking "node/45" and returning "page/45-eng" based on the alias.  That aliased path works, but a url to "node/45" prints returns "page/45"

function custom_lang_language_negotiation_info() {
 return array(
    'custom_language_provider' => array(
      'callbacks' => array(
        'language' => 'custom_lang_language_getter',
        'switcher' => 'custom_lang_language_switcher_url',
        'url_rewrite' => 'custom_lang_url_rewriter',
      ),
      'file' => drupal_get_path('module', 'custom_lang') . '/custom_lang.inc',
      'weight' => -10,
      'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
      'name' => t('Custom path suffix'),
      'description' => t('Determine the language from the URL suffix.'),
      'cache' => 0,
    ),
  );
}

Thoughts or something I can try?

I may be missing something in the way urls are generated or maybe the path is being reverted somewhere.

I did the configuration with yml file.. try this solution

https://www.drupal.org/node/2775809#comment-11502283

It worked for me.


How to create 2 product node displays How can I create 2 displays of a products node one for Authenticated users and one for anonymous ?

I am trying to create a single products display for my site that will display the product image and all of its fields for a single product basically like most eccomerce stores do with the image on the left and all the details on the right

there needs to be two versions of the display one for anonymous users that will display product without the add to cart button and price fields and rather display Text stating "we do not supply directly to the Public"

and then another display for authenticated users that will display the price and add to cart button.

this was easy to do for the grid views of products on my site I just created 2 views with role based access but for the actual single products node I aparently cannot use views because it is a node.

I am thinking I need to use display suit but how can i create 2 displays and use role based access.

You can use Entity view modes to create two displays for an entity.

  The Drupal 7 successor to Build modes which will allow administrators
  to define custom view modes for entities.

I'd probably then use Panels to output the product displays (but that's because I'd already be using Panels). Most likely two variants of the node_view page that both check user role. If a logged in user is discovered, then use a variant that uses view mode X, if the user is anonymous then use view mode Y.


Need to be able to disable taxonomy term, but maintain legacy Need to be able to disable taxonomy term, but maintain legacy. Attempting to populate a drop down with taxonomy term, but have a required to disable a specific term, but still maintain the data.

Another way to describe what i'm trying to do. Is not allow a user to select a specific term in the drop down.

Depends where you wish to add the term. If you need to add it to a Node creation page, you could always, instead of adding the field as a term reference, add it as an entity reference, select Taxonomy Term as target, select the correct bundle, and in ENTITY SELECTION, select Views: Filter by an entity reference view.

In order to do that you will beforehand need to create a view on the taxonomy terms that you wish to display and hide (ie filter out those terms that should not be displayed), then add this view to the dialog that will appear when you select Views: Filter by an entity reference view


How to display current user name in webform field? I have created one webform with Name,Email id, Address fields.
if user is login in name field already fill with 'login user name' and no one login then its fill with 'Anonymous'.

my issue is if user login its fill with login user name but not login then filed should be blank not fill with 'anonymous'.

Please help...

You can alter the webform and put some and achieve this.

<?php
    function module_name_form_alter(&$form, &$form_state, $form_id) {
   // module_name = your custom module name.
       if($form_id =='webform_name')
        // webform_name = your webform id
           //check condition for non login user
           if(!user_is_logged_in()){
            {
             $form['submitted']['field_name']['#default_value']= 'anynomous';
             // field_name = Field name
            }
         }
    }

    ?>

You also need to debug using dpm. Which helps you solve you problem easily.

I believe that you can also do this using Rules module. You also need to try for this.


How does a PaymentGateway signal a completed order I'm trying to implement the Commerce Ingenico payment gateway for a Drupal 8 Commerce site. As this module is still in unfinished for Drupal 8, I'm fixing it up as I go. Most of the implementation is located in Composer packages, so it's mostly plumbing.

I'm hitting a bit of a wall now though. I'm using the off-site payment gateway, and I've configured the IPN (server to server notification). The values for the payment in the database look good*, but the Cart never turns into an Order. Somehow the trigger for signaling a completed payment to the order is missing.

The results is that after returning from the offsite payment (and the onNotify has already been triggered, so the payment is marked as completed), I end up back at the start of the payment flow; the order summary.

How are these parts supposed to fit together?

Here's the code to the onNotify method in the PaymentGateway:

public function onNotify(Request $request) {
    parent::onNotify($request);

    // Common response processing for both redirect back and async notification.
    $payment = $this->processFeedback($request);

    // Let's also update payment state here - it's safer doing it from received
    // asynchronous notification rather than from the redirect back from the
    // off-site redirect.
    $state = $request->query->get('STATUS') == PaymentResponse::STATUS_AUTHORISED ? 'authorization' : 'completed';
    $payment->setState($state);
    $payment->setAuthorizedTime(REQUEST_TIME);
    if ($request->query->get('STATUS') != PaymentResponse::STATUS_AUTHORISED) {
      // setCapturedTime has been relegated to the mists of history
      $payment->setCompletedTime(REQUEST_TIME);
      // $payment->setCapturedTime(REQUEST_TIME);
    }
    $payment->save();
  }

And this is the resultant row in the commerce_payment table:

 payment_id
13

type
payment_default

uuid
payment_default

payment_gateway
ogone_offsite

payment_gateway_mode
test

payment_method
NULL

order_id
29

remote_id
3039111240

remote_state
9

amount__number
26.400000

amount__currency_code
EUR

refunded_amount__number
0.000000

refunded_amount__currency_code
EUR

state
completed

authorized
1534516744

expires
0

completed
1534516744

test
NULL

captured
NULL

Of course I don't know what these values are supposed to look like. I'm actually a little concerned about payment_method being NULL in this row. Is that normal for an offsite payment gateway, or should that be set to something?

A similar scenario has been discussed on #commerce Slack on Monday. In contrast to onReturn() no transition is triggered after onNotify().
@bojanz says:

it's a safeguard we'll need to add to Commerce, but won't have the resources to do so before october
once we have $order->balance and an order paid in full event, we can use it to auto-place the order
at least those two parts could land in september for 2.10

TL;DR
onReturn() must create a Payment, as suggested in a comment from @No Sssweat. In case PaymentGatewayException is thrown Commerce will redirect to the previous checkout step.
onNotify() can register info about payment but, at the current state, it won't place the order for you.


how to assign different default images to different roles I have only two profiles, public and registration but I have different roles and would like to add an appropriate default image for each role.

Must I create a separate profile for each role to implement this?

If you want to display an image for a particular user role , say "Role1" , then in page.tpl

 <?php global $user;
  if($user->roles[2] == 'Role1')
 {
 print $logo;
 }?>

Just print the $user to get in what values your role is in the role array.

If you print $user, your role may be in this,

 [roles](
 [1] = role1
 [2] = role2
 [3] = role3
       )

So choose your role and check the condition and accordingly print the $logo however before that get the image in $logo using the image source tag.


Multiform/Wizard module I'm looking for a module, that changes the workflow of creating a node. I want to be able to have several fields in named group sections so the author of a node has some structure.

But when editing the node the author should be able to quickly jump around the forms.

So for example the Content Type "Article" has the following group sections:
Content > Images > Related Articles

In each section there are fields.

How can I do that? Are there mature modules for that case?

You could check out the field group module. You have several options to group your fields:

Fieldsets
Horizontal tabs
Vertical tabs
Accordions
Divs
Multipage steps: Note: This is only client side.


Output from preprocess_views_view_field in Drupal 8 I tried to alter the Output of an View-field with function in Drupal 8:

function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];

  if ($view->storage->id() == 'myview' && $variables['field']->realField == 'field_sterne_value') {

    $string = "";
    $sterne = intval($variables['field']->getValue($variables['row']));

    for ($i=1;$i < $sterne;$i++){
      $string .= "<img src='/themes/mytheme/img/stern.png'>";
    }

    $variables['mystar'] = $string;
  }
}

The output should show the stars as Images, but shows the html-Code in Frontend.
I tried different encoding with htmlentities and html_entity_decode.
But it does not work or I did encoding in a false way.

In my custom twig-template I use {{mystar}}.
But the same problem exists when I use the original template with {{output}}.

Where is my error?

Use the raw twig filter - so, in your template:

{{ mystars|raw }}


Show  on user page if user page belongs to current user I have made a page that displays information about a user, much like a profile page.

Now I want users to be able to edit their information, so I added a button using twig tweak in user.html.twig:

{% if logged_in %}

Edit profile

{% endif %}

This works fine, however the button is displayed on every profile page. I want to hide the button if a user is viewing another user's page.

  Can this be done using an {{ if statement }} to check if the viewed page belongs to the logged in user?

To do this right you will need to use this combination of tests.

Is the user logged in {% if logged_in %} ?

Does the user have the permission needed to edit their profile with {% if user.hasPermission('depends on your site setup') %}?

Is the owner of the node the same as the current user?  {% if node.ownerId  == user.id %}

NOTE: The snippets above are not tested.  You may have to tweak to get the correct info (e.g. getOwnerId SHOULD equal node.ownerId.. but twig may have a different opinion).


How to create a button that creates an article with a specific tag? I'm administrating a public site and there's some other guys who add content, too. We have a page with articles with a certain tag (let's call it theTag) which has an address like the-site.com/taxonomy/term/41. Now, since other users are not advanced ones (and for general convenience) I'd like to create a button which:

adds an article (opens the the-site.com/node/add/article or the corresponding overlay) with pre-set theTag
also I'd like the "is shown on the main page" flag (not sure about the exact name, it's "Помещено на главную страницу" in Russian) unset, so that the article is show only on the the-site.com/taxonomy/term/41 page, not on the main one
the button should obviously be shown only to those who can edit

How to implement that? It sounds like a common feature, but googling didn't help. Since I'm totally new to Drupal internals, I'd appreciate any partial suggestions if you think I'm asking for too much.

PS may be there's some params that I can use in the the-site.com/node/add/article url (like, say, the-site.com/node/add/article?tag=theTag) so that the corresponding tag is pre-set in the new article form?

Sounds like the Prepopulate module does exactly what you want.

EDIT:
From the module's page:

The Prepopulate module allows fields in most forms to be pre-populated from the $_REQUEST variable.

For example, the following URL,

http://www.example.com/node/add/blog?edit[title]=this is the title

will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.


Change font color in unsorted list in Views Drupal I'm using Drupal with Views, which outputs an unformatted list of news titles (accompanied with dates). Example output of my View:

Some of the news titles need to change font color or size. For example, if the chosen taxonomy term is "hot" then the font size of title should be 8px.

I think I need a CSS class to be inserted for tagged news, but I can't figure out how to do this.

Views supports tokens to generate CSS classes in the HTML output of a field. Below a screenshot depicting an example where I have added the fields 'Tags' and 'Title' from the default Article content type. In this way, the chosen taxonomy terms are added as CSS classes and you can apply the appropriate styling using CSS.

In order to see the list of available tokens in your View, checkout the section 'Rewrite results' -> 'Rewrite the output of this field' -> 'Replacement patterns' in the configuration screen of the field (you don't need to actually rewrite the output, however, this is the location where you can find the list of supported tokens for the particular field).


Sort taxonomy terms alphabetically by default I created a taxonomy vocabulary and added some taxonomy terms to it. How can i sort alphabetically the listing of terms in taxonomy vocabulary page. The same sorting needs to reflect in content type fields when this vocabulary is added as term reference.

I hijacked the code from /modules/taxonomy/taxonomy.admin.inc that runs when you click "Reset to alphabetical". I tweaked it a bit and you can place this code in a custom module and it will run every time you insert a taxonomy term.

/**
 * Implements hook_taxonomy_term_insert()
 */
function YOURMODULE_taxonomy_term_insert($term) {

  $vocabulary = taxonomy_vocabulary_load($term->vid);
  $tree = taxonomy_get_tree($vocabulary->vid);

  if($vocabulary->machine_name = 'MACHINE_NAME_YOU_WANT_TO_FORCE_ORDERING') {
    //Make sure the taxonomy doesn't have terms with two parents
    if ($vocabulary->hierarchy < 2 && count($tree) > 1) {
      $params = array(
        'values' => array(
          'vid' => $term->vid,
          'name' => $vocabulary->name,
          'machine_name' => $vocabulary->machine_name,
        ),
      );

      taxonomy_vocabulary_confirm_reset_alphabetical_submit(NULL, $params);
    }
  }
}

If you want it to apply to all vocabularies, you can remove the IF statement on line 7. Good luck!


Approach of building a website for local basketball league? I am asked to build a local basketball league website.

Functionality is quite simple:

League news/articles
Different team page with team news, player info, gallery
Each player has profile. such as name, height, position, photo.

Module OG seems to be a good match in this case, but I am wondering if it can be done without OG.

Are there any other easier approaches?

Thanks for any suggestions!

I see you tag this as Drupal 7.  You don't need OG unless you want to have groups where members of the group can chat with one another.

Content Types:  League, team, news/articles (maybe Players)
Modules:  Image field, Viewes.

News & Articles are self explanatory.
Create node reference fields for Teams & Players
Teams would node reference league,  players would node reference a team.
You may only have 1 league or multiple.
Add fields to players (name, height, position, photo)
May want to use image style to set defaults size for photos
Depending on your use, Players can be users or a content type
Then you will use views to display everything the way you want, such as, team gallery, teams in league, etc.

Also you may want to embed a view into a node.   Use embed_views module


Check Billing and shipping info to be the same using Drupal commerce module? I'm using the drupal commerce module and I also installed the commmerce shipping module. Now in my cart I have the form to enter the Billing and Shipping information. So far so good, but I'd like to have the checkbox option to check something like: "Use the billing information for the shipping information". Then when checked I should be able to submit the form and the validation will skip the shipping information form.

Do I need to installed other modules to do this?

No.

I recently added this feature to the commerce shopping module (both 1.x and 2.x branch). It hasn't been widely tested yet though, but I am using it for a production site and haven't seen any problems.

It's available for the 1.0 version or the 2.x-dev version.

This feature has been moved to Drupal Commerce in the 1.4 release (at the time of writing yet to be released), which means right now it's in Drupal commerce dev release and not in the 2.x-dev release.

The setting can be found under:
/admin/commerce/config/checkout/form/pane/customer_profile_billing


How to display the rendered entity of entities flagged with a Search API view? I created an index view "Search API".

I added the flags to the index.

How to display the rendered entity of entities flagged with a Search API view?

Currently only the title is displayed, I want to display the display mode "Teaser".

Have you tried to change the configuration of the Format section ?

Instead of "Fields" you might be able to select "Rendered entity" and then under Settings link, you will be able to choose a view mode like "Teaser".


How do I get the UID in user-profile.tpl.php? I'm trying to make a custom view mode for user profiles. In my user-profile--myviewmode.tpl.php, I want to get the UID for the user whose profile it is.

The help text for user-profile.tpl.php states:

  $user_profile: An array of profile items. Use render() to print them.
  Field variables: for each field instance attached to the user a
  corresponding variable is defined; e.g., $account->field_example has a
  variable $field_example defined. When needing to access a field's raw
  values, developers/themers are strongly encouraged to use these
  variables. Otherwise they will have to explicitly specify the desired
  field language, e.g. $account->field_example['en'], thus overriding
  any language negotiation rule that was previously applied.

I used dpm() to print out the array $user_profile, but I couldn't find the UID anywhere.

Then I tried:

global $user;
$uid = $user->uid;

However, this doesn't work because when I use Views to render the view mode, it gives me the UID of the logged-in user, not the user whose profile is being rendered.

Is there a way to get the UID in user-profile.tpl.php?  I need to get the UID to build some custom links based on it.

I found the uid under the elements >> #account object:

$elements['#account']->uid;

Good luck!


How to hide an empty view block when using a contextual filter and NO file fields? I'm trying to figure out how to hide a view block when it has no rows. Though this questions is similar, it's not the same. In my situation I am also using a contextual filter but have no file fields so the answer in that question doesn't apply.

I've tried global: null as a second contextual filter but still the block shows with just the title.

Can anyone help me solve this issue.

Many thanks for any help.

Add  another filter it's not important which field , as example if you have Content:title ( or any field you have in fields row) and  set filter is it's not empty.

The mechanism is simple, contextual filter cause view not consider as empty even thought there is no any row, and when you add a filter on a field that not exists it cause view considered as empty. So only add one of your view field to  filter and  check if it is not empty


Is it possible to disable taxonomy hierarchy? The site I am building uses fields (plus a custom module) to provide a richer set of relationships between taxonomy terms than the built-in hierarchy allows.

I want to remove/disable the built-in hierarchy. What I mean is that when a user is creating or editing a term, I do not want them to see the "Relations" section, and when they are viewing a list of terms in a taxonomy, I want the drag-and-drop functionality to only work for ordering, not indenting.

I know I can do this with another module using hook_form_alter() or the like, but is there an easier and quicker way to "turn off" this functionality in Drupal 8? I have a vague memory of (maybe in an earlier Drupal, or somewhere else) being able to specify, when you create a taxonomy, if you want it to be hierarchical or not, but I cannot find such a thing here.

If the Relation input is not exposed in the Form Display, then you are going to need to use a hook_form_alter to hide the Relation input.

Also, note, that the drag and reorganize on the vocabulary overview will still support hierarchy. You'll need to alter that form as well to disable it.


How to add  in drupal? I'm using underscorejs function _.template() to render html on client side. I found that in many examples, the templates are placed in some

I try build a block to hold these tags, but drupal will break it, lost some tags eventually.

My solution right now drives me crazy: save the template as one line string or concat multiline strings with \ in js.

I really need a better idea. Thanks.

UPDATE:
I found a better idea, using coffee script raw string. From External template in Underscore

You really shouldn't be putting things like that in a drupal block via the UI anyway because someone with permissions could come along and mess it up and then everything breaks.

You can add/remove/change markup on the page by editing the templates in your theme.

For example you could add your template script tag into the page.tpl.php file of your theme.

Assuming you are using the same template on all pages (or a bunch of pages) or you just want a template on a specific page then this is really straight forward.

If you have more complex requirements you might need a large amount of template overrides or you may want to use some code in template preprocess functions in template.php to make things simpler.

For more information on this see Theming Drupal 6 and 7. There is a lot of info in there.


Hide Drupal Web Form until Logged in? I am running a competition whereby users must fill in a webform to enter. However, I am also using Facebook connect, and want the web form page to display, with the body and all the rest except for the form itself, unless the user is logged in. What is the best way to:

Allow access to the webform if anonymous?
Not allow the user to submit the form if anonymous?
Hide the form and show my custom Facebook login button if the user is not logged in?

Point 1 is basically using Webforms the default way. And point 3 I can probably do by just editing the template of the node. But I am not sure how I can override the validation of the form to stop the user from actually entering the competition if he is not logged in.

Any ideas on what the best way is to do this?

I haven't done this, but it should work to do something like this: Once you've created the webform, on the settings for your webform, under "Submission access" you can choose to restrict "Roles that can submit this webform" to "authenticated user" and under "Advanced Settings" there's a checkbox to make the webform "Available as a block." Once you have the webform block, restrict the block to authenticated users only. Put the content that should be available to anonymous users on a new page and add your webform block to that page. The webform should then only show up on that page for authenticated users.


Views, taxonomy and content type I have a content page called Book, to which I also added an image field and a "term reference" to a Book taxonomy which has Book A, Book B, Book C, Book D, Book E as available terms in it.

I created 5 'Book' pages, inserted images and selected taxonomy terms (each taxonomy value are different).

I have another content page called List Book, to which I added a "term reference" to a Book taxonomy as well.

When I create a 'List book' page, I have to select a term from the Book taxonomy. If I select the terms 'Book A' and 'Book C', two images (related to Book A and Book C) will display.

Lastly I created a view with as a field the image field. As the filter, I added:

'publish = yes'.
'content type = Book' and 'List Book'.
taxonomy field from 'List Book'.

Field:
image from Book

There is no result.

What is the correct way?

What I'm getting here from your question is, you want to search on the basis of category.
I think, you can use exposed filter in the views to get your desired result.

You can find exposed filer in views Under "Filter Criteria".

Hope it will help you.


Custom field type not found I'm writing my first custom field type. The field will contain a rating field for authors. Now when I create the class for the field and activate my module nothing has been found. No errors can be found in the log and the field is not be inserted into the field list of the content type.

I used the "Drupal 8 Development Cookbook" for more information about Drupal 8, but when I check my source with the example from the book I can't find any changes (except from my custom rating).

My class that contains the custom field was placed in the src/Plugin/Field/FieldType/Rating.php file and looks like:

<?php

/**
 * @file
 * Contains \Drupal\RateField\Plugin\Field\FieldType\Rating.
 */

namespace Drupal\RateField\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'Rating' field type.
 *
 * @FieldType(
 *   id = "rating",
 *   label = @Translation("Rating field"),
 *   description = @Translation("This field stores a rating of the object."),
 *   category = @Translation("General"),
 *   default_widget = "string_textfield",
 *   default_formatter = "string"
 * )
 */
class Rating extends FieldItemBase {
  /**
   * {@inheritdoc}
   */
  public static function schema(\Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition) {
    return array(
      'columns' => array(
        'rating' => array(
          'description' => 'Rating',
          'type' => 'int',
          'length' => '255',
          'not null' => TRUE,
          'default' => '0',
        ),
      ),
      'indexes' => array(
        'rating' => array('rating'),
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['rating'] = \Drupal\Core\TypedData\DataDefinition::create('range')
      ->setLabel(t('rating'));

    return $properties;
  }

}

Can someone help me with this?

This is most probably a namespace issue, I think you have to replace

namespace Drupal\RateField\Plugin\Field\FieldType;

with

namespace Drupal\rate_field\Plugin\Field\FieldType;

or whatever your name's folder is called.

Good luck!


Trying to enable clean URLs: The clean URL test failed I am trying to follow this document to enable clean urls on a fresh Drupal installation. When I run the test, I get:

The clean URL test failed.

My host provider confirms that mod_rewrite is enabled. I am using a shared server.

In my Drupal installation folder, I see a hidden .htaccess.txt file. Apparently, it has been installed by Drupal itself.

But, I cannot find information in the document mentioned above explaining to solve this issue. What is missing to make Clean URLs work? Thanks.

The file name should just be .htaccess, without the .txt extension.


CSS not being loaded from CDN (CloudFiles) I've got CDN installed and configured and I've copied all of my css up to the CDN.

The CSS urls change from this (using my hosts IP address):

@import url("http://xxx.xxx.xxx.xxx/modules/system/system.base.css?mhdfaw");

When I enable the CDN module, they look like this:

@import url("http://b24fb3007bd5cf6f616a-a6cd251ed0dfba89acb0fcd5fb378f4a.r38.cf1.rackcdn.com/modules/system/system.base.css?mhdfaw");

When I copy that url and paste it into my browser, the file exists and is being served by the CDN just fine. I have tested EVERY css file in the source and every single one of them exists, but my page is completely unstyled. None of the CSS files are being applied at all.

I'm not referring to the images in the stylesheets, I'm referring to ALL of the styles.

What the heck?

EDIT: Here is a link to my site, in case that helps:

http://108.166.112.120/blog

The files had the wrong mime-type.

I wrote a php script using Rackspace's Cloud Files PHP api to upload all of my files to the Cloud Files container. All of the files had the default mime type/content type of "text/plain". I changed the content types of the css files to "text/css" and it all started working.


How to rebuild form after AJAX call I'm attempting to allow the user to dynamically choose a number of fields based on a dropdown box using an ajax call, but I can't seem to get the ajax call to rebuild the form afterwards.

<?php
class AJAXexample extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        if (empty($form_state->getValue('number'))) {
            $form_state->setValue('number', 3);
        }
        $form['columnNum'] = [
            '#title'   => t('Number of Columns'),
            '#type'    => 'select',
            '#options' => [
                1         => '1',
                2         => '2',
                3         => '3',
                4         => '4',
            ],
            '#default_value' => $this->configuration['columnNum'],
            '#empty_option'  => t('-select-'),
            '#ajax'          => [
                'callback'      => [$this, 'columnCallback'],
            ],
        ];
        for ($i = 0; $i < $form_state->getValue('number'); $i += 1) {
            $form['column'][$i] = [
                $i => [
                    '#type'       => 'details',
                    '#title'      => t('Column '.$numTitle),
                    '#open'       => FALSE,
                    'columnTitle' => [
                        '#type'      => 'textfield',
                        '#title'     => t('Column Title'),
                        '#value'     => $config[0]['columnTitle'],
                    ],
                ],
            ];
        return $form;
    }

    public function columnCallback(array &$form, FormStateInterface $form_state) {
        $form_state->setValue('number', 10);
        $form_state->setRebuild(true);
        return $form;
    }
}

The number of textfields is based on the form_state variable 'number'. The callback columnCallback changes the form_state variable to 10, and is fired when the 'columnNum' form field is changed. However the form isn't rebuilt with the new number of fields even though $form_state->setRebuild(); is called. Is there a way to get the form to rebuild after an ajax call?

NOTE: I have already tried techniques such as replacing or appending the items of the form inside of the actual ajax call but when that happens none of the input into the replaced fields get passed to $form_state.

UPDATE:
After attempting 4k4's solution I receive an error

Recoverable fatal error: Argument 1 passed to Drupal\Core\Render\MainContent\AjaxRenderer::renderResponse() must be of the type array, null given, called in /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php on line 89 and defined in Drupal\Core\Render\MainContent\AjaxRenderer->renderResponse() (line 45 of /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php).

The belief is that the error occurs because $form['column'] is returning null despite being created as a container in the blockForm function. I've attempted calling the callback in other ways like

'#ajax' => [
    'callback' => '::columnCallback',
]

and

'#ajax' => [
    'callback' => [$this, '\Drupal\my_examples\Plugin\Block\AJAXexample::columnCallback'],
]

But I receive the same error. Curiously, when I change the callback to return the entire $form instead of just $form['column'] it repeats the form (a copy of the form appears below the current form) and still without the proper number of columns.

First problem is to handle the value for the column number. On the first build get it from configuration, on a rebuild get it from the user input and put it in $columnNum.

The second is to decide, what part of the form changes in AJAX and put this in a div container with the id columns-wrapper.

class AJAXexample extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        $columnNum = empty($form_state->getValue('columnNum')) ? $this->configuration['columnNum'] : $form_state->getValue('columnNum');
        $form['columnNum'] = [
            '#title'   => t('Number of Columns'),
            '#type'    => 'select',
            '#options' => [
                1         => '1',
                2         => '2',
                3         => '3',
                4         => '4',
            ],
            '#default_value' => $this->configuration['columnNum'],
            '#empty_option'  => t('-select-'),
            '#ajax'          => [
                'callback'      => [$this, 'columnCallback'],
                'wrapper'       => 'columns-wrapper',
            ],
        ];
        $form['column'] = [
            '#type' => 'container',
            '#attributes' => ['id' => 'columns-wrapper'],
        ];
        for ($i = 0; $i < $columnNum; $i += 1) {
            $form['column'][$i] = [
                $i => [
                    '#type'       => 'details',
                    '#title'      => t('Column '.$numTitle),
                    '#open'       => FALSE,
                    'columnTitle' => [
                        '#type'      => 'textfield',
                        '#title'     => t('Column Title'),
                        '#value'     => $config[0]['columnTitle'],
                    ],
                ],
            ];
        return $form;
    }

In the callback we only need to return the ajax wrapper.

public function columnCallback(array&$form, FormStateInterface $form_state) {
    return $form['column'];
}

Drupal rebuilds the form on every ajax request and puts it in the parameter $form of the callback. It would make no sense to try to rebuild it again.


How can I field-rewrite a URL? I need the modified URL to call a view with contextual filter, in Drupal 8.
The URL must include the value of a field, that the user's clicking on.

This works.

Link to Testview

How can I overwrite Link to Testview with the field value?

{{field_example__value}} works as well.

I've seen it often that the path is simply built by concatenating strings. But if you want to do it in a D8 way, then use the route from the view.

You can investigate the routes with Drupal Console on the command line or the Devel module in UI, where you'll find the routes in /devel/routes.

For example this view:

ROUTE NAME: view.testview.page_1    PATH: /testview/{arg_0}/{arg_1}

When you know the route name and the arguments for the contextual filters you can build the URL:

use Drupal\Core\Url;

  $url = Url::fromRoute('view.testview.page_1', [
    'arg_0' => $arg1,
    'arg_1' => $arg2,
  ]);

The URL is an object, which you put in a render array, for example in a link element. If needed you can get the path as string with the method ->toString(), but this should be avoided.

If you want to use the route in a field rewrite you can use the twig function url() in a field replacement pattern:

Link to Testview


Add file field with Form API I'm writing a block plugin that uses the form API to allow users to edit its settings, and then output them into a template.

I'm currently using

<?php

/**
 * @file
 * Contains \Drupal\my_plugins\Plugin\Block\InfoWithSideImage.
 */

namespace Drupal\my_plugins\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @Block(
 * id = "infowithsideimage",
 * admin_label = @Translation("Info block beside an image")
 * )
 */

class InfoWithSideImage extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        $form['image'] = array(
            '#type'          => 'file',
            '#title'         => $this->t('Image'),
            '#default_value' => $this->configuration['image_submit'],
        );
        $form['test'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Test text field'),
            '#default_value' => $this->configuration['test_submit'],
        );
        return $form;
    }
    public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['image_submit'] = $form_state->getValue('image');
        $this->configuration['test_submit'] = $form_state->getValue('test');
    }

    public function build() {
        return array(
            '#theme' => 'infowithsideimage',
            '#image' => $this->configuration['image_submit'],
            '#test' => $this->configuration['test_submit'],
        );
    }
}

The text field works fine, but whenever I try to submit with the file field I get the following error:

  A fatal error occurred: Serialization of Symfony\Component\HttpFoundation\File\UploadedFile is not allowed

Is there something I'm missing? Is it possible to use the form API to allow users to upload files?

I discovered that the error only occurred when using the in-place panel editor. When adding the block in the panel page editor there were no errors.


How can an author mark the update date of a node to be visible or hidden for visitors? I want to let the author to specify whether node update date should be visible to visitors or not, per node (not node types) with a checkbox at node insert/edit form?

Update:
I know how to use fields but I considered using something other than a new field. Something like variables.

Because I just want to save a simple Boolean value and I think fields will push an unreasonable overhead to Drupal for such a simple task.

You could add new field as a checkbox author check if he needs the update date visible to visitors.

Use panels and page manager to build a custom page view for that node type

Add visibility rule to display the update date if the checkbox field is checked


How to locally export config from a remote environment? If I have config that's out of sync on production, I may want to export it without copying down the database, or I may have environment-specific config that interferes with exporting config from the local environment. Is there a way to export config from a remote environment locally?

Edit: Turns out drush has a config-pull command to handle exactly this:

https://drushcommands.com/drush-8x/config/config-pull/

However, it doesn't work with config_ignore as far as I can tell.

The original answer for posterity:

I've found that this bash command does the trick (on Mac OS X):

yes n | drush @site.env cim sync --preview=diff | \
sed -E 's/([\-]{3} ).*(\/.*.yml)/\1a\/config\/sync\2/' | \
sed -E 's/([\+]{3} ).*(\/.*.yml)/\1b\/config\/sync\2/' > cim.patch && \
interdiff -q cim.patch /dev/null > cex.patch && \
git apply cex.patch && \
rm cex.patch cim.patch

We use the preview argument of drush config-import (passing in 'n' when it prompts to import), clean up path names with sed, reverse the patch from import to export, and finally apply it and clean up. Note that you have to be on the same git branch as production.

With drush 9, the output and yes functionality changes a little, so you can instead use:

drush @site.env cim sync --no --preview=diff 2>/dev/null | \
sed -E 's/([\-]{3} ).*(\/.*.yml)/\1a\/config\/sync\2/' | \
sed -E 's/([\+]{3} ).*(\/.*.yml)/\1b\/config\/sync\2/' > cim.patch && \
interdiff -q cim.patch /dev/null > cex.patch && \
git apply cex.patch && \
rm cex.patch cim.patch


Pass variable to field template from theme_preprocess_field() I'm stuck trying to pass variables from my theme_preprocess_field function to my template file. I want to have a variable for each of the fields I am printing out to my template.

I'm using the Paragraphs module in Drupal 7, so that might be throwing me off, but I feel like I'm really close. Here's a simple example:

Preprocess function in my template.php:

function merge_preprocess_field(&$variables) {
    $element = $variables['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_title') {
      $variables['test_title'] = $variables['items'][0]['#markup'];
    }
  }
}

The name of the template I am using is paragraphs-item--full-text.tpl.php.

field_title is the name of a field inside a paragraphs bundle called full-text.

Everything that I have read so far indicates that I should be able to access the $variables['test_title'] variable in my template this way:

<?php print render($test_title); ?>

It doesn't print, even after clearing the cache. It's even showing up in the array when I krumo($variables);. Am I missing something?

Ok, I figured this out. My preprocess function was for a field, but I was trying to access the variable in the wrong template. What I ended up doing was creating individual preprocess functions for each paragraphs-item, and preprocessing the variables in there.

First, I created a function that would allow me to create preprocess functions for entity types:

function merge_preprocess_entity(&$vars, $hook) {
  $function = 'merge_preprocess_' . $vars['entity_type'];
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

This allowed me to create a preprocess function for paragraphs items. Then I used this same idea to create preprocess functions for individual paragraphs items:

function merge_preprocess_paragraphs_item(&$vars, $hook) {
  $elements = $vars['elements'];

  $function = 'merge_preprocess_paragraphs_item__' . $elements['#bundle'];
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

Now I can set variables that are available in the paragraphs items templates, like so:

function merge_preprocess_paragraphs_item__smaller_full_width_text(&$vars, $hook) {

  if ($vars['content']['field_cta']) {

    $field_cta = !empty($vars['content']['field_cta'])? $vars['content']['field_cta'][0]['entity']['field_collection_item']: '';

    foreach ($field_cta as $field_cta) {

        // Make the CTA url available to the rest of the block
        $vars['content']['cta_url'] = $field_cta['field_link'][0]['#markup'];

        // Set character limit for CTA Text
        $vars['content']['cta_text'] = truncate_utf8($field_cta['field_link_text'][0]['#markup'], 24, TRUE, FALSE);

    }
  }
}


Dealing with absolute paths while on localhost I have a long-term path problem while developing modules.

For instance I have the following project path http://localhost:8888/mylocalproject, which (on the production server) would be http://www.project.com.

Now each time I use global $base_url or other absolute paths it only returns me the http://localhost:8888/ not http://localhost:8888/mylocalproject. For instance if I want to handcraft a logout link will give me http://localhost:8888/user/logout which is wrong, since mylocalproject is excluded.

I have all the time to hack solutions like this

global $base_url;
$needle = "localhost";
if (strpos($_SERVER['REQUEST_URI'], $needle)) {
  path = $base_url."/mylocalproject";
}
else {
  path = $base_url;
}

Is there a Drupal standard solution for that?

You should just set the $base_url in your settings file while you're working on localhost, then you can just change it when you put the site live.

The settings file is at "sites/default/settings.php" and you should add:

$base_url = 'http://localhost:8888/mylocalproject';

Obviously when the site goes live you want to change/remove that line to match your new environment.


How to create absolute url for a page/node? I think that I need to use the l() function as seen here: How do I get the absolute URL when using l()?

I just need a bit more clarification. What's the best way to create links on pages? I would like to link them correctly so that if my domain changes then the link will be updated (for example going from a local host to an online host). Let me also know if this is not the best way to do it.

I guess I need to know what would go into HTML tag  and then also do I need to place any code anywhere else?

You should use the l() and url() functions as specified in the answer to the question you link to. Those are core Drupal functions so nothing else is needed.


change default payment in ubercart I have two allowed payment methods, Paypal and Credit card. When a user checks out Pay Pal is selected by default and is shown on top. How do I change the order of these with the credit card option on div on top and make the radio button for credit card, the option selected by default?

Probably with hook_form_alter. Change the #weight attribute so credit card lighter than paypal. Set the #default value to credit cards for the radio values.

I haven't used these modules nor have an Ecommerce site live so I cant post example code ...

EDIT

install Devel and implement hook_form_alter for your module. put dpm($form);dpm($form_id); in your form atler implementation ... and goto the page with the form in question. You will then see the PHP array structure for the form on the screen.


Entity reference : show fields instead of Label Each user has a personal calendar (tab in profile from Views) where they can add "Event" content-type. I have a Entity reference field where the user can add 5 different "friends" to this "Event".

With Entity Reference view Widget I have a view (Picture and user name) from which the user can add up to 5 people. And it works, but...

How can I have more than just the Label? I would like to have the user picture and his name.

I've tried for 2 days... Please help. Maybe Entity Referennce is not the solution.

Thanks.

Might want to check the display settings (IE: Manage Display) of both the referencing and referenced entity.  Haven't used it in a while, but definitely worth a look.


Which hook to allow specific users to add/edit/view comments? Is there a hook that I can use that would give specific users permissions to add a comment, or edit their own comment?  I was hoping there would be something like hook_node_access().

In my form, I have a select list with all the users that the submitter can choose.  If the person is selected, then that selected person can comment on that specific node.

I looked at the comment access module, but that does not work since it is still being controlled by role permissions.

There is no hook to do this. One possibility that doesn't require editing of the comment module is to change the comment status of the node depending on the current user using hook_node_load:

function MyModule_node_load($nodes, $types) {
    global $user;
    foreach($nodes as $node) {
        if(!user_has_access_to_node($user, $node)) {
            $node->comment = COMMENT_NODE_HIDDEN;
        }
    }
}

The hook will be called after the one in comment module, and will prevent users from posting comments unless user_has_access_to_node returns true.

The implementation of user_has_access_to_node would simply check if the current user is in the list of users allowed to edit the viewed node.


Why can't I set radios default value (when after build is done) I'm putting a node add form on a custom page that is a menu local task tab for specific taxonomy terms, and trying to set default values for some of the elements.

I'm building the form like this:

function emtr_form($form, &$form_state) {

    module_load_include('inc', 'node', 'node.pages');
    $form = node_add('mtr');

    $form['field_shift'][LANGUAGE_NONE]['#default_value'] = 'early';
    // also tried this but it doesn't work either
    //$form[LANGUAGE_NONE]['early']['#default_value'] = true;

}

When I inspect the form array I can see:

#options (Array, 3 elements)
    early (String, 13 characters ) 23:00 - 07:00
    lunch (String, 13 characters ) 07:00 - 15:00
    late (String, 13 characters ) 15:00 - 23:00
#default_value (String, 5 characters ) early
#after_build_done (Boolean) TRUE

This shows my default value matches the options array key, however also shows that #after_build is done. I suspect that the default value gets set in the after build function, however if I set after build to false I seem to get caught in an endless loop and the browser crashes.

I tried adding my own custom after_build function to the form and setting the default values there, but because after_build has already been done it is never called.

How can I set default values when building a form like this? Or is there a better way to load the node add form?

EDIT: Here is a paste bin with the whole form item array

EDIT2: This is a radios field that is part of a field collection that is part of a node add form.

The assignment of the default value doesn't seem correct. I think it should be like this:

$form['field_shift'][LANGUAGE_NONE][0]['value']['#default_value'] = 'early';

See the following questions and their answers for more information:

Programmatically set the default value for a field
Why is hook_form_alter() so messy?


How do relationships work in Views? This is related to my previous question, How can I make a block that holds all the information about an articles author? I want to make a block that holds all the information about the user who authored the node. I started using Views to make the block, and found the field "Content: Uid" underneath which is described as:

  The user authoring the content. If you need more fields than the uid add the content: author relationship

I was wondering if this could help me to make this block as I've described.

If you add a relationship in the View definition (Third column of the view input form), and select the Content:author from the dialog, you have created a link in the view that exposes data regarding the author. This will give you access to more fields that can be displayed in your view.

Check out the video series, "Taming the Beast" at nodeone.se to get a better understanding of what Views can do.


Which module can hide or show text? I have a site with puzzle and I need to hide or show some answer. It can be some photo or some text. It can't be block, I need a module that will be able to hide or show fields as is it done in the photo modules When I add some photo in any article. How can I hide or show it?

There is a Quiz module, that looks awesome: https://www.drupal.org/project/quiz

The Quiz module lets you create graded assessments in Drupal. A Quiz
is given as a series of questions. Answers are then stored in the
database. Scores and results are displayed during or after the quiz.

A simpler option might be the Peekaboo module: https://www.drupal.org/project/peekaboo

Use cases: ... Fields that reveal more information
Peekaboo can also be used purely for the Ajax functionality as a gimmick to reveal more information.