Drupal 7 form missing from $form object during Ajax callback function

Just incase anybody wants to know the issue was I was trying to obtain a value from arg() and this was different for the ajax callback funtion. So in my hook_form function I set the following:

  // This is needed for the ajax callback
  if (arg(1) != 'ajax') {
    // We need to set the variable before we load the form.
    $form_state['value'] = arg(3);
    $key = arg(3);
  }
  else {
    // Ajax callback can now reference correct key.
    $key = $form_state['value'];
  }

This allowed me to obtain the correct value during the ajax callback function.


How to override items per page in cloned view?

You can do this with the Views UI.

Click on Display a specific number of items

Then at top in For select This block/page (override)

PS: When you add fields, contextual filters, etc... anything under/besides a BOLD/Bold section, you need to do this there too, as each section has its own For setting.


Domain Access and One.com hosting (funny subdomain rewrite)

It turned out that my symlink from /event/ to / was correct, but that I additionally needed to specify RewriteBase / to fix the link rewriting part.


Could you use "tabledrag", the code draggableviews uses to do dragging? It is basically javascript acting on an html table, with a weights column to remember the order.

Have a look at how the block module uses it (but bear in mind block is more complex because it has multiple regions to manage).

For tabledrag to work you need your questions in the form of a html table, which you then extend using the render array "#type" = "tabledrag". It is possible to configure tabledrag in Javascript, too.


how to display filed values form People » Account settings » Manage fields

If you want to display first name and last name of the logged in user, then you can follow the below code snippets.

global $user;

$account = user_load($user->uid);

print "First name:" . $account->field_f_name[LANGUAGE_NONE][0]['value'];
print "Last name:" . $account->field_l_name[LANGUAGE_NONE][0]['value'];

The global $user object does not load the fields which are attached to user profile. So, We need to use function user_load() in code.

If you want to display First Name and Last Name of the user profile, then you need get uid of the user from the arguments.

$uid = arg(1);

$account = user_load($uid)


Is there for modules the same as theme_get_setting() for themes?

You're probably looking for drupal_parse_info_file()

Parses Drupal module and theme .info files.
Info files are NOT for placing arbitrary theme and module-specific settings. Use variable_get() and variable_set() for that.

Pay attention to the second paragraph - it applies to you :)


You can use Path Redirect module. Module page says -

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.

As I see you are talking about taxonomy terms, so alternatively you can use Taxonomy Redirect.

  This module allows the administrator to change the destination of
  Taxonomy Term links.

  The module can now handle redirections at the term level.
  You can specify a replacement character for spaces and + characters.
  You can specify a list of characters or strings to remove from the path
  You can enter php code that will create your path at runtime (In 5.x-1.3, variables for term ID ($tid) and term name ($tname) are available to use in your php code).


Drupal 7 dynamic dropdown list options An illegal choice has been detected

The value you are submitting was not present during the page or form loading time.

If you populate some values using ajax which was not present in initial page loads and try to submit the form, then Drupal will not allow you to submit the form. It will always shows "An illegal choice has been detected" message.


How do I create a View of different entity types?

Views uses a term it calls base table translated into SQL it is the table used for the initial query

SELECT something FROM {base_table};

The thing is that what you want to do is a bit atypical, instead of doing

SELECT something, field_item FROM {entity} LEFT JOIN {field};

You want to do

SELECT something, field_item FROM {field} LEFT JOIN {entity};

In order to do this you need to use the field you are after as the base table. By default this is not possible, but it's not much work required in order to do it. What you need to do, is to use hook_views_data or hook_views_data_alter and add the data for the field table and make it selectable as base table displayed when you create a view.

There's a lot of doc on how to do this (the Views doc), and I have written this in one or more answers here. So I won't bother explaining how to do this.


Dev version connects to the live site database despite settings.php

You did not edit your sites.php file or name the new site directory in such a way that Drupal can discover it.


How can I increase memory_limit for batch processes only?

I think that @kantu's answer is the proper thing to do, but I am going to offer up an alternate solution that is a little hackish.

If you don't want to do a module, then you could add the setting to settings.php wrapped in a conditional.  Just note that this is included really early in the bootstrap process, so you don't have access to the vast majority of the API.

You could try adding

if (strpos($_SERVER["REQUEST_URI"], "/batch") === 0) {
  ini_set('memory_limit', '200M');
}

to the file.

I would also double check the PHP doc about memory_limit (or post a question on one of the sister sites).  I believe that PHP doesn't allocate this during startup; it is just a safety limit to prevent imploding your server.  I am pretty sure you can just bump up this limit globally.

If you are worried about Apache hanging on to this memory, then you can play with the MaxMemFree setting for Apache.  A while ago, I did a site that would need huge amounts of memory very infrequently.  Tweaking this parameter, along with a MaxRequestsPerChild, kept my server running happily.


DAMP / Aquia Dev (mac) apache fails on import of drupal core 7

This turned out to be a bug in Dev Desktop.  The good folks at Acquia fixed the bug and posted a new version that works nicely.


How to debug a configuration object, when testing?

You can use Config::get(), for which:

  If no key is specified, then the entire data array is returned.

e.g.

debug(\Drupal::config('mymodule.settings')->get());


Create a template file in your theme.

block--locale.tpl.php


Drupal 7 website layout/styling breaks all a sudden (random), how to debug? there are no logs

Above all, I assume that you have Google Analytics Installed. Go to the Behaviours menu and from there look at Site Speed and Page Timings to see how much times it takes to load a page. Use the Speed Suggestion option to allow Google suggest you a number of fixes/tricks that can potentially improve the performance of your web page. This is very handy.

This is clearly a problem of CSS. Open your site in chrome, enable the development tool F12 and then keep refreshing and monitor Network and Console windows. I observed that every reload of the page causes a request to a CSS to break (hence the resource is never downloaded - each time a different CSS from a different module).

It would be a great idea if you could give this module a go https://www.drupal.org/project/advagg, I highly recommend that you aggregate all your site's CSS into few or single CSS file.

It is always better to download one slighty larger file than make over a hundred calls to a web server requesting for tiny tiny CSS files, because there is high chance that your request fail or die (to to waiting).

I will update my answer with more findings but, give that module and a go and let us know your findings.


Can't import from XML using Feeds importer and XPath parser

Solved this on my own, the problem was that in context I had to write //book, instead of book. Stupid mistake which caused me headache for 2 days. I hope this will be helpful for people who will face the same problem.


You can change how dates from date fields are displayed by changing it on the Manage display (/admin/structure/types/manage/[my_CT]/display) page for that Content type.

Custom date format for individual field

The quick and dirty way of doing it is by choosing Custom for Formatter and entering the code for the date, for example:

Y-m-d\TH:i:s, l

will give you "2019-09-09T17:30:19, Monday".

You can lookup the various date and time codes in the PHP manual:  https://www.php.net/manual/en/function.date.php

Overriding individual fields displays with custom date formats isn't the best way to go because you can't reuse it throughout the site, for other fields, or translate into other languages (different countries have different conventions about how to write dates).

Reusable Custom date format

The best way is to first add the new Date format to your site. This way you will be able to use anywhere where you can format Date output.

Go to Configuration > Regional and language > Date and time formats and Add a new format.

Name it so it makes sense to your case, enter the PHP date code you want into the Format string, select Language and add the format.

Now visit your Content type's Manage display page and change the Formatter of the Date field you want to affect to Default, and the Date format to the one you have just created.


Generate new bearer token with simple_oauth programmatically?

POST request to /oauth/token generates a new token (don't forget to add proper body params)

You can also use a refresh token to generate a new access token by using grant_type 'refresh_token'


Placing content in different regions using a controller

The normal way to do this is to provide the main content in a controller and the additional content in block plugins.

If you don't want to use blocks and the block layout for this task (what you really should do!), and want to solve this in code, you can use a preprocess hook to add content your module provides in a function (procedural or static, not a controller) to a region.


Using the Migrate Source CSV plugin to migrate images

You'll need to run a migration of all the files you want first. The file_copy process plugin is going to be your best friend for this part.
To get you started,

id: image_migration
destination:
  plugin: 'entity:file'
process:
  uri:
    plugin: file_copy
    source:
      - file_source_uri
      - file_destination_uri

Once you have your files migrated, it's actually very easy to tell your image field about the file

process:
  field_image:
    plugin: migration
    migration: image_migration
    source: image_id

A couple notes:

image_migration refers to the migration that imports your images. Make sure to change it if you use a different name.
image_id needs to be the key from the image migration. It will be mapped to the new file created during that import.

Very Useful Guide


How to make existing fields available to be created as instances on other content types etc.?

An 'existing field' in that context is one that already has an instance, it doesn't refer to the existence of the field type. Until an instance is created, it doesn't exist as such.

Your field will be available to add as a new field as usual; if you want it to appear under 'Add existing field' section, you'll need to create an instance of it first.


For any source or path of any thing in drupal site use src like this. It will work everywhere.

<?php $src = base_path() .'sites/files/logo.png'; ?>

This src use like

<img alt="logo" src=" <?php echo $src ; ?>">

Enable PHP filter module that come with core module.

and in Block Body Choose Text format as PHP CODE.

I assuming block is created using Block module(Block UI)


You should use the Twitter module.

  This module provides API integration with the Twitter microblogging service. Out of the box, it allows users to:

  Associate one or more Twitter accounts with their Drupal user account
  List tweets in different ways thanks to Views
  Post to their own Twitter account or a site-wide Twitter account whenever they create new content or based on Drupal Actions or Rules
  Log in to your Drupal site via Twitter
  Format twitter @usernames and #hashtags as links to Twitter.com


Why are there module files like [modulename].pages.inc?

It's just a convention used for separating logic out of the main .module file.

The [modulename].pages.inc file typically contains page callback functions (those defined in hook_menu()). Since these functions aren't used in every page request there's no point including them, so they're auto-included from the file property defined in hook_menu() when needed.

You'll probably come across [modulename].admin.inc too, which typically contains callback functions for admin pages.

[modulename].api.php is another convention that Drupal core uses (and subsequently a lot of contrib modules use) to show examples of the hooks they provide, and usually how to use them.

There are other [modulename].[group].inc files that can be auto-included when another module implements hook_hook_info():

  Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.


Template suggestion does not work for table in a custom block / Might there be a way around?

Since Drupal doesn't suggest certain template file names I had to create a custom module which adds the template name for my needs. I had to implement the hook_theme_suggestions_HOOK() for my table view and add an appropriate name to the suggestions array.
<?php

use Drupal\views\ViewExecutable;

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function custom_template_suggestions_theme_suggestions_views_view_table_alter(array &$suggestions, array $variables) {
  if (isset($variables['view']) && $variables['view'] instanceof ViewExecutable) {
    $id = $variables['view']->current_display;

    if (!in_array('views_view_table__' . $id, $suggestions)) {
      $suggestions[] = 'views_view_table__' . $id;
    }
  }
}


Creating comments and nodes with Services 3.x and JSON

The following JSON appears to be the minimum you need to post a comment:

{
  "nid":"1",
  "subject":"Comment Subject Text",
  "comment_body":{
    "und":[{
      "value":"Comment body text"
    }]
  }
}

Since there is no user, commenting on this "example.com/node/1" needs to be turned on and permissions for anonymous users to post comments need to be set.


Change in view hooks file name/location in core 8.3.x?

I was finally able to get the hooks working again by putting them in the my_module.module file. I thought I read about that when I was first implementing these hooks when the site was still in 8.2, but it worked in the views_exection.incfile and not .module then. I haven't been able to find any documentation on this change so far, so if anyone could shed some light on it, I'd appreciate it.


Lightbox2 Swipe Gestures Support Adds swipe gesture support for Lightbox2. This makes a lot of sense on mobile or responsive pages, because the "Next" an "Prev" Buttons are only visible on hover.

  Adds swipe gesture support to the well known Lightbox2 module for
  mobiles. Just swipe left or right on galleries to show the previous or
  next element!


How can I save all taxonomy terms automatically?

The best I know from your question is to use the Views Global Filter module.

Using this module you can save you taxonomy term into cookie and get any where in the page and can also redirect and filter the results.


Important part you left out is what kind of ajax, is it a form you are submitting or custom javascript which uses ajax to target a controller endpoint? As this is how we return the code of the block.

But the code you are looking for re-rendering a block is:

$id = '' // the number of the block_id
$block = \Drupal\block_content\Entity\BlockContent::load($id);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
return $render;


How to add UNION with pagination in drupal 7 query?

I got the solution. I added this whole query as in subquery like,

$query_club = db_select('club_members','cm');
$query_club->fields('cm',array('first_name','last_name'));
$query_club->group_by('cm.uid');

$query_network = db_select('network_members','nm');
$query_network->fields('nm',array('first_name','last_name'));
$query_network->group_by('nm.uid');

$query_club->union($query_network, 'UNION');

**$query_pagination = db_select($query_club,'club_network')->fields('club_network');
$query_pagination = $query_pagination->extend('PagerDefault')->extend('TableSort');
$query_pagination->limit(10)->orderByHeader($header);**

$result = $query_pagination->execute()->fetchAll();

And using custom form table $form['pager'] = array('#markup' => theme('pager'));
pagination working fine now


Is Entity Translation module compatible with Internationalization and can they be used to translate menus?

Yes, they are compatible.

Entity Translation deals with entity translations, and menus in Drupal 7 are not entities, there's no clash between Entity Translation and Internationalization modules.


it all depends on what functionality your entity provides. are you defining entity yourself or are you using some other module?

anyway simplest way is to create entity manually

$entity = entity_get_controller($entity_type)->create(array('bundle' => $bundle_type));//this could look this way ->create($bundle_type); depending on your constructor

$entity->your_field['und'] = $value;//assuming you don't use entity translation then language is und

entity_get_controller($entity_type)->save($entity);

in case your controller extends EntityAPIControllerExportable then you could use import/export  but if you importing from external source probably custom code would be easier


How do I use "drush make" modules with a local module code?

You can set up local domains and local git repositories or tarballs like so:

projects[my_module][type] = "module"
projects[my_module][download][type] = "file"
projects[my_module][download][url] = "http://localhost/my_module.tgz"
projects[my_module][subdir] = "contrib"

Then in your build script you could just recreate the tgz


You should be able to get the form id from the $form_state variable as $form_state['build_info']['form_id'] inside your submit handler.


Store value in file entity field using a form

I posted this on drupal.org (https://drupal.org/node/1820706) and got an answer that works. I have to replace
$image->field_caption[0]['value'] = $caption; with $image->field_caption[LANGUAGE_NONE][0]['value'] = $caption;


Store information from hook_form_alter to be used in later hook_user_update?

As far as I'm aware, all form element values entered by the user on the profile edit form are available in the hook_user_update()'s $edit argument. The only element that won't be there is the plain text password.

There is no "drupal way" to avoid this, as core handles this functionality and it's trying to stop you from accessing the plain text password.

REMOVING SUGGESTION PER @znerol. Will update later this evening


Change site logo for specific content type and page

Do not know weather this method fulfill the requirements but you can take a look. As Drupal 8 creates a block for logo. You can create separate block for each content type and depends on visibility condition you can show.


Path parts are passed to the menu callback function with a zero index as the first path part i.e.

First url:
array(0 => 'test', 1 => '%id')

Second url:
array(0 => 'test', 1 => 'new', 2 => '%new_id')

Your form function expects two arguments but you only ever give it one.

In your form function arguments, this: $id = NULL, $new_id = NULL corresponds to this array('my_module_form', first_argument, second_argument) in your menu callback args. So you are only ever giving your form function one argument from the menu.
Try this in your second menu item:

'page arguments' => array('my_module_form', 1, 2),

This will provide two arguments for the form callback function. Your first menu item will return null for $new_id, because you don't have further path parts to provide from the url.


How to disable cache on view with ID as contextual filter

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

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

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


How to get select option id value in form api

You can get the value using:

$form['field_name'][#options][$form_state['values']['field_name']]


Is there a module/Drush command for updating multiple field settings at once?

I don't think there's a module or anything to do this, as it's quite a specific use case.

However, you could try something like the following in either a custom module's update/install hook.

Note I've not tested this, but you'll have to tweak it for your use case anyway.

$options = array(
  'entity_type' => 'node'
);
// Get all field instances that are on nodes
$fields = field_read_instances($options)

// Loop through the fields...
foreach ($fields as $field => $data) {
  // ...and prune the array to remove any non-required fields
  if ($data['required'] == 0) {
    unset($fields[$field]);
  }
  // $fields now only contains data for required fields attached to nodes
}

// Loop through the remaining fields
foreach ($fields as $field) {
  $instance = array(
    // Provide the default information that field_update_instance requires
    'entity_type' => $field['entity_type'],
    'bundle' => $field['bundle'],
    'field_name' => $field['field_name'],
    // Make your required changes
    'required' => 0
  );

  // Take the data in the $instance array and pass it through to field_update_instance.
  field_update_instance($instance);
}

You can filter down your selection of fields by passing different options through to field_read_instances() (e.g. if you only want fields attached to the Basic Page content type, the $options array would look like this:

$options = array(
  'entity_type' => 'node',
  'bundle' => 'page'
);

As a sidenote, field_update_instance clears the field cache at the end of every call, so if you have a lot of fields, then this might take a while .

Documentation:

field_read_instances();
field_update_instance();


Pardon my neanderthalic jQuery skills here, but if you add a CSS class to your view via the UI, let's all it clickable-row, you could then do something like this in a JavaScript file that basically looks through the HTML and, if it finds a link inside your views row, it makes the surrounding div clickable to that link. So, just as long as one field in your view is a link, you'd be all set.

$('.clickable-row .views-row').each( function() {
  if ($(this).find('a').length) {
    $(this).click(function() {
        window.location=$(this).find('a').attr('href');
        return false;
    });
  }
});


Is there an input filter to add the class clearfix to all  tags?

If you are trying to add the "clearfix" class to all of your paragraph tags, sitewide, it would probably be more simple to apply the "clearfix" properties to your "p" tag in your CSS files.

So you'd find:

.clearfix { ... }

and add in your paragraph tag like so:

.clearfix, p { ... }

Or copy the properties to your custom CSS file if you are worried about overwriting your changes.


Inserting tokens into a text field, such as body

I think you are looking for Advanced Text Formatter module which allows you to enable token replace on fields you choose. The mantainer says it would have a Drupal 8 version too.


Under Relationships, I choose "OG membership: OG membership from Node".

Then under Contextual Filters, I choose "OG membership: Group ID".

The last step is to select the Provide default value and choose "Type: Current OG group from context" under the WHEN THE FILTER VALUE IS NOT IN THE URL heading. Attached is a picture of what I mean.

Contextual Filter setup


Now I found the cause: The "pass" field in "users" table by some accident was set as 32 chars long, which is far less than required by phpass module (128 chars long).
I re-installed phpass to make the table change as required and fixed the problem.


Drush installed but all commands could not be found

Ended up uninstalling and re-installing drush and seems to have fixed my problem. Thanks.


How to render a form in custom template?

'render element' => 'form'

Your render element is form which means all provided variables will be passed there.

In your twig template you can render your form like here

<div>{{ form.form }}</div>

UPDATE #1

Wow man, you have wrong namespace Drupal\cmodule\Forms\RequestForm

Should be Drupal\cmodule\Form\RequestForm

Please rename Forms to Form (the same for directory) and clear cache. It should help you.


How to get a themed form via Ajax in D7?

I don't know that this counts as a duplicate, but the answer by "jeroen" on https://stackoverflow.com/questions/247991/displaying-a-drupal-view-without-a-page-template-around-it got me past this.  It's a greasy little hack (no offense, jeroen!), but it seems to work.


Views: pass link to referenced node to image field

You can select the entity I'd formatter and set the image link to 'node/'[your_token_here]
Use the views image field template (see the views theme information) to wrap it with the link


Select only if row not exists in joined table

You can use isNull() method :

$query = db_select('scald_atoms', 'a');
$query->fields('a', array('sid','title'));
$query->leftjoin('table_name','table_alias','table_alias.entity_id = a.sid');
$query->isNull('table_alias.mon_field_value');
$query->execute();
$query->fetchAllAssoc('nid');

with your example something like that should do it :

$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->leftjoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->isNull('m.milestone_id');


There are two possibilities: You can implement a hook in a module, or implement a theme function in the theme you are currently using.

Module

In Drupal 7, you can implement hook_menu_breadcrumb_alter(). The hook implementation receives the current breadcrumb array by reference, and the menu item for the currently visualized page. The example provided in the documentation page is the following one:

function hook_menu_breadcrumb_alter(&$active_trail, $item) {
  // Always display a link to the current page by duplicating the last link in
  // the active trail. This means that menu_get_active_breadcrumb() will remove
  // the last link (for the current page), but since it is added once more here,
  // it will appear.
  if (!drupal_is_front_page()) {
    $end = end($active_trail);
    if ($item['href'] == $end['href']) {
      $active_trail[] = $end;
    }
  }
}

An example of implementation of such hook could be the following one ("mymodule" needs to be replaced with the short name of the module that contains the hook):

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  if (substr($item['href'], 0, 4) == 'user') {
    // Add a trail item before the one linking to the user profile page.
  }
}

For a method that can be used on Drupal 6 too (when you want to develop code that is for both Drupal 6 and Drupal 7, and you don't want to write code for each Drupal version), you can use drupal_set_breadcrumb() to set the breadcrumb for the user profile pages.

An example of how the function can be called is the following Drupal function:

function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => format_username($node))), 'blog/' . $node->uid)));
  }
  return $node;
}

You could alter the menu callback for the menu items associated with the user profiles, and use a menu callback that first sets the breadcrumb, and then calls the original menu callback. The hook to implement in this case is hook_menu_alter().

Theme

As far as I recall, a theme can also implement some alter hooks as a module does; alternatively, a theme just overrides a theme function ("mytheme" needs to be replaced with the short name of the theme).

function mytheme_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];

    // Modify the breadcrumb.
}

The variable $breadcrumb is an array containing the HTML for the single parts of the breadcrumb.
The default implementation of the theme function is the following one:

function theme_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';

    $output .= '
' . implode(' » ', $breadcrumb) . '
';
    return $output;
  }
}

Between the two possible implementations, I would rather use a module, as it doesn't depend from the currently set theme; the theme can be changed, and the code would still change the breadcrumb. Generally, the code of a theme should alter the way elements are rendered, not to change the breadcrumb to alter the links it contains.


How do I use hook_update_N() to create a vocabulary?

You should be able to do it like this:

<?php

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * create vocabulary testname.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';
  $vocabulary = Vocabulary::load($vid);
  if (!isset($vocabulary)) {
    Vocabulary::create([
      'vid' => $vid,
      'description' => '',
      'name' => 'The vocabulary’s name',
    ])->save();
  }
}


How to get All options of a 'select' field?

You can also use list_allowed_values().

$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);


The security danger of publicly exposing an upload field

Drupal places an .htaccess file in the files directory to prevent files inside from being executed. Check the status report on your site to ensure that this is correctly configured.


How to manage translations when a site is being re-installed frequently?

The only way is to make a copy of the translation options.

I'm not sure if a hook_cron or a drush can donwload the files, if not the only way is to donwload and them copy into
../profiles/myprofile/translations/*.po


You need to enable pdf module and create a file field in the content type where you want pdf to be visible and there are two option to display PDF file in the field display setting, select which ever you require. (You need to use the latest pdf.js to use first page display).

Note: you need to download pdf.js manually and add in project directory

Hope you are following this,
http://drupalcode.org/project/pdf.git/blob_plain/refs/heads/7.x-1.x:/README.txt


I believe it is generated when it's needed, and not stored. But, after looking at the Commerce Order Weight Token module, you can get the weight using the following:

$weight = commerce_physical_order_weight($order);


Image upload functionality for drupal 7 content

Install the IMCE file browser module.  This will let you integrate direct file uploading while editing content, which of course includes images as well.  Follow the directions on the module's homepage for linking it with CKEditor.


menu_get_object() not returning node object when view's display is Entity Reference

The entityreference autocomplete paths are defined in entityreference_menu() as:

entityreference/autocomplete/single/%/%/%
entityreference/autocomplete/tags/%/%/%

The wildcard arguments are field name, entity type and bundle respectively. The entityreference_autocomplete_callback() function also accepts an optional entity id and string parameter (the last being the search string).

So while you're expecting the path to be node/[nid], it'll actually be one of the above - which explains why arg(1) is giving you the string autocomplete.

I haven't tried it but you should be able to use arg(6) to get the node ID in your current context.


You can use hook_preprocess_node to passe base_url to your twig like the following:

function mymodule_preprocess_node(&$variables) {
  global $base_url;
  $variables['base_url'] = $base_url;
}

in node--page.html.twig you will get the absolute url by:

{{ base_url ~ url }}


Running into deadlock when using XDebug with Drush

In PhpStorm at least, under File >> Settings >> PHP >> Debug you can find Max. simultaneous connections and crank it up. I typically keep it at 8 but probably 3 is enough.


How to include jquery from URL in custom module?

D7

For those who need to do this in D7, its as simple as

drupal_add_js('http://example.com/example.js', 'external');

D6

I can not take credit for this example but found this to be rather nice and easy way of dealing with external js files.

$external_js = 'http://www.example.com/a.js';
drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js . '\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');

Found this via http://www.wootenswebdesign.com/load-external-js-file-drupal-6


Which module creates the "Article" and "Basic page" content types?

@Wim Mostrey was right.

In Drupal 7, the default configuration for modules (e.g. content types, field configuration, views) required custom PHP code to install and keep updated. In Drupal 8, these are stored with the configuration system in plain text YAML files, for example core/profiles/standard/config/install/node.type.article.yml.

References

Include default configuration in your Drupal 8 module


How to create a custom home page template?

Yes : https://www.drupal.org/node/317461

  In Drupal 7, copy the page.tpl.php file and name it page--front.tpl.php.

Copy the file in your sites/all/themes/yourtheme/templates file (and then clear the caches of your site)


Cache problem in Drupal 6  when updating node

Assuming D6, You have to use the reset flag (third argument) in your node_load.


How can I automatically add a comment to a node with rules

If I'm going right with your requirement that you want an add comment link with every node in view result listing of nodes.

You should add a relation first to that node with comment by using node reference/entity reference by using referece from url widget type.
Your requirement is same like posting answers node on the specific question node.


How to apply or assign custom view mode to user display?

The question is too old, but for those who are still looking similar functionality. We can implement hook_entity_view_mode_alter in our custom module and change the rendered view mode dynamically. Check sample below:

/**
 * Implements hook_entity_view_mode_alter().
 */
function MODULE_NAME_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when in full display mode.
  // Add/Remove any condition based on requirement.
  if ($context['entity_type'] == 'node' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}


You can do this by implementing hook_entity_view_display_alter in a custom module.

Some code like this should work:

function HOOK_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context) {
  if (
    $context['entity_type'] == 'node' &&
    $context['bundle'] == 'CUSTOM_CONTENT_TYPE' &&
    (
      $context['view_mode'] == 'full' ||
      $context['view_mode'] == 'teaser'
    )
  ) {
    foreach ($display->getComponents() as $name => $options) {
      if ($name == 'text' && isset($options['label'])) {
        $node = \Drupal::routeMatch()->getParameter('node');
        $options['label'] = $node->FIELD_TERMS->entity->label();
        $display->setComponent($name, $options);
      }
    }
  }
}


How to add content title as dropdown list for exposed filter?

You have to implement a hook_form_alter with a custom module like this:

    function mytools_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'views_exposed_form') {
    //unset($form['average']);
    $form['average'] = array(
      '#type' => 'select',
      '#options' => array(0 => t('<any>'), 20 => '*', 40 => '**', 60 => '***', 80 => '****', 100 => '*****'),
      '#default_value' => 0,
      '#title' => t('The average vote is more than'),
    );
  }
}

Where the form_id is your current views form ID (you can see it with firebug in your code).


How to apply specfic coupon in ubercart while creating an order from backend means admin pages

1.) How to add coupon codes on add order admin page ? i need to add orders manually from backend but not able to apply coupon codes for
  discounts, there is only a feature to "add a line item" but not for
  coupon. I think there should be a textbox to fill coupon code and
  apply button to apply it.

If you want to apply a coupon code from the admin page. Use the uc_discounts_alt module that provides you three submodules(uc_discounts,codeless_discounts_field,product_price_alterer_field).
Enable the uc_discounts module it will provide you the textarea at the admin configuration page to apply the discount code.
1)Go to admin >> store >> orders >> create
2)Enter the customer information
3)It will open the create order screen as shown in the screenshot below

  2.) If coupon is applied to manually created order then tax calculation should be done after coupon price deducted from subtotal.

Yes.


Attaching Theme Library to Custom Module

Based on that structure, you're referencing the library incorrectly.
It should be $form['#attached']['library'][] = 'bootstrap_subtheme/bootstrap_subtheme.global-styling';
As noted in a comment below, the duplicate use of the theme name may not be necessary, and $form['#attached']['library'][] = 'bootstrap_subtheme/global-styling'; should work according to the docs. (Note the use of a dash, matching the library name versus an underscore in your code.)


Is there a Drupal rating module that lets you rate from 1 - 10?

The VotingAPI module (D6 and D7) offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

Create/Retrieve/Update/Delete operations for voting data.
Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
Via its integration with the Actions module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
It integrates with the Views module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

Rating related modules with a stable release for D7:

Rate (D6 and D7).
Fivestar (D6 and D7).
Voting API Bayesian (D7).
Star Rating (D7, no VotingAPI dependency).
Raty (D7-beta2).

Other rating related modules:

Plus 1 (D6 and D7-alfa2).
Vote Up/Down (D6 and D7-alfa1).
NodeReview (D6-beta1 and D7-dev).
Voting Rules (D6-beta2 and D7-alfa1).
Drupalit (D6).
Decisions (D6, unsupported).

Rating related modules with maintenance/development status 'unknown':

Extra Voting Forms.
UpDown.
Drigg.
Node Moderation.
SimpleVote.
MediumVote.
User Review.
Latest and Greatest.
jRating.
Loves and Hates.


Adding an extra class to the last element of the navigation/tree menu

You should be able to apply an additional loop to iterate by specific menu_level. Here is an example of a twig template that iterates over menu level variable:
How to add classes to menu items in navigation twig template

Then use a condition to set the class within the for loop such as:

loop.last ? 'last'

See all the variables associated with for loops in twig here:
https://twig.symfony.com/doc/2.x/tags/for.html


I believe that Contextual Filters are what you are looking for. The example should be pretty close to your use case from the sound of it.


Add HTML Chars To Breadcrumb Kickstart 2

There are different parts to this answer.

  since it doesn't use the core theme_breadcrumb() function.

By default, it does use theme('breadcrumb').
But you should have a look at the settings in admin/structure/crumbs/display.

But the check_plain() that causes special characters to be double-escaped happens in theme_crumbs_breadcrumb_link() and theme_crumbs_breadcrumb_current_page(), which you could also override.

You could also look at the $double_encode option in htmlspecialchars(), so you could use your own version of check_plain().

This being said:
Simply omitting the sanitization for all breadcrumb links is a bad idea, and potentially exposes your site to script injection. If anything coming from a non-trusted source ends up in the breadcrumb, or if people add broken html into a node title or menu link title or elsewhere, this could cause broken or malicious html on your site.

I think the better option is to just use the literal character in the node title, instead of the html entity.

Some general info:

With Crumbs, every breadcrumb item title is provided by a plugin. The plugins take these from menu links, from the title / title callback of the router item, or elsewhere. In most cases there is already an existing plugin which provides the breadcrumb item title you need.

Otherwise you can write your own plugins. I can give you a hint about that, but I need more information where you want the special char to show up. (I will edit the answer then)


ordering profile 2 module profile type tabs

Yes, by default profile2 module not cosidered any ordering of it's profile types.
if you want to change default ordering of them you have some  solution.
create a template file for user_profile .
Another way is ordering them with form alter
in your custom module

function hook_form_alter(&$form,$form_state) {
 if ($form_id == 'user_profile_form') {
     // do this for all your profile types
     $form['profile_yourprofiletype']['#weight'] = 'your optional order';
   }
 }


Go to  Content types » [your_content_type] » Manage display
and select FORMAT as Link label to the referenced entity for your referenced field.


How to change the format of Last seen: in author pane in advanced forum?

Here's what you need to use:

function YOUR_THEME_preprocess_author_pane(&$variables) {
  // Get the number of seconds since last login.
  $time_since_last_login = REQUEST_TIME - $variables['account']->access;
  // Custom override of the "last_active" variable.
  //
  // This is just an example; add your rules here.
  if ($time_since_last_login < 120 * 60) {
    // Show 2hr ago for any interval within last 2 hours.
    $variables['last_active'] = t('2 hours ago');
  }
  else {
    $variables['last_active'] = format_date('short', $variables['account']->access);
  }
}

Just add your custom time formatting rules.


After updating to 7.27, updates don't work and Status says cannot verify Drupal core

I found the issue. It was a javascript error with the "Colorbox" library. Apparently the colorbox library was two years old and became incompatible due to the switch from .live to .on. All issues were solved when I updated my colorbox library.


Here's a working and tested example:

/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(view &$view) {
  if ($view->name == 'my_view') {
    $query1 = &$view->build_info['query'];

    // Basic setup of the second query.
    $query2 = db_select('another_table', 'at')
      ->condition('some_field', 0, '>')
      ->condition('some_other_field', 12345);

    // The number of fields (and their aliases) must match query1.
    // Get the details with:
    // dpm($query1->getFields());
    $query2->addField('at', 'some_field', 'alias1');
    $query2->addField('at', 'some_other_field', 'alias2');
    $query2->addField('at', 'some_other_field2', 'alias3');
    $query2->addField('at', 'some_other_field3', 'alias4');

    // Verify that queries are very similar.
    // dpq($query1);
    // dpq($query2);

    // Matrimony.
    $query1 = $query2->union($query1, 'UNION ALL');

    // Manual test.
    // dpm($query1->execute()->fetchAll());

  }
}

This works for most views.  However some style plugins may do fancy stuff that won't work with this technique (Calendar module I'm looking at you).


How to compare with a rules condition vote:uid to 10 instances?

In the scenario you describe, a simple solution could be to create a profile field to store the number of votes per user. This field will be:

set to 0 as a default value
incremented when the user votes (you can use Rules for that, there is an action called "Set a data value")
compared with your defined maximum (ex: 10) in Rules, so that when the user reaches 10, something is triggered (ex: Remove user role: "Voting User")

You can then set the voting API permissions to this role ("Voting User"), and use it as a display condition to hide the voting buttons (Plus 1 or Rate).

Hope it helps!
Cheers


You can use field_get_items(), which returns you the value of a field in the language they would be displayed, or in the language whose code is passed as argument to the function. Generally, you are interested to the field's value in the language that would be used to show the field, and you don't pass any language code to the function.

$items = field_get_items('node', $node, $field_name);

$node contains the node object, and $field_name the name of the taxonomy term field.

What returned in $items is an array containing (possibly) multiple values; each value is an array containing the "tid" index, and the term ID. For a taxonomy term for which users can enter more than a value, this is what the function returns.


Create a user friendly workflow to create banners

The simplest would be a content type with an image field and a text field. The image field would be the banner and the text field would be the path on your website where it should be displayed.

Create a view that filters on that content type and has the image as the field it displays.  Put the path field as an argument.  Configure it to return only 1 item.

In a block, call that view using $_GET['q'] as the argument.

Image is displayed in the block.  Display this block on your page where you want your banner.

Don't like blocks?  Put this in a page_preprocess() hook and assign the view output to a variable and put this in your page where ever you want it.

Get fancy?  Randomize the sort so if more than one of these content types has the same path a different image is displayed on each page load/reload.

Get fancier.  Use the views_nivo_slider module ( http://drupal.org/project/views_nivo_slider )


//Get the Field information.
$field = field_info_instance('node', 'field_business_challenge', DIGITAL_IQ);

//Obtain group of that field.
$field_group = field_get_field_group($field);

//Get the name of the group from the Lable Attribute.
dpm($field->Lable);

There you go, you have the group name.


How to alter query of block inside a panel

You can check $view->current_display in your hook_views_query_alter to alter the query differently for each different block.


Setting field attribute as read only in hook_form_alter?

You can use the #disabled attribute:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form' && $form['nid']['#value']) {
    $form['title']['#disabled'] = TRUE;
  }
}

I made the assumption that you want this when editing nodes only (not when they are being added) which is what the && $form['nid']['#value'] part is for.


Why is my Views row template not loaded?

Your file should be called views-view-field--presse.tpl.php. field without an 's' not views-view-fields--presse.tpl.php file


Entity Reference - adding fields to reference?

The Entity Reference module does not support this. You'll want to check out the Relation module. With this module the reference (relation) itself is a fieldable entity.

I do realize you'll have to write an update function to migrate your current references to relations, but aside from creating a custom table as @FriOne suggested, it's the only way to go as far as I know.


How do I render nodes, now that node_view() has been deprecated?

The answer given by Berdir uses entityManager, which has been deprecated in favor of more specific services. This is the code I currently use.

$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';

$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$node = $storage->load($nid);
$build = $view_builder->view($node, $view_mode);
$output = render($build);

This code is a little more verbose than some might like; you could reduce it down to a couple lines if you really want more brevity by chaining together some methods.

$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';

$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($nid);
$output = render(\Drupal::entityTypeManager()->getViewBuilder($entity_type)->view($node, $view_mode));


Have you cleared cache yet? If not, go to the URL below to clear the sites cache. See if the error changes like you expected.

Drupal 6: /admin/settings/performance/drupal
Drupal 7: /admin/config/development/performance

It could also be that you changed the password of the SQL user that Drupal uses to operate, in which case you would need to update that information in /sites/yoursite/settings.php

What version of Drupal are you using?


There's a core issue for failure to install experimental modules (or, more precisely, modules with parentheses in the group name with Suhosin): https://www.drupal.org/node/2665152


There is a Webform issue which might be similar to this question here. Though that issue is after "upgrading", one could argue that after "upgrade" or after "install" of the module, the result is in both cases that you are using the newest version of the module, right?

So therefore, here are a few things in that issue that might help to get you going:

Clear the cache and try again.
if you did something like an update of that module (I think not, but you never know), then run update.php and try again.
Try to disable and then enable the module, and try again.

Curious to hear if any of this helps ...


I found the answer from someone on Facebook group (Drupal support group)
The answer is to add " --update" argument to the migration command, it will check for existing record and update it, or create new record if not exists.


How to force a cron run after a Rules component is scheduled?

you can give this module a try , it makes it possible to run cron via configurable rules
Ultimate cron


You can just insert it in a Block. just goto Structure > Block > Add Block and enable full html input and just copy and pate. Then just assign that block to where you want it to show up.


Add fields to a coded block and use them in a templated block

Probably the easiest way to do this is a block with a settings form.

When you place a block of this class via the block layout, you can add your information in the settings.  To have another block with different settings, just place another block.

Some sample code:

 public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['my_block_text'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Foo'),
      '#description' => $this->t('my desc'),
      '#default_value' => isset($config['my_block_text']) ? $config['my_block_text'] : '',
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['my_block_text'] = $values['my_block_text'];
  }
  public function build() {
    $config = $this->getConfiguration();
    $text = $config['my_block_text'];
    ...
  $block = [
   '#theme' => 'my_module_my_theme',
    '#my_text' => $text,
    ...
  ];
  return $block;
}

For images / files, you can just use the standard file form type.  The config will get the fid of the image.  In the build, you will need to load the file entity and generate the URL to the file.  (Lots of existing examples of this).

To get it all to twig, you will need to use a hook_template() implementation that defines the twig template and variables. Then pass it to the theme using the render array created in the block build code.


What is the Drupal 7 version of FILE_STATUS_TEMPORARY?

That is strange, as FILE_STATUS_PERMANENT still does exist indeed. But the value of FILE_STATUS_TEMPORARY used to be 0. So I suppose you can use anything that evaluates to zero: FALSE, NULL, 0. Personally I have always used 0.

But why set your file back to temporary to have it deleted by cron, why not just delete the file directly after processing? You can use file_delete() to do that.


TinyMCE - Drupal 7 - Insert images not functioning

Disabling the BBCode option in my TinyMCE Wysiwyg profile worked for me.


This is a php issue.

$data = 'heeeello';

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  echo $data; // $data is NULL, will also throw a notice
}

MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  global $data;
  echo $data; // $data is 'heeeello'
}

regarding your variable_set, the params are different:

$data = 'heeeello';
variable_set('hello', $data);
MY_MODULE_leaflet_views_alter_points_data_alter ($result, &$points) {
  $data = variable_get('hello');
  echo $data; // $data is 'heeeello'
}

RE edit: this goes towards your extension:
variable_set() is not designed to do sets on every request, variables should be quiet consistent, every variable_set will clear your cache (to some extend), abusing this will lead to a lot of performance problems.

If you need a cache use cache_set and cache_get, for singletons/ static stuff use drupal_static. The global variable $test you are using right now in your question, should not return NULL but array(), everything else looks like a different problem.

If you want to build up a storage backend create proper tables using hook_schema or (advanced) build your own entities.

edit: almost forgot, your code from above, is not working because you are not saving that variable again, so even for the second run it will always be empty.


Redirection after adding new groups and gnodes using group module

If The issue you posted about promises to solve your problem then your best bet would be to test the patch (always on a test server) and help this issue forward so others can take advantage of that in the future, because this is how drupal progresses mostly.

Just download the latest .patch that you find in the group modules directory
and open up up a command window (in windows) or shell in linux based systems and apply the patch

in a linux based system you could run the following commands, assuming group is in modules/contrib/group and using latest patch as an example

cd modules/contrib/group
wget https://www.drupal.org/files/issues/2817109-by-rachel_norfolk-ericras-How-to-redir.patch
git apply -v 2817109-by-rachel_norfolk-ericras-How-to-redir.patch

If the patch does not report any errors you will probably get a configuration field to do what you are asking and it would be great to post in the thread how the patch went for you.

More on patches here

If you want something different you should create your own module and implement a hook_form_alter to set setRedirect for both of the forms that you mention similar to what rachel_norfolk does in comment #3


How do I deliver a nested JSON array for content reference with export view display?

I've created a very simple module REST Export Nested to support nested JSON using Views Field Views.

After installing "REST Export Nested":

Install and enable <a
href="https://www.drupal.org/project/views_field_view" rel="nofollow noreferrer">Views Field
Views
Create view display of referenced content (Articles in your case) of type "REST export" or "REST export nested"
Add a relationship to the parent entity and contextual filter of parent entity ID
Create a view display of the parent entity of type "REST export
nested"
Add required fields (e.g. "nid", "title")
Add a field of type "Views field" (e.g. "articles"), configure with
the correct View and display and pass "nid" as the contextual filter

The module doesn't depend on Views Field View and may work with other fields which produce a JSON string.


Can you save state in the $form_state variable that remains when the form is rebuilt?

You only need #name if the form array keys don't provide a unique path for form_state. I agree with @Jaypan, I too found setting #name never really necessary, it seems to be more reliable to define a unique key to the lowest level of the form element if you have issues with Ajax not finding the form element. In either case, #name or form key, it has to be predictable, derived from data which doesn't change between form builds, for example a field delta.
The form object and $form_state are not cached when a form is rendered, only after submitting the first Ajax request. So it doesn't help to store data in $form_state you want to use to rebuild $form.


Give access to private files to certain role?

I found the problem. As per this page:

Once configured, files stored in the private directory are inaccessible via a direct link; however, if Drupal constructs a link to the file, the file will be accessible to anyone who can see the link.
For example: you have created a new content type with a file field which stores files in your site's private file directory. Next you create a node from this new content type and attach two new files. When the node is published links to both attached files are visible and anyone who can view the node may download the files. Now, if you unpublish the node, all attached files become inaccessible for download even if you use the direct link to the files that worked when the node was published.
Re-publish the node, and disable the "display" checkbox for one of the files. Save the node. Now one file is accessible for public download and the other is not accessible--even if you have the direct URL for the file that is not listed you will not be able to download this file.

So the problem was that I was expecting you could access a file if you have the right URL, even if that file is used on an UNPUBLISHED node. So to solve my problem I:

Published all the nodes I needed to have access to the image
Used "Rabbit Hole" to hide the nodes from the public


Try This

$nid = db_query('SELECT id FROM {stats} WHERE type = :type ORDER BY id DESC LIMIT 1', array(':type' => $param))->fetchField();

Refer db_query for more information...


User Content with image gallery and text

You can configure the number of images the user can upload while creating a node in the field settings (manage fields page of your content type)

Once the images are uploaded you can display them in a slider/carrousel style using modules such as :

Galleria
Gallery formatter

Or you can just display clickable thumbnails (and a bigger version in a lightbox.)

You can set the image dimensions in : /admin/config/media/image-styles

You need to tell me more about the way you want your images to be displayed.
What version of drupal are you using ?


Watchdog entries are deleted by dblog_cron(), if the dblog_row_limit variable is greater than 0.

To stop them being deleted, set the dblog_row_limit variable to 0.


How can I recalculate field values of a rendered node?

I dont think there is any module that you can use, you can try hook_node_view_alter hook to change the rendered.

  If the module wishes to act on the rendered HTML of the node rather
  than the structured content array, it may use this hook to add a
  post_render callback. Alternatively, it could also implement hook_preprocess_node(). See drupal_render() and theme() documentation
  respectively for details.

Check hook_entity_view_alter too

If you want to change in the node create form, there is Conditional Fields Module.

  Define dependencies between fields based on their states and values.
  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.

Installation and Usage


.htaccess file using redirect.

IfModule mod_rewrite.c

Redirect 301 /fromurl /tourl

Example:

Redirect 301 /http://www.example.com /https://www.example.com

Try it.


entityQuery filter by content moderation state

You try the code :

$query = \Drupal::database()->select('content_moderation_state_field_data', 'ms');
    $query->join('node_field_revision', 'nf', 'nf.nid=ms.content_entity_id AND nf.vid=ms.content_entity_revision_id AND nf.langcode=ms.langcode');
    $query->fields('ms');
    $query->condition('ms.moderation_state','draft');
    $results = $query->execute()->fetchAllAssoc('content_entity_id');

Because entityQuery not filter content moderation


I assume you have a custom block with a form created from your custom module.
You would need to add an attribute #prefix to the first field item starting from which you want to hide the items and add an attribute #suffix to the last field item you want to hide, For example,

$form['first_item']['#prefix'] = '
';

// more elements here

$form['last_item']['#suffix'] = '
';

Then, you can bind jQuery.slideUp() and jQuery.slideDown() to the more/less link element, let's say for example, #moreless.

$('#moreless').bind('click', function(){
    if( $('#accordian:visible').size() ){
         $('#accordian').slideUp();
         $(this).html('More &raquo;');
     }else{
         $('#accordian').slideDown();
         $(this).html('Less &laquo;');
     }
});

You can see the working jQuery code here. These two jQuery functions are provided by jQuery core API. You don't need to include any extra library.


There are multiple ways to do this.

You can create a view page with list of nodes and you can add other
content in the views header or footer area.
You can create it as view attachment and can add to other view.

Basically views have a great flexibility to get embedded in one another,panels, nodes etc.


Admin edit of older order forces to add values to newly added required fields

How you resolve this depends on your Drupal version, so please be sure to specify Drupal 7 vs. Drupal 8 in future questions. On Drupal 8, you can likely resolve this by editing the form display mode and not including those fields on the normal admin form. However, in Drupal 7 you'll have no such option. You'll need to use hook_form_alter() to prevent those fields from showing up on the order edit form instead.

Re: the administrator name, there's no way for us to help you without knowing how you've constructed that View. If it's just showing the name of the last person to edit the order (i.e. create a revision of it), it makes sense that it'd be the administrator. It should normally be pulling the name from the order's billing information profile.


What privileges should a MySQL user have?

For development you'll need essentially everything - including drop. Once you go live, drop is generally not needed.

That said, if you're allowing delete - for instance - then drop isn't much more drastic. If someone owns your server, deleting all the rows from your tables is pretty much as bad as dropping a table - either way, the only good fallback is proper backups.

Setup your database user to only be allowed to connect from the host Drupal is running on. And make sure if that host has ssh allowed, you're using keys, and not just username/password, and you should be pretty good.


i hope , you have used basic html filter. Basic filter doesn't support all of the tags of html. you have to use full html filter instead of basic html.


First verify that the Issue type isn't set to hide comments. If comments exist but are hidden, only admins will see them. A path something like this: /admin/structure/types/manage/issue, and go to the 'Comment settings' tab at the bottom.

Also, you might go to /admin/reports/status/rebuild and rebuild the permissions cache.


How can I show the user login block on the 403 page?

One approach is to add page templates to your theme registry:

function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  //Allow theming the site error pages
  $route_name = \Drupal::routeMatch()->getRouteName();

  switch ($route_name) {
    case 'system.401':
    // Unauthorized Access.
    $error = 401;
    break;

    case 'system.403':
    // Access Denied.
    $error = 403;
    break;

    case 'system.404':
    // Page Not Found.
    $error = 404;
    break;
  }

  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }

}

Then in page--403.html.twig you can render a specific block with Twig. See: How to embed a view in a specific node? and Programatically print blocks in twig

*A reason I like this approach is that the Login block is a Drupal core block, not a custom one. You can just carry around a nice 403 template file and always know it will render out this block. The preprocess function above seems like the least invasive and time consuming (from looking at different approaches), plus it gives the ability to theme these error pages. I think it is ideal to utilize template files for error pages.


Is making field.tpl.php print the URL of the node the displayed field is attached to possible?

The solution is<?php print drupal_get_path_alias("node/".$element['#object']->nid); ?>

This will print the URL Alias of the node that the respective field is attached to.

I found that I could get the NID of the node the element was attached to by doing<?php print_r($element['#object']);?>to find all of the available options for<?php $element['#object']?>when I found I could get the NID from that field I then put it inside of<?php drupal_get_path_alias() ?>and have it return the desired text.

It took a day to find it but it works. Hopefully someone else can benefit from this as well.


How to allow users to post content and easily overrule its default access settings?

You can get this to work using a combination of the Rules module and the Content Access module, whereas the Rules module will automatically (behind the scenes) trigger the logic that's needed. The logic itself is entirely hidden for the user (author) and is equivalent to using the interface that you consider too complicated.

Here are some more details to get it to work:

Start from a rule that is similar to the example I included in my answer to "How to specify a Rules condition related to select list values?".
This sample rule uses a field named field_optionlist, with 3 possible values A,B,C. In your case you could use any other fieldname (to fit your naming conventions). And your field only needs 2 values, say Y (= yes, instead of A) and N (= no, instead of B). Some more tips to get you going:

Make sure to define this field (for your content type news) BEFORE importing the rule sample in item '1.' above (if not the import of the rule will fail).
If you use another machine name for that field, also edit the field name in the sample rule before importing it.
Adapt the Rules condition related to "value = C" to "value = Y" (to fit your case), and the message included in the Rules Action.

QA-test the intermediate result after completing step '2.': you should have a Drupal message show up when a news node is created with field value = Y (and not when it is not Y).
Use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?". The actual settings to use for the content access module should match with the settings you seemed to already have tried (but which you consider as too complicated to have the node editor set them).

Refinement: if you really want a "checkmark" (instead of such yes/no selection field explained above), create a boolean field and rework the rule detailed above to use that field instead.

Bonus: if you ever need similar logic for another content type, just define the SAME field (with same machine name). After doing so, you should not have to change anything to the Rule as defined above. That's because of the "entity has field" condition ...


How to alter Fields of Field Collection?

try to use
$form['YOUR_field_collection']['und']['0']['sub_field']['und']['0']['value']
for ex : to add ['#autocomplete_path'] would :
$form['YOUR_field_collection']['und']['0']['sub_field']['und']['0']['value']'#autocomplete_path']=''


How can I alter an "Add to cart" button at the submission time?

You can use the form alter as follows:

function hook_form_alter(&$form, &$form_state, $form_id) { //hook can be replaced by theme name if being defined in *template.php* of a theme and by the module name if function is being defined inside a custom module

  if($form_id == 'commerce_cart_add_to_cart_form') {

//HERE YOU CAN DEFINE A SUBMIT HANDLER, WHICH WILL ACT ON HITTING ADD TO CART BUTTON. Example:

    $form['#submit'][] = 'custom_submit';
  }

function custom_submit($form, &$form_state) { //custom submit handler

  //Add here the functionality you want to do on click of add to cart button

}


db_update query in custom installation profile gets ignored

db_update it is a selectable object. It builds SQL queries. https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_update/7

Yes. Everything is in database. You can changes by queries. You should use api functions or common approaches.

Theme data is stored as variables, for Drupal it is enough.

variable_set('theme', 'my_theme');
variable_set('admin_theme', 'theme_name');

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable_set/7
It says that if you want change it by queries you need update the variable table.

Also when you manipulate with cache-able objects(blocks here) you need clean cache.

cache_clear_all();


How to display current langage on top of the langage list in a content type

If you edit your content type, you should have a Language settings tab, I guess you have on Default Language "Site's default" and not the current interface language.


My local site directs to install.php after update from production site af drush sync

Is settings.php there? It is not synced by default with drush rsync.

The redirect to the install page also indicates that you are missing settings.php.


Can I use views_bulk_operations with the D7 core toolbar module?

I figured out how I want to do it: http://drupal.org/project/quickbar

The Quickbar module allows me to provide an administration bar at the top of the page, much like the default toolbar, but I get to define what menu is placed in that bar. It will allow me to keep the content admins away from the default content admin pages by simply not providing a link to it.


Views Path Settings is not redirecting to particular path?

Go to /admin/config/search/clean-urls and enable the clean urls.

Then try these steps If clean Url test is failed.
enable mod_rewrite apache from httpd.conf

open httpd.conf
find mod_rewrite
just remove # to enable
once it enable then you can run Clean URL
this will show check box tick on it and save it


Assign content automatically to specific user

You can use Node Access Rules to achieve this goal. Using this you can create rule to access that particular content having some condition as per your requirement.


In D7 you can use a phpsnippet calling views_embed_view. Modules to do the job like Views embed filter seem to have died at the D6 stage.


WYSIWYG + CKeditor provides a "Paste from word" option; it doesn't do any automated importing, but does provide a popup window containing a textarea for the user to paste from word. The pasted content is then cleaned up and converted to HTML, and finally placed in the WYSIWYG as normal content.


Render a field contained inside of another field

I think the issue here is that each of those paragraph groupings contain various elements that are array keys. For example, if you dpm up to $content['field_paragraph'], you may see values that look like this:

I think the issue is, due to your loops, your trying to render/loop through things that aren't objects. To get around this, you might want to try checkin if the key is numeric before proceeding on.

Something along the lines like this:

<?php
    foreach($content['field_paragraph'] as $key=>$array){
  if (is_int($key)) {
    foreach ( $array['entity']['paragraphs_item'] as $key2=>$item ) {
    if ( is_int($key2) ) {
      print render($item['field_body']);
    }
  }
  }
}

?>

Note the is_int($key), that's what you need to get the errors to go away. Note my code has my own field names in it, so you'll just need to switch yours in.


Should I run tests for the entire core and contributed modules, or only for the codes I wrote?

The whole point of doing unit testing is verifying code functionality and preventing regression bugs on new code changes. Unless you're working on some development branch (i.e. not a release), running 3rd party vendor (core, contrib modules) unit tests is redundant; you should write unit tests for code that you're maintaining and trying to keep reliable and bug free.


theme_hook_suggestions is ignoring my suggestions

You're missing how the framework is designed.

If you're doing anything with hook_preprocess_page() you are affecting the 'page'.

The default template for page is 'page.tpl.php'.

If you want to 'override' this template Drupal needs to understand what's going on so has some conventions.

page--[front|internal/path].tpl.php

page--node--edit.tpl.php
page--node--1.tpl.php
page--node.tpl.php
page.tpl.php

"Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds"

See: http://drupal.org/node/1089656 and http://drupal.org/node/223440#custom-suggestions

In your case, your defining 'newbies.tpl.php' and expecting this to work but it's still going to use 'page.tpl.php' so to override this you want to do 'page--newbies.tpl.php' (same as 'page--node.tpl.php').

More to the point, you don't even need to set this with hook_preprocess_page() as Drupal will follow those conventions automatically.


Can't migrate alias with Wordpress Migration

Turns out path/alias worked. I must have been doing something wrong or my page was cached that it wasn't redirecting to the alias.

path/alias:
  -
    plugin: get
    source: link
  -
    plugin: str_replace
    source: link
    search: 'https://myurl.com/'
    replace: '/'


How to change background image based on current node?

You can make a different templete and use, for example, a class and load the different img by css is one of many possible soluctions, I think that is the best practice

You can read more about Drupal 8 Temple in these threads:

https://www.drupal.org/docs/8/theming

https://www.drupal.org/docs/8/theming/twig

Example aplications

function YOURTHEMENAME_preprocess_node(&$variables) {
  if ($variables['node']) {
    $node = $variables['node'];
    switch ( $node->nid ) {
    case 'nid1':  // Replace nid1 etc with your nid
    case 'nid2':
      break;
    }
  }
}

Template/node/node--full--[nid]

    <div class="img--hero--image">
    </div>

Other solutions it is use a field in the content type and use this field to render in your background.


Why does Drupal have both "sid" and "ssid" field in the session?

Yes it is a security measure; sid is the session id for HTTP traffic &  ssid is the session id for HTTPS traffic. The idea here is that secure parts of your website (e.g. https://www.example.com/user/*/edit ) can't be compromised by session hijacking the sid that occurs with HTTP traffic.


How can I add a title to a field in the checkout page?

Not possible in User Interface (via link or menu or whatever). But if you use the following code in a module, you can add a title to your form element:

<?php
function CUSTOM_form_alter($form, $form_state, $form_id) {
  // You should probably check for a form_id in here, as this runs on every form.
  // Below you will need to find the part of the $form array that has the billing address.
  $form['[see note above]']['widget'][0]['address']['address_line2']['#title'] = t('Address 2');
}


How can I capture JavaScript value for use on tpl.php

What you can do in this particular case is add the HTML for both the images inside tpl file.
On the js file, you can display/hide the images according to your IF condition.

To capture JS value for use in tpl, you can use javascript/ajax to send the information through a url / xmlhttp and then use hook menu to grab the information inside module file, then send the variable to the tpl


very bad thing of output the vocabulary in drupal 7

What you are looking for is what is called field formatters. It is essentially theme function for themes, and can be used to render the same field in ['form'] ways. You can create a custom field formatter where you render the output of the field how you want.

To read more about fields and formatters see: http://drupal.org/node/707832
Or you can checkout this step by step guide on how to create a field formatter.

Another option would be to simply overwrite the theme function (That can be done with any theme function) used for the default field formatter, which would then effect all of the fields across your site.


Your menu item looks fine so make sure you've done the usual things, make sure the module is installed and enabled, and make sure you clear Drupal's caches so the menu is rebuilt and your new item can be picked up.

On another note, if this callback is meant for AJAX you probably want to be printing something rather than returning it in your callback function. Something like this:

function callback_test() {
  print 'success';
  drupal_exit();
}


Will this php code (field_view_field) work if i put this inside body field of a node with php filter?

Use the following code.

  $node = node_load(1);
  print render(field_view_field('node', $node, 'field_fivestar_rating'));


Create custom and unlimited Node list per user

You can have a look on these modules

Flag
Flag Lists

Using Flag module users can save nodes in to their bucket
and Flag lists module will make those lists as like folder structure.


How can I improve running repeating background tasks?

Instead of updating a global cache of remote objects (which a visitor might see a stall on while data is being fetched ...)

Simply use 2 caches. 1 cache is what visitors see data from from say a Drupal cache bin. The second cache bin is another private drupal cache bin updated by your module from the remote host. You could make custom cache tables in Drupal or simply use raw MySQL tables without the Drupal API if you're not familiar with it.

Then on occasion do a database table flip (eg, truncate cache2; select cache1.* INSERT INTO cache2;, or sync from 1 Drupal cache bin to the other. This local cache store updating should be faster than the remote server.


How to call form function in menu callback in drupal7?

After some sort of study, I got to the answer. we can get form by using drupal_get_form and then in return function, we need to render it also.
for example:

function component_list_edit() {
  $form = drupal_get_form('component_type_select_list_form');
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return '
Title:'._mid_component_make_link('Title').drupal_render($form).'
';
}


Add custom class to views row depending on field value

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);
    }
  }
}


Is there any log or receipt or anything that message was sent to someone?

It won't help to go back in time, but for similar requests in the future I recommend you to have a look at the Message module, which is part of the Message Stack. Read on for more details ...

Create a Message archive (audit trail)

By using the Message module, you automagically also create an archive of all Messages. Which is very handy in cases such as when a user claims to never have received some eMail. In such cases, think about how you'd proof that some eMail was mailed somewhere in the past ... as compared to using Message and just bring up that message again ...

A typical scenario (as in the question here) that would be prevented by using the Message module:

  I tried to look at the log files at server but they didn't include anything regardins this message. Also the Drupal system log was one month ahead that time when the message was sent.

Message stack

These are the basic components and dependencies of it:

For this question only the Message module would be needed (not the other Message-related modules). But first, to explain the above picture, some more details about the Message-related modules (=quotes are from the module's project page):

Message:

  The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

  This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

  With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Distributions / modules using Messages

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its Answers Notification sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

Combining Rules and Message

Moreover, by using the technique of Replacement tokens, it's possible to create your own Message-"tokens" using ... Rules! If these Replacement Tokens don't mean anything to you (ie you don't understand what they are really about), then head over to the answer to What's the purpose of "Replacement tokens" of a Message type? for (way) more details on that.

As an example, here is a (rather basic) custom rule:

a Rules Event like "Before saving a new node", of "After updating an existing node" (or variations of these events).
a Rules Action to "Create a message" (of a selected Message type).

That's really it ...

A really interesting facility of the Message module is its perfect integration with the Rules module. Have a look at the answer to "How to implement a follow author (or user) function?" for way more details on that.

Yet another sample that could be a perfect fit (= a quote from the question ...):

  I'm using Drupal 7 and custom message(confirmation) is sent with Rules when user has made an order and registered as user (of which all is done via customized "Add node" form).

You might be lucky

The prior quote got added to the question afterwards. And possibly explains also why you tagged your question with the drupal-commerce tag (removed in revision 3 by a mod).

So if you're lucky your site might already use the Commerce Message module, in which case you already might have such audit trail (which you don't know about). Just use Views to search what you're looking for.

If you don't use that module yet, then hurry to get it enabled for similar requests in the future.

Possible alternative for syslog

The Message module is also a possible alternative for the Syslog module (included in Drupal core). For example in situations like this one (= quote from "Syslog module overview"):

  It is not suitable for shared hosting environments.

More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules.

Though there is not a lot of documentation about it (which is what makes it a hidden D7 gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

How to create a basic message - notifications system displaying a real time message counter badge?
How to show message view containing own and following activity?
How to integrate messaging into a custom module?
Is there a simple way to notify users about new posts on the site?

Tutorials:

What is Drupal's Message Stack and how do its modules work together?
How to allow users to manage their own Message Stack messages?


Looks like you're on /admin/people/permissions, which is the page for configuring permissions per role. You want to be on /admin/people/permissions/roles, which is the page for configuring the roles themselves. If you can access /admin/people/permissions/roles, you'll be able to add more roles there.

If you get an 'Access Denied' error when you try to access that page:

Go back to /admin/people/permissions.
Make sure you've given the 'administrator' role all permissions.
Go to /user.
Click the 'Edit' tab.
Scroll down and make sure your account has the role 'administrator'.


Drupal PHP filter being overwritten in Lexicon Module

I have been able to get a fix - but not an ideal one. I moved the PHP text format to be displayed as a first priority at admin/config/content/formats. Doing this preserves the PHP code after hitting save. The reason I say it's not ideal is because now PHP code will be displayed as the default format for making new pieces of content - fine for me, but I'm sure the client will wish they could get their WYSIWYG right away.

If anyone knows a way to target the display order of text formats for just one specific module, I'm sure that would be the solution.


How do I programmatically duplicate a view display?

The View entity comes with a handy function for duplicating an existing display, ->duplicateDisplayAsType().

->duplicateDisplayAsType() requires 2 arguments--ID of the display to duplicate & new display's type.  First one is self-explanatory--if you want to duplicate something, you need to know what you want to duplicate (visit a View and look at the URL for the unique ID).  For the second arg, a View Display needs to be of a certain type--page, block, feed, etc.

Finally, we have something like below:

$commentView = \Drupal::entityTypeManager()->getStorage('view')->load('comment');

// ->duplicateDisplayAsType() returns the new display's ID so it's not 100% necessary
//   to assign the return val to a variable.
$new_page = $commentView->duplicateDisplayAsType('page_published', 'page');
$new_block = $commentView->duplicateDisplayAsType('page_published', 'block');

$commentView->save();

Above, I am using the default 'Comments' view and duplicating the 'page_published' Display as both a new page and new block.  Try copy pasting the above code into a Controller and triggering the controller method once and visit the View to see your new Displays.

Finally, as with most entity operations, you'll want to ->save() it afterwards.

Note:  Using (presumably) \Drupal\views\Views::getView() will return a ViewExecutable--aka a configured View which is used for generating the actual output.  You cannot edit the View's config via ViewExecutable.  Above, I am using the entityTypeManager() to query for a View so I can retrieve the actual Entity so we can modify its configuration.  The above code can act as boilerplate--try switching out values to achieve your desired goal.

EDIT: To answer your question more definitively, the above example code could be translated to match your code snippet:

$view = \Drupal::entityTypeManager()->getStorage('view')->load('my_view');
$new_page = $view->duplicateDisplayAsType('page_1', 'page');

$view->save();

Edit 2:  Sorry, I didn't answer your second part--how do we modify the display after duplicating.  This may not be the most efficient way so someone please tell me if there is a better way to do it.  Luckily you want to only remove a filter.   Because filters are not yet OOP, they're just giant arrays with specific keys you need to set.  This part does get a bit more complicated.

There is one thing you need to keep in mind though--the default display will apply its display_options across all displays unless you override them in the 'defaults' array on the specific display configuration.  You can override defaults for each display_option so you can still inherit defaults for some properties while overriding others.

For comments, specifically, the filters are all placed on the 'default'.  Out of the box, the Comments view only comes with the page_published display.  Let's say we want to duplicate the page_published display, copy over the filters from the original display, remove its default filters, and then array_pop() one of the filters off our new display.  So starting from scratch again:

$view = \Drupal::entityTypeManager()->getStorage('view')->load('comment');
$new_display_id = $view->duplicateDisplayAsType('page_published', 'page');
// Must use the getter--the display property is protected
// We assign by reference because there is no setter--we cannot set the display
//   options again after modifying but we can modify the referenced var to change
//   the original values
$new_display = &$view->getDisplay($new_display_id);
$default_display = &$view->getDisplay('default');
// Copy the filters from the 'default' to the new display
$new_display['display_options']['filters'] = $default_display['display_options']['filters'];
$new_display['display_options']['filter_groups'] = $default_display['display_options']['filter_groups'];

// Tell Views not to use the defaults for these two specific properties
$new_display['display_options']['defaults'] = [
  'filters' => FALSE,
  'filter_groups' => FALSE,
];

// For demonstration purposes, we remove 1 filter from our copied over filters
array_pop($new_display['display_options']['filters']);

$view->save();

You should see a page exactly like the page_published except it should be missing 1 filter.


Edit

According to the Readme.txt,

  You should now see login and register links on the right of the main bootstrap nav bar.

Enabling the module should show a link on the nav bar by default.

According to the project page,

  You should now see login and register links on the right of the main bootstrap nav bar.

/Edit

You can update all the links on your content, or use Javascript on a page load to modify them.

If you want to go with JS. This should get you started:

  var aTags = document.getElementsByTagName("a");
  for (var i = 0; i < aTags.length; i++) {
    if(atags[i].href == "/user/login") {
      //Modify your links
    }
  }


Why can't I uncheck "Create new revision" on the content type edit page?

The problem was the Content Moderation module (Drupal 8.4).  I guess I have to take the experimental warning seriously.

When Content Moderation module is enabled, you can't change the "create new revision" status for any content type.

However, content types not subject to content moderation will not have the "Create new revision" box checked on the node edit page if the box was not checked before Content Moderation was enabled-- or if the content type was created while Content Moderation was enabled.

This can be confirmed by checking the config for the content type that has been exported by drush, which shows new_revision: false.  This is most likely a bug so I'm off to file an issue.


You don't have any submit callback. You should do any process with the submitted data in a submit callback like that:

function project_creator_insert_submit($form, &$form_state) {
  db_set_active('civilproconstru'); /* OPEN DATA BASE*/
  db_insert('project_info')
    ->fields(array(
      'p_name' => $form_state['values']['p_name'],
    ))->execute();
  drupal_set_message("succesfully saved");
  db_set_active(); /*CLOSE DATA BASE*/
}


// Check to see if $user has the administrator role.
  if (in_array('administrator', array_values($user->roles))) {
    // Do something.
  }

Replace "administrator" with the role name you want to check.

EDIT:

If you want to check for role id's use below code.

global $user;
$role_ids = array_keys($user->roles);
if (in_array(6, $role_ids)) {
  // Do something
}

In your case

<?php
global $user;
$role_ids = array_keys($user->roles);
if (user_access('access administration pages') || (in_array(6, $role_ids))) {
  return FALSE;
} else {
  return TRUE;
}
?>


Why is the 'time ago' not displayed in my view?

I don't know what causes the problem, but I solved it temporally. I changed the Date format to 'Time ago' an added the 'ago' manually via the 'Rewrite results' function.


Display name of Content Type instead of node Title in Views

It's simple. Go to your view. Add field >> Content: Type

Then in the field settings, check 'Link this field to the original piece of content'

That's it. You will find content type in each row. and if you click on it goes to node content page.


Are there any disadvantages in placing form elements in custom containers?

I can't comment yet so I'll try to be broad.  First, there are not any disadvantages to customizing your output html, the form process and validation will work just fine as long as you're not adding form tags to your html that you are hoping Drupal will also process.

You don't need hook_form_alter if you only want to modify the html. You can use, in your template.php file, hook_theme().

The first thing you would need is the id of the form.  You can get this via viewing source or using the devel and devel themer modules.

Once you have your form id, within template.php:

/**
 * Implementation of hook_theme
 */
function yourthemename_theme($existing, $type, $theme, $path) {
  return array(
    'user_login' => array( // to modify user_login form, for example
      'render element' => 'form'
      )
  );
}
/**
 * Theme function
 */
function yourthemename_user_login($variables) {
  $user = drupal_render($variables['form']['name']); // use the devel module:kpr($variables), or print_r($variables) to look at the $variables['form'] element
  $pass = drupal_render($variables['form']['pass']);
  $remainder = drupal_render_children($variables['form']);
  // put the user field and pass field inside a custom div
  $output = '
' . $user . $pass . '
';
  $output .= $remainder;
  return $output;
}

Take a look at drupal_render() and drupal_render_children() but, basically, when you call drupal_render it 'renders' the element and remembers that it was already rendered.  You use that with as many elements as you need to but always remember to render the children as well so that all of your hidden fields and drupal form stuff doesn't get left out.

Alternatively, I don't think I've come across a Drupal form I couldn't wrangle with some well-targeted CSS, if you'd rather go that way.


How to translate plurals in language with multiple cases (most of European)

format_plural() does support multiple plural versions in general.

format_plural() only has arguments for singular and plural because english only has those two and the input is always english, Drupal does not support translating interface text from another language than english.

However, it is something that defined per language and not per word, that doesn't work. I'm not aware of a workaround that can handle per-word differences.

Actually, according to https://en.wikipedia.org/wiki/Czech_declension#Plural_forms, those rules (1, 2-4, 5+) are always the same? So that should just work.

This is how it looks in the UI


Redirecting doesn't work with a custom form in a block

I believe the redirect should be $form_state['redirect']