Selecting the number of Records from Textbox

IIRC you could build this type of an Entity reference field with the help of Entity reference Views Display in Drupal 7 and the Entity Reference View Widget module.

In Drupal 8 you probably need the wonderful Entity Browser that is usually used to manage media files, but no reason not to use it for any other entity references. So you still need the Entity reference field, you just use the Entity Browser as the widget for that field to control how the choices are presented.

You'll probably want a filter above your results to list a certain number of results (100 for example) and then a "Select all" option to select all the results that have been filtered out (table display may come with that already).


How I can add an optional parameter in REST API URL

I experienced the same issue and solved it by adding the current request from the request stack to my resource:

RestBase.php

<?php

namespace Drupal\api\Plugin\rest;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

class RestBase extends ResourceBase {

  /**
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;
  /**
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $currentRequest;

  /**
   *
   * @param array $configuration
   * @param type $pluginId
   * @param type $pluginDefinition
   * @param array $serializerFormats
   * @param \Drupal\api\Plugin\rest\resource\LoggerInterface $logger
   * @param \Drupal\api\Plugin\rest\resource\AccountProxyInterface $currentUser
   */
  public function __construct(array $configuration, $pluginId, $pluginDefinition, array $serializerFormats, LoggerInterface $logger, AccountProxyInterface $currentUser, Request $currentRequest) {
    parent::__construct($configuration, $pluginId, $pluginDefinition, $serializerFormats, $logger);

    $this->currentUser = $currentUser;
    $this->currentRequest = $currentRequest;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
    return new static(
        $configuration,
        $pluginId,
        $pluginDefinition,
        $container->getParameter('serializer.formats'),
        $container->get('logger.factory')->get('rest'),
        $container->get('current_user'),
        $container->get('request_stack')->getCurrentRequest()
    );
  }

  /**
   *
   * @param array $message
   * @param integer $cache
   * @return ResourceResponse
   */
  protected function getResponse($message, $cache = 0) {
    $build = [
      '#cache' => [
        'max-age' => $cache,
      ]
    ];

    $response = new ResourceResponse($message);
    $response->addCacheableDependency($build);

    return $response;
  }

}

TestResource.php (the actual REST resouce)

<?php

namespace Drupal\api\Plugin\rest\resource;

use Drupal\rest\ResourceResponse;
use Drupal\api\Plugin\rest\RestBase;

/**
 * Test resource.
 *
 * @RestResource(
 *   id = "test_resource",
 *   label = @Translation("Test API Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/test-resource"
 *   }
 * )
 */
class TestResource extends RestBase {

  /**
   *
   * @return ResourceResponse
   */
  public function get() {
    if (!$this->currentUser->hasPermission('use ' . $this->pluginId . ' service')) {
      throw new AccessDeniedHttpException('Access denied.');
    }

    $id = $this->currentRequest->get('id');

    $message = [
      'message' => 'Hello, you called service: ' . $this->pluginId,
      'id' => $id,
    ];

    return parent::getResponse($message);
  }

}

In my own base class RestBase I added the current request from the request stack (besides the AccountProxy for permission purposes) by overriding the create method of the ResourceBase class. You can then access query parameters in your REST resource by calling the get($key) method on the request object.

You will need to pass your parameters in the API URI like so: http://localhost/api/test-resource?_format=<your-format>&<parameter1>=<value1>. Considering this example API URI you would access parameter1 via $value1 = $this->currentRequest->get('parameter1').

I guess that it is not possible to have slugs in your resources at the moment. If someone knows how please do tell :).


How to create a module to allow for multiple instances of the same module with different variable parameters

Generate your blocks same way block module does: appending an id. Then store your configuration indexed by this id. You can store your values in a custom table (see schema api and install file syntax) or in the variable table (using variable_get() and variable_set()).

Whenever an operation with a block happens you receive the block id. Use the block id to access or set your configuration data. For example, the code for rendering a block should be the same for all your custom blocks, but you feed that code with different configurations that you read from your custom table or variable table using the provided block id.


Views query alter for specific node/content type

If You only want to display data for specific roles to specific persons then you can use Global php in views to filter your results, Just take "User: Roles (Roles)" in your field as excluded and use its token in Global PHP field.example

if([roles] == "admin"){print [your_field_token_name];}
elseif([roles] == "your_roles"){print [your_field_token_name];}

You have to download the module of viewsphp to use global php.


Vague error message on config import: Config x depends on x that will not exist after import

Answering my own question, hoping it may help others. The error message above, in my case, indicates a missing configuration file.

My workflow usually involves switching between branches and re-setting the database to its pristine state. Then I try to import the configuration before finishing a piece of work.

It turns out I did not commit some field.storage.* configuration files before I switched branches and re-set the database. Then the import failed and complained about missing configuration. Re-reading the error messages more carefully allowed me to understand the underlying issue.

I used my IDE (phpstorm) local history feature to search for the missing files and restore them. This fixed the issue.


How to convert Drupal Field Collection to Node?

This sounds like a job for the Migrate module: https://drupal.org/project/migrate

I don't know if it can do what you need out of the box, but at least in the issue queue there are discussions about migrating between fields and field collections.

Migrate Field Collections documentation page: https://drupal.org/node/1900640

Editing the database directly is rarely a good idea.


last night I'v found the problem and solve.

change the row in the file "charts_google.inc" row n. 223

from
       $format = $prefix . '#' . $decimal_count . $suffix;

to

  $format = $prefix . '#0' . $decimal_count . $suffix;


Ultimately this was answered in a different but similar question I asked. The answer is the code below attached to the field in my entity.

use Drupal\Core\Field\FieldStorageDefinitionInterface;

->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)


You can calc it with formula which is used by Fivestar on theme layer: http://drupalcode.org/project/fivestar.git/blob/refs/heads/7.x-2.x:/includes/fivestar.theme.inc#l132

$fivestar = field_view_field('node', $node, 'field_cg_rating');
$stars = 5; // Stars count from your field instance settings. Settings can be loaded with field_info_instance() if needed.
$rating = round(($fivestar['#items'][0]['average']/100) * $stars, 1);


You have to do all together, set cache max-age = 0 for all responses the controller returns and apply the kill switch

public function mycontroller() {

  \Drupal::service('page_cache_kill_switch')->trigger();

  if (!$a) {
    return [
      '#markup' => 'no',
      '#cache' => ['max-age' => 0],
    ];
  }

  return (new TrustedRedirectResponse($url))
    ->addCacheableDependency((new CacheableMetadata())->setCacheMaxAge(0));
}

and then clear the cache one more time.


height of block with view containing exposed filter

Some html element wrapping the block has a fixed height. This height gets set the first time you load the page and thereafter it does not change (it could be done by a jQuery script). You will need to hunt it down in your web dev tools and alter it with a CSS rule that sets the height to auto, or you might even have to do it via jQuery.

Try with another theme (bartik) and see if it also happens. If it does not then it is theme related.

If you cant get it fixed then I suggest you create a custom region just below the content region that is used solely for the block. Just use a div for the custom region and only set the width if need be. On a block level element the height should by default be auto.

Look here how to add custom region.


How to theme webform's Custom Composite element?

You can add classes like you do for any other element. The only difference is that in the case of custom composite elements, there are no fields for setting them directly. Instead, you can go to your respective nested element of Custom composite and set your classes like

'#attributes':
  class:
    - trip-departure-date

inside the custom property and theme accordingly. You can also use bootstrap class to change the layout.


Taxonomy fields in node default display using display suite

In Manage display of Product content type, select Rendered taxonomy term for term reference producer, then create taxonoy-term--producer.tpl.php to change style of the taxonomy.


Show PDF/print icons inside a template file

As the README.txt says

  Administration > Structure > Content types (admin/structure/types)
  For each content type it is possible to enable or disable the
  PF link via the "Show printer-friendly version link"
  checkbox. (default: enabled) It is also possible to
  enable or disable the PF link in individual comments via the
  "Show printer-friendly version link in individual comments"
  checkbox. (default: disabled)

API

print_insert_link(), print_mail_insert_link(), print_pdf_insert_link()

  The *_insert_link functions are available to content developers that
  prefer to place the printer-friendly link in a custom location. It is
  advisable to disable the regular Printer-friendly link so that it is
  not shown in both locations.

Take a look at THEMEABLE FUNCTIONS

It is a best Practice to read modules README.txt.


Migrate users from a table with non-unique email column

It depends on what kind of method, modules, tools you'd like to use to migrate the data as each of them might have their own settings for the kind of situation you had described.

If it's just a custom script migrating data between databases, then I would treat all users the same and import any of the tables first and then import the second one ignoring the error message - Drupal won't be importing users with the existing e-mail twice. After the migration you could go over each admin to assign appropriate role.


Ajax form in preprocess_node never triggers

You don't use the correct function for that;

function MYMODULE_form_alter(&$form, &form_state, $form_id) {
  if($form_id == 'selection_node_form' //and same condition you call your function){
    //do your changes here
  }
}

Or use drupal_retrieve_form then you can override the form.
The drupal_get_form call the function drupal_build_form which build the form, you can't override it that way.


As a related solution, it's much easier to execute a Rules Component programmatically. They're designed for that.

For example, consider a Rules Component (type "Rule") that accepts a $commerce_order parameter.

In this case, it happens to process a queued order item from a cron queue, pushing the order to a remote system via an API.

function MODULE_queue_iwi_push_instant_sale($item){
  try{
    if($order = commerce_order_load($item['order_id'])){
      // Invoke the rules component programmatically
      // passing the $order parameter
      rules_invoke_component('rules_iwi_push_instant_sale', $order);
    }
  }catch(Exception $e){
    watchdog_exception('my_module', $e);
  }
}

I like to think of Rules Components as similar to functions that can be called, passing parameters and potentially returning a value. They can do other magical things as well. See rules_invoke_component

Reaction rules on the other hand are event driven, triggered by some event such as node_save and passed the relevant parameters. See rules_invoke_event

More info on Rules Components here: https://drupal.org/node/1582182


Server Error 500 when changing pager of Views to display all items

Answering your last statement displaying multiple nodes at once is totally possible in Drupal. (Bear in mind though the power of hosting and caching is something to consider.) Unfortunately, the 500 error isn't helping a lot; a good approach is checking the error logs for any indications there.

If you are suspecting a PHP memory allocation error, try increasing the memory_limit variable in php.ini to a higher value. This link might be helpful.

Displaying thousands of nodes at once needs caching, so your site can be nice and quick. First, enable the caching in the advanced section of your View UI. Also consider using modules like memcache and boost.

As I said, first check what this 500 error you are getting is, because maybe it has nothing to do with the amount of nodes you are displaying.


How to perform a REST request after a node created using rules?

Guzzle is similar to Web Service Client and there is also Web Rules but I assume Guzzle would require some coding. Guzzle is a powerful HTTP client and library and itself can do whatever you want.

The reason there are few user interfaces to what you want is that they're annoying to build and add next to nothing to your client website. The UIs dont make the website any faster, they're just bloat.

This is why Views and ViewsUI are decoupled so you can turn 1 off in production environments.


How to determine the modules enabled on a third party website?

There are various you can find this out. But none of them are foolproof and they are just dirty tricks at best.

You can check source(view source) of the website and do the following.

Check the css includes in the head tag and figure out the modules from path.
Check the javascript includes in the head tag and figure out the modules from the path.
Check the classes of html tags from the body tag.
Do the above for multiple standard pages and you should be able to make a list of at-least 50% of the websites based on your knowledge of the modules.

But the easiest of them all is using the http://www.drupalxray.com/ website. Looks like they have automated many rules like the above and search enough paths to prepare a pretty exhaustive list of modules used on a website.


Instead of print rendering the individual items, you can try to build your form using the drupal_get_form core function, which allows Drupal to add all the extra components to the form (including the Ajax call).

So in your template it would like like this:

$output = drupal_get_form('mymodule_form');
print drupal_render($output);


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


Bulk import images into content image field

Why don't you make a new csv field for the images with a relative path to each image as the row value? Then when you import the nodes using Feeds, the image field will automatically have a link the the image


Error in drupal "Notice: Undefined index: extension in require()..."

There is not an sftp.inc in the filetransfer folder in Drupal core by default. Perhaps more information on your contributed modules in use, a custom module, Drupal version, etc. might help...


If bandcamp offers a method of embedding their players into other websites, you can open a request in the issue queue for the URL To Video Filter module (which I'm the developer of), with a link to their embed method, and I'll try to integrate it for you.


Why do the exposed filters in my view return to previous values after I change them?

You can select under each exposed filter, if Views should remember the selection or not. Remembering the last selected value will be stored as a session variable and persist until the user logs out etc.


Is it possible to select all results in Views bulk actions form?

The simple bulk action support in Drupal 8 core does not currently support this feature.


entityQuery condition for users without a role

Your original code is correct. The problem is condition of 'not in'. It doesn't give result of users who has no roles. If you give roles to each user you are good to go.

More reading

You can get deeper understanding from class file
   https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Condition.php/class/Condition/8.2.x

Also there is a Drupal 7 API documentation about conditional-clauses
https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses


Add javascript scolbar & effects to Block from module

It's probably bad usability because you would want your users to know that a block has scrolling content, but you could do something like this.

$(".block .content").hover(function(){
  $(this).css("overflow","scroll");
  },function(){
  $(this).css("overflow","hidden");
});


File to import not found or unreadable [omega 4] Windows OS

You can fix this by editing your Gemfile and changing:
gem 'sass-globbing'
to
gem 'sass-globbing', '1.1.0'

Then go back to terminal and type:
bundle

All should be fixed


Datetime retrieved from db is 7 hours off?

Date/times are generally stored in the database as UTC, so if your timezone is UTC -7 hours then all your times will be out by 7 hours (between the database and your expected output).

When you load a date from the database you then have to apply the desired timezone before displaying it or doing calculations on it or whatever.

For some examples you can see what the date module does with:
date_formatter_process() and
date_tokens()

It creates a new DateObject and then runs date_timezone_set($date, timezone_open($timezone)); on that date to set the timezone.

If you just want to use the site timezone (or user selected timezone) you can use date_default_timezone().

There is also the drupal core function format_date(), which takes a timestamp, a date format, and a timezone and gives you the output date.
That would be the easiest option.

For example, you might do this:

$okdate = format_date($nttdate, 'medium', '', date_default_timezone());


I did it setting my own headers (cache-control, last-modified, etag, expires), and setting rules for delete cache.


in drupal 7, how to add user pic and name to the user menu when logged in?

In Drupal 7, you can implement hook_block_view_alter() to alter the content of a block defined from another module. For example, menu_block_view_alter() is an implementation of that hook done by the Menu module.

function menu_block_view_alter(&$data, $block) {
  // Add contextual links for system menu blocks.
  if ($block->module == 'system' && !empty($data['content'])) {
    $system_menus = menu_list_system_menus();
    if (isset($system_menus[$block->delta])) {
      $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($block->delta));
    }
  }
}

$data is the array defined from the implementation of hook_block_view(), and it contains two array indexes:

"subject": the default localized title of the block
"content": the content of the block's body

In Drupal 7, $data['content'] could be either a string containing HTML code, or an array as accepted from drupal_render().

$block is an object containing all the data about the block loaded from the database. You can at least count on two elements:

"module": the name of the module implementing the block
"delta": the identifier for the block used from the module implementing it

If you just need to alter one single block, you can consider implementing hook_block_view_MODULE_DELTA_alter(), which is the equivalent of hook_form_FORM_ID_alter() of hook_form_alter(). Replace MODULE with the module name, and DELTA with the identifier for the block.
The hook gets the same parameters as hook_block_view_alter().


'File' class not found in submitForm(...) - uploading managed_file

You need to add it in a use statement in your class (at the top of the file with the rest of the use statements)

use Drupal\file\Entity\File;


How do I move more link to title of views block?

You should copy the views-view.tpl.php from views module into your theme folder. If you want to do this only for a specific views, you should also rename the file like views-view--your-view.tpl.php. Then you can simply move the 'more link' part wherever you like in this template file.

UPDATE:
Thanks to @Mołot's pointing about an issue that the title is rendered by the block, I've found out that there is already a discussion about that in the API page. As a workaround, you can set in the block configuration the title to <none> so that it isn't rendered by block. And in the views template replace the following part which is responsible for printing title:

<?php if ($title): ?>
  <?php print $title; ?>
<?php endif; ?>

with this:

<?php if (empty($title)): ?>
  <?php $title = check_plain($view->get_title()); ?>
<?php else: ?>
  <?php print $title; ?>
<?php endif; ?>


How to redirect language prefix to language domain (TLD)

I had the same issue and solved it by putting a 301 redirect in the htaccess file:

# 301 rewrite for all prefixed language nodes to their own domain
RewriteRule ^en/(.*)$ http://example.com/$1 [L,R=301]
RewriteRule ^de/(.*)$ http://example.de/$1 [L,R=301]

Then I generated a new sitemap and inserted it in the google webmaster tools. I'll monitor the performance impact of this solution. Update is coming in two weeks!


Panels is the right module to control this kind of layout. You should be using the node/%node panel in Page Manager and be overriding that.
http://example.com/admin/structure/pages/nojs/operation/node_view/handlers/node_view_panel_context/content

The documents should be uploaded to the Node during editing. If you are missing a field for Documents create a Documents field in the node Content Type of Field Type file. Allow it to have infinite values.

Return to Page Manager > Content. Add content into the right hand panel (using the gear icon). Choose Node and locate your Field: Documents. Add that.

Add your other content into the centre panel. Your left hand panel can be a block (for example a Menus block).


An AJAX HTTP error occurred. HTTP Result Code: 200

Increase your PHP max_execution time in php.ini


og_members block & og_nodes block won't display content

og_nodes and og_members did not exist prior to views 3 beta 3's release.  The user must have been using a dev version at this time because I was unable to reproduce this until views beta 3 came out today.


Looks like I found a possible answer. Use Google Analytics module and make sure to track internal search. Then setup your Google Analytics account like so.


Download and install the Better Exposed Filters module. This module provides a "Include Reset button" when you are creating a View.
Hope that helps.


One of the option is:

create a entity reference field in 'school' content type to reference associated contact form.
write a helper module that adds a menu item node/%node/contact.
Make sure access_callback check for your content type and return false for other node type to avoid any perf issue.
In menu callback function, render the entity form to display.

Here is an example of "node/%node/something" pattern from token module.

/**
 * Implements hook_menu().
 */
function token_menu() {
  ...
  ...

  $items['node/%node/devel/token'] = array(
      'title' => 'Tokens',
      'page callback' => 'token_devel_token_object',
      'page arguments' => array('node', 1),
       // 'node' => token_devel_token_object function gets a string 'node' as argument 1
       // 1 => token_devel_token_object function gets a node object of node id given in url. for mode details refer https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_load/7.
      'access arguments' => array('access devel information'),
      'type' => MENU_LOCAL_TASK,
      'file' => 'token.pages.inc',
      'weight' => 5,
    );

// page callback definition
/**
 * Menu callback; prints the available tokens and values for an object.
 */
function token_devel_token_object($entity_type, $entity) {
...
...
}


How to setup different confirmation email per webform instance

You can pass a custom confirmation message from a Webform node to the Webform email handler using a token like [webform_submission:node:field_confirmation_message]


How to hide "Log in or register to post comments" when I've already disabled displaying comments?

You also have to disable the "links" section or you'll see this message.
Go to the Administration > Structure > Content types > Article page. Drag comments and links to the disabled section. Repeat for any other content types where you want to hide this message.


sort views comments by vote result keeping thread

Main problem
Currently there is no way to tie all the children and grandchildren comments to the Main Parent (original/first ever parent). Also, need a way to separate the Main parent from all the children.
TL, DR Solution
Use the Views field view module to separate the children from main parent, and add all children as a field. That way, we are able to sort Main Parent's by Votes without affecting the children and grandchildren.
But there is no way to just show all children and grandchildren of a Main Parent CID; therefore, create a custom module to solve this problem, so we can use the view field technique.
Detailed Solution
Requirements:
Views field view, Entity API, Main PID (custom module below).

main_pid.info
name = Main PID
description = Links all children and grandchildren comments to the main parent by saving main parent cid into main_parent_pid field when comment is saved.
package = custom
core = 7.x

main_pid.module
<?php

/**
 * Implements hook_comment_presave()
 */
function main_pid_comment_presave($comment) {

  $pid = $comment->pid;

  if ($pid > 0){

    while ($pid > 0) {
      // Implements comment_load()
      $load_comment = comment_load($pid);

      $pid = $load_comment->pid;
      $cid = $load_comment->cid;

    }

    $comment->field_main_pid[LANGUAGE_NONE][0]['value'] = $cid;

  }

  elseif ($pid == 0) {

    $comment->field_main_pid[LANGUAGE_NONE][0]['value'] = 0;

  }

}

Now in comments add a new field called Main PID with machine name of field_main_pid. You can do this programmatically or using the Drupal UI (I will leave this up to you)

Now, hide field from display

In your view:
In fields, add Comment: Rendered Comment (Thanks to Entity API)

In fields, add Comment ID

Now add a new block

Click on block, and change the display name

In fields add Depth

In fields, add Comment: Rendered Comment (Thanks to Entity API)

The style settings will allow you to indent the children with CSS.
Example:
.depth-1 { width: 480px; margin-left: 10px; }
.depth-2 { width: 470px; margin-left: 20px; }

In Filter Criteria, add Content: Main PID

Only the Main parent has PID of 0, therefore, this will show all the children only
Then add Content: Thread in Sort and Main PID in Contextual Filter
So your Children View should look like this:

Going back to the first View:
In Filter Criteria add Main PID

This time equal to 0, since we only want the main parents.
Now in Fields, add Global: View (Thanks to Views field View)

Your Original/Main View Should look like this:
Important: Add contextual filter of NID here (forgot to do that).

Lastly, In Sort Criteria, add the Votes Value (Not shown on screenshot since I did not bother to install Voting API and Rate) and remove the default Post date.


Anonymous (and authenticated) users can both get the token from the same place. Try following these steps:

Get the token with a GET to ?q=services/session/token
Attach the token to your POST header under the name X-CSRF-Token
Make the POST call to register the user


The event you're looking to trigger is the onchange event. JQuery's val() does not trigger onchange automatically. You can either call change() or trigger the change event

$('selector').trigger("change");.

See Also: https://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery


Looks like the Domain Rules module provides a condition so that you could limit a configuration by a domain.


How to get collapse text to open below admin menu?

This is a CSS issue; what you need is to move the named anchors up a bit for administrators.

Here's a sample code:

/* If you are using the core Toolbar module. */
body.toolbar a[name],
/* If you are using the contrib Administration Menu module. */
body.admin-menu a[name] {
  position: relative;
  display: block;
  visibility: hidden;
  /* This value will be different for Toolbar/Administration Menu modules. */
  top: -30px;
}


How to loop over a list of Organic Group users using Rules

You don't need any of that php stuff tenken is saying.
Just install Rules, create a new rule reacting on a user joining a group and use the action "Get group members from group audience". For this to work, you'll have to add to the conditions in the rule that the node is in fact a group.


What are the reasons for images going missing without changes made?

There are known issues with the images after the security update of Drupal 7.20. I would suggest you to update the latest release if it is the case.
I would also check if there is a .htaccess file preventing access to the files or folders. I remember that there was a similar issue and it was related with a .htaccess file restricting access to the files under the path where the images are saved.


Here is what I ended up doing in a custom module if anyone else needs to do this

use Drupal\Core\Url;

function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  //contact page form
  if ($form_id == 'contact_message_feedback_form') {
    $form['actions']['submit']['#submit'][] = 'custom_module_contact_submit';
    dpm($form['actions']['submit']);
  }

}

function custom_module_contact_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    drupal_set_message('we sent a form woohoo');
    $url = Url::fromRoute('contact.site_page');
    $form_state->setRedirectUrl($url);
}


You shouldn't need contextual filters for this as nothing needs to be passed in via the URL.

It should work like this using regular filters:

Create a node view
Add a relationship for "Content: Author"
Add a filter for "Content: Type" and restrict to the specific content type you refer to.
Add a filter for "User: Current" and set it to "Yes".  This will be using the relationship you defined in step 2.
Click the drop down next to the filter criteria heading and click "And/Or, Rearrange".
Change the operator for your 2 filters to "Or". Then you will see on the right it says current user or content type. Then click apply. - Note that if you have other filters set you may have to click the "Create new filter group" button then add these 2 filters to the new group then use "Or" within that group and "And" for the rest.


When altering the submit button, the form does not work

I just had the same problem. All the needed was adding this.

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


There is a module that takes care of this called Login Destination.

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.

Also available for Drupal 8


There did not appear to be any way to do this easier, so I did it manually/hacky.


Display driving distance between coordinates

You can use The Google Distance Matrix API

If you want it to display in views there are a few ways you can implement it Either as a custom module, theme the view, or use the views php module.


looking for a slider module to use in the header

Try Views Slideshow. It is the most used and most flexible and you can create as many as you need.


I would do like this:

Define a new 'Restricted' View mode. Either manually with hook_entity_info_alter or with Display Suite.
Create a new Page in Page manager, using the by default available Node view.
Create two separate variants in the page.

The first one will use a selection rule on ´Role: Anonymous´ and ´Field Private event: True´. In this Variant, display the node with the 'Restricted' view mode.
The second variant will not need a selection rule, as it will be the fall through option. Here you show the node with the normal 'Full' view mode.

For making everything visible after a year , it sounds like either a hook_cron with some code in it, or perhaps a combination of some Rules with a VBO, which would flip the private field off after a year. Sounds like that might be a separate question though.


Completing the checkout process event isn't firing

Debugging is the art of eliminating possible causes for an issue. In this case, your issue could be because ... your rule is disabled.

As per the 'I've disabled all of the rules bound to the event "Completing the checkout process" ...', double check that the rule you want to fire is (still) enabled. If it isn't, then make sure to enable it (again).

Also, your question states "the e-Mail is never send": it could well be because something (different from your rule not firing) is wrong. So therefor, add an extra Rules Action to the rule you're struggling with, as the very first Rules Action, and which is only to "show a message on the site"", and with a message like "Bingo" (or whatever). Then rerun your testcase, and verify if you do get such "Bingo":

If you do, your rule has fired ... and your real issue is related to sending the eMail.
If you don't, (temporary) remove ALL Rules Conditions in your rule and retry. If in that case you do get a "Bingo", then your issue is related to one or more of your Rules Conditions (though the rule did fire).

The above is how I typically do most of my Rules debugging, in cases where some rule seems to not fire (stupid, but pretty effective).

If none of the above debugging tips helps ... then edit your question and include an export of the rule you are debugging (in that case I might further improve my anwer).


How to duplicate image file in the same folder

To add entry for a file to a file_managed table, you could use code like:

global $user;
$file = new stdClass;
$file->uid = $user->uid;
$file->filename = 'image.png';
$file->uri = 'public://path/to/file/image.png';
$file->status = 1;
$file->filemime = 'image/png';
file_save($file);
file_usage_add($file, 'mymodule', 'mykindofusage', $node->nid);

Code shamelessly stolen from this answer by Clive.

Now, if you are using a file_copy function, it should work all right and create these entries for you. But you should always check what's in return value ($file in your case). If it's FALSE, you should not call file_usage_add, but output a message to check watchdog entries for failure reason.

If you will tell us what's in your watchdog, probably in another question, we'll be able to answer with more details about the reason of failuer.


After update 8.7.0 seven admin theme can't find icons

Suggestions

I see that you are new to the community, so welcome. Here are some suggestions:

Make sure you performed the updates correctly (preferably using composer)

I see that you've already cleared cache (:

See if the files are actually there in your file system.

If you're not getting this problem on your dev env and only getting it on your server, see if the files are getting uploaded properly.
I had a similar problem and the reason was because of a .gitignore entry which was ignoring the icon files, so they were not getting committed and as a result, they were not being uploaded to the server.

If the SVG files exist on your server, see if you can access them by typing an absolute URL to those files

If not, then maybe there's something in your .htaccess or in your server config which is preventing you from seeing SVG files.

If all of the above don't work, please post a comment and I'm sure me / someone else will surely help.


how to use hook_views_query_alter() to modify where condition?

To add a new where clause you can use, add_where

For example :

$query->add_where(1,'taxonomy_term_data_node.tid', $value, 'NOT IN');


Constant Contact module puts subscribe checkbox on every user profile page

I found this same issue.  It is due to a bug in the module.  I have submitted an issue here and have attached a patch which fixes the bug.


Custom redirect specific page after edit

It is always a good habit to use l() to create links in Drupal. In your case, you can use the below code to create link.

l(t('Title'), 'node/' . $article->nid . '/edit', array('query' => array('destination' => 'node/' . $node->nid)));


How to use a view block in a dropdown menu item?

Try out for following modules

Menu Views

  Allows menu items to render views instead of links. This is useful for
  creating "mega-menus".

Menu Attach Block

  Menu Attach Block allows you to attach blocks to standard core Drupal
  menu items. This is especially useful for creating complex dropdown
  menus and mega menus.

  Any block can be used, including blocks generated by other modules.
  Blocks generated by Views are particularly good candidates for
  embedding.


How to restrict content access within a site?

1) How to create a specific set of users?

That's what you typically do by creating appropriate "roles" in your site, and then for each user, you assign appropriate "roles".

  2) How can I restrict the specific set of users to the forums, groups, etc...

Combine this with granting "Permissions" to "roles" (which are then inherited by all users with the appropriate role). E.g. you grant access to (selected) forums.

When it comes to "groups", there are typically these modules that get used for that:

The most commonly used is Organic Groups, for which there is a set of amazing video tutorials to Learn Organic Groups. Especially the video about "Basic Organic group setup" should help to get you going with it. Here is what you'll learn from it (quote from that link):

  How to create a content type that is used as groups – meaning containers for other stuff (content and other entities)
  How to modify a content type (Articles) to allow it to be posted to selected groups
  That the user creating a group by default will be the group manager
  How to add more members to a group
  That there is an example feature shipped with OG
  That groupness and group contentness is actually managed by special fields
  That group membership is actually also managed with a field (of the same type that tells what group a content piece belogs to)

For anybody who considers the Organic Groups module as rather complex (like me ...), have a look at the (fairly new) Group module as a possible alternative. Some more details about it (from its project page):

  Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).

  Groups instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.

The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

  ... you can already use Rules to:

  Add a new Group
  Create a new GroupMembership and save it (the equivalent of $group->addMember())
  Add or remove a GroupRole from a GroupType
  React on new GroupMembership or Group entities
  …

  What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.

  Useful Rules we may add could be:

  E-mail all members of a Group, optionally filtered by GroupRole
  Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"

  ...

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

Note:
It seems to me that "a particular school" (as in your comments below) would be a perfect with a "particular group" (no matter which of the 2 modules above you would use).


Id say its simple case of organisation and relevance. Hooks fit into three different categories, alter, process and theme so probably best to organise these into separate include files.

inc/
template.alter.inc
template.process.inc
template.theme.inc

If your going to add a class to a button in a certain contrib module or similar then obviously creating a custom module is overkill.

Probably the best strategy to have is to work on the theme layer and it will soon be apparent if its worth putting the relevant code into its own module. Either way, you have achieved what you wanted.

Does it matter where the code is? Probably not, it's a few checks or calls wherever it is. Your probably get many an argument on best practices from various developers on this.


There is Ubercart Product Minimum & Maximum

  Adds minimum, maximum and order in multiples limits on products.
  Checks that the quantity selected matches the limits during both Add
  To Cart and Checkout actions. Quantity checks are disabled when
  product is added to the cart as part of a product kit.

If you want to do it with code this is one way to do that.

You can make use of hook_add_to_cart to get the product add event.

To get the number of items use uc_cart_get_contents

The ides is

function <modulename>_add_to_cart($nid, $qty, $data) {
  $items = uc_cart_get_contents();
// Display a message if the cart has more than 5 products.
  $item_count = count($items);
  if ($item_count < 5) {
    drupal_set_message('Your cart Should contains more than 5 products to checkout !');
    // drupal_goto to product listing page
  }
  return $result;
}


Add trailing slash to URLs when generating Sitemap with Simple XML sitemap

You can use hook_simple_sitemap_links_alter() to change the links generated before the sitemap is saved.

function example_simple_sitemap_links_alter(&$links) {
  global $base_url;
  foreach ($links as $key => $link) {
    if ($links[$key]['url'] != $base_url . '/') { // Excluding base url
      $links[$key]['url'] = $link['url'] . '/'; // Here Trailing slash will be added
    }
  }
}

Before using the hook:

After using the hook:


This isn't a problem with the view. The url paths used for your tabs are using relative URLs (e.g. "node/$nid/group-forum") you need use absolute URLs (e.g. "/node/$nid/group-forum").

View

Forum

Members

You need to check the rendering logic in your theme templates to see where the problem lies.


Using theme_preprocess_node i'm trying to add a class to all images on the page

From what I can tell, hook_preprocess_node() won't let you add both classes and title attributes to images from image fields. Try using hook_preprocess_field() as in the example below:

function myTheme_preprocess_field(&$variables) {
  if (($variables['element']['#field_name'] == 'field_about_image') && ($variables['element']['#bundle'] == 'basic_page_with_pic')) {
    $variables['items'][0]['#item']['title'] = t('This is the title text that will display when hovering.');
    $variables['items'][0]['#item']['attributes']['class'][] = 'class1';
    $variables['items'][0]['#item']['attributes']['class'][] = 'class2';
  }
}

Be sure to clear your cache.


Found the solution.

The lat/long came from a different source and when the location module tried updating the lat/long I got NULL/NULL, because I was on the max amount of requests to google.

Solution was to set the 'source' column in the location table to 1, so the module thinks the value is overruled by the user. The lat/long doesn't get updated / reset to null anymore.


The NodeFamily module will allow setting a maximum number of nodes that can be created per user. However it doesn't provide per role maximum number settings.


For Drush 8.x (the last version compatible with D7), the drush command, drush pm-download, can either use HTTP (wget) or SSH (git@git.drupalcode.org) depending on your --package-handler argument. It defaults to HTTP.


How to get field values in rules condition from fetched entity

You have to first add conditions that allow the rule to know what fields are available.

To do this you can use combinations of the following conditions:

Entity exists by property
Entity has field
Entity is new
Entity is of bundle
Entity is of type

Those conditions help rules identify the entity and bundle so it can show the relevant fields.

You can then access those field tokens in subsequent conditions and actions.

For example, you might use Entity is of bundle "Event" to then get access to fields used on the event content type.

In your case where you only have access to he user/profile entity you would have to add a condition like above to determine the entity/bundle of the user/profile so that you could get access to the field that references the event.

Then have an action to load the event entity (you could use the action "Fetch entity by id") using the entity id in that field.

Then you could add an if condition in the actions (using the conditional rules module) and say if the fetched entity is of type "Event" then if the value of your field is "Open" then do your final action.

It's a bit complex but you should be able to achieve what you want using the conditional rules module.
I think though that this will only work if you have a field on the user that references the event.

If it is the other way around and you have a field on the event that references the user then it would work differently.

In that case I would use the "Fetch entity by property" action to fetch content where the checkbox field = "Open".


How to create a views listing of all groups including a join link in OG 7.2x

Add a field to your view of the type Content: Group - set the formatter to OG subscribe link - screenshots in this thread on drupal.org:

http://drupal.org/node/1816096


You need a where, condition always uses the value literally:

$db_or = db_or();
$db_or->where('nid = tnid');
$db_or->condition('tnid',0,'=');


How to map multiple existing term IDs to an entity

You need to use plugin sub_process. File yml have soure like this:

  field_prod_category:
    plugin: sub_process
    source: tids
    process:
      target_id: tid

and soure plugin need to prepare:

$tids = [
      'tid' => 806,
      'tid' => 635
    ];
$row->setSourceProperty('tids', $tids);


Is there an AJAX command I can use to debug PHP variables without breaking AJAX call?

As far as I know, there isn't such logging or "nulling" Ajax command. That doesn't mean you can't build any! I for example, have created some custom Ajax commands, and also a eval() so I can run some quick codes.

1: Define the JS action

You need to add a new JS  file, or merge as necessary. Note this document.ready event is important (this is just the definition, so no need to be a behavior).

(function($){
    $(function() {
        Drupal.ajax.prototype.commands.js_eval = function(ajax, data, status) {
            eval(data.script);
        };
        Drupal.ajax.prototype.commands.console_log = function(ajax, data, status) {
            console.log(data.var);
        };
    });
})(jQuery);

2: The Ajax render array

Assuming you are aware of the ajax_render() and JS renderable arrays, it's time to create your own custom command.

function mymodule_ajax_command_js_eval($script) {
  return array(
    'command' => 'js_eval',
    'script' => $script,
    'my_custom' => 'my custom value',
  );
}
function mymodule_ajax_command_console_log(&$var) {
  return array(
    'command' => 'console_log',
    'var' => $var,
  );
}

Above PHP function is not really a hook, and can be any name you want. For the sake of convention, I'm using ajax_command in the function name.  In the return array, command will be called from Drupal.ajax.prototype.commands scope. You can pass additional variables, and they will be in the data for JS to access (data.my_custom, data.script, likewise.)

3: Now call it!

Now that you have the JS and PHP ends, time to call the function!

$output = array();
// $output[] = ajax_command_append('#some_random_id_that_you_d_normally_use', $html);
$output[] = mymodule_ajax_command_js_eval("alert('Big Bang Theory S8!)");
$output[] = mymodule_ajax_command_console_log($stuff_you_d_normally_dpm);

print ajax_render($output);
exit;


Adding create, edit, delete link of referenced entity in same content type

You want a combination of inline_entity_form and Entity browser.

It's possible to create different browsers that consist of one or multiple views, dropzonejs upload forms (with the dropzonejs module), you could also integrate it with a create form I guess but there's no integration for that yet I think (within the entity browser, which is why you can use Inline Entity Form for that part directly in the widget9.

Entity browser doesn't have a UI yet to create browsers, but you can look at the provided demo module and adjust it to your neeeds.

Another example is the File Browser project. That uses an inline iframe, and not a dialog. And it's specifically for managing files/images.


Save a user field without calling hook_user_update

field_attach_update() may do what you need

https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_update/7

A comment on the API doc page mentions using it to update a node's fields without updating the node.

If your custom field isn't part of the user object, you may just need to use drupal_write_record to write your field data.


How to expire views cache in code or with rule?

I ended up using Views Cache Actions. It allows to use rules to expire a specific view or views displays when a certain event occurs (like user profile save).


There are a number of api/integration points for SDL Tridion, depending on your version you have:

SDL Tridion 2009 and previous -> TOM (Tridion Object Model) a COM+ API you can use in a .NET project.

SDL Tridion 2011 -> TOM (as before) or the SDL Tridion Core Service (.NET web service)

I'd recommend using these APIs to extract the information you need from Tridion into XML data in the structure that makes it easy for you to work with.

You can then use something like the services module http://drupal.org/project/services to process and import your XML.

Also maybe of use... SDL Tridion is a component based CMS and content is based on a specific Schema items.   A schema is likely to translate to a drupal content type pretty well, but if you're trying to achieve the sort of flexible layout that you can get from SDL Tridion (page/component templates) you'll likely need to be using the Panels module.. or something similar.

Let me know if you need some more information.


How to pass variable to a views template?

Replace this, with your function

public static function mytheme_preprocess_views_view(&$vars) {
  $vars['test'] = 'Filtertest';
  return $vars['test'] ;
}

Then use this short code on your twig view:

{{ test }}

or if wanna use it in something.php in your views:

dump(test )


How do I export the list of URL alias into an excel or csv?

This is easy with a query:

select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

If you are good with mysql, you can run this directly from mysql with your drupal database selected.

If you are using drush you can run the query this way from the command line when in your site's root directory:

drush sqlq "select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';"

If you have the developer module installed, you can run this with db_query in /devel/php:

db_query("select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';");

You can also run the above code anywhere in the code base that runs on page execution, and then remove it once you have gotten your csv.


Not able to get textfield value to generate a ajax dependent dropdown option

Not sure, but from the looks of it (I think) you need to set

$form['#tree'] = TRUE;

When building your form.


Drupal uses messages as the 'base' class for messages so this should work:

jQuery('h1').prepend('
Start
');

Note that you shouldn't escape double quotes inside a string unless the string is actually wrapped in double quotes.


If I am understanding you correctly, all you should need to do is go into the View UI and click on the clone link of the existing calendar view and then enter the new path in the page display and appropriate date field to use.

ADDITION:

based upon your comment below, you could set a variable in a preprocess hook to the output of this view, eg:

$vars['cal']=views_embed_view('calendar','calendar_1');

and then you would have $cal inside your template to use however you wanted.  If you needed this information inside of a node, eg in a text field that would be displayed between those paragraphs of other text, you could probably hook into nodeapi() and set it there on display of the node.  If you need it embeddable inside a field amongst other text, that gets trickier, but doable with a custom filter of your own (or http://drupal.org/project/customfilter might be able to do it with their php filter but I've not used it personally) but then you'd have something along the lines of [calendar] that your users could have inside of a text field that would be transformed into the calendar view output on view.

Regardless of any of the above, I have no idea what CSS style issues you would have to fiddle with, if any, or what to do with the previous and next links of the calendar and if they would also work or not as expected on this new page.


How to refresh all views in Panels with a time interval without page refresh?

I have done this in the past with the help of Views Auto-Refresh

Try the module and let us know if it work.


You can use hook_menu with type as 'MENU_LOCAL_TASK'. So that your menu path will be like 'user/your_path'.

Ex:

function my_module_menu($items) {
  $items['user/my-path] = array(
    'title' => 'Some title'
    'page callback => 'your callback',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

If you are using views to print this page, you can set menu as Menu tab in path options.


user relationship node access is not working

If you are using a view, and trying to constrain the nodes listed in the view to those posted by the currently logged in user, you would use a Contextual filter to accomplish it, not Node access or Content access.

Assuming you are using Drupal 7, edit your view and under Advanced add a Contextual filter. Select Content: Author: Uid, and when the configuration screen comes up, under When the filter value is NOT available select Provide default value and use the select list to choose User ID from logged in user.

Save your view, and it will only list nodes authored by the current user.


Drupal 7 Trying to create a "Today in History" view

Try to use hook_views_query_alter.

Even though, I think you can do it using only views without altering the query.
Maybe using Date Views module would help.


Accessing all VIEW data in a preprocess hook

The result array in the Views object contains the row information so yes, if you need to access the results, this is the way to do it.

For example, including:

function YOURMODULE_preprocess_views_view(&$variables) {

  $view=$variables['view'];
  drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

}

and then a quick View that just returns node objects would look like this:

and a View that returns fields (in this case just titles) would look like this:

and then when you actually include custom fields, you get that big _field_data array, eg:

but you should also see it in a more top level area of the results as well:

Also, a quick look at views_get_view_result() might shed some more "this is how we do it" confirmation/information on Views results.  Also What is the hook to preprocess a view and Changing values in preprocess view function talk about other options available to you in the Views API.


How to fetch all the details of a marketplace organization's page on Drupal.org

You can check with GET method with your URL.

GET https://www.drupal.org/api-d7/node/782.json


Can Drush be assigned as a ssh users default shell?

Drush has some sort of interactive shell - try drush php:cli. (You would created a script /usr/local/bin/drush-shell similar to git-shell.) However, I just tested and it doesn't seem to work for Drush 9. If you are still using Drush 8, it seems to work just fine (as drush core-cli). Disclaimer: I haven't actually tested this as a login shell.

The other more standard approach is to use lshell and set it up so Drush and needed tools can be used. I haven't tested this either - sorry.


How do I output the entire page template?

This is a wild guess but have you tried:

$html = array('page' => $message);
theme('html', $html);

(or something along those lines)?


Drupal's primary role is a CMS. For development tooling, it's probably more effective and more efficient if you build sprites without the use of Drupal. Drupal itself already has a very large memory footprint.

How to produce CSS sprites (2013/2014 Edition)

With today's rapid growth in development tooling and technology, here are just some ways of which one can produce sprites for your theme today:

Manually Manually edit them in photoshop and place them accordingly in the same file and write css for it. If this isn't clear to you. There's a plethora of information on how to do this: here, here, here, and yes there's plenty of more articles out there. Just search for "css sprites" in your favorite search engine.
Use Compass Compass, a Ruby Gem, allows one to automatically generate sprites. It's very well used and integrated in some themes today. For example, Zurb Foundation.
Grunt Spritesmith If you're familiar with using Grunt and have node already setup on your local machine Spritesmith is a viable option. Spritesmith allows you to create sprites within a folder for use of your theme.
CSS Sprite Generator - I quickly googled 'css sprite generator' and found this particular tool. Not sure if it's helpful but it seems as to allow you to build sprites online via upload.

Again, IMHO i'm pretty skeptical and think that outdated Drupal 5 sprite module will improve your front performance when you have to load one more module.


Custom block with a field value that can be used in other twig template

In a field template you find the parent entity in the variable element['#object'], from where you can get field values of other fields:
{% set field_foo_value = element['#object'].field_foo.value %}


hook form alter with hidden field, throw an error

The problem causing the error is that you are setting your hidden description field value is a string, but the taxonomy module is expecting a text area type array with a 'value' and a 'format', which you cannot replicate with a hidden field.

Unfortunately the term description field is a special property of the term, not a proper field, so you can't remove the field (the taxonomy module relies on it being there).

If you don't want people to see it and you always want it to have an empty value a good option is to restrict it from the user like this:

$form['description']['#access'] = FALSE;

but that doesn't allow you to change the value if you want to.

Another option is to use 'value' instead of 'hidden' as the type, like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  // Hide the desciption field and relations group field
  $form['description'] = array(
    '#type' => 'value',
    '#value' => array(
      'value' => '',
      'format' => 'filtered_html',
    ),
  );
  // Unset the existing relations fieldset.
  unset($form['relations']);
  // Set hidden values for all the sub-fields of the relations fieldset.
  $form['weight'] = array(
    '#type' => 'value',
    '#value' => 0,
  );
  $form['parent'] = array(
    '#type' => 'value',
    '#value' => 13,
  );
}

Note the changes to the relations fieldset too:

Since you only want to pass hidden values from the children of the fieldset just remove the fieldset altogether and then set the hidden values (be careful if using other add on modules that add fields to the 'relations' fieldset).

Because the fieldset wasn't using #tree the values passed through in $form_state will just be ['weight'] and ['parent'], not ['relations']['weight'] and ['relations']['parent'] so you can leave the ['relations'] part out when adding the values back in.


How to add another entity type to Search API multiple types index?

Not a proper answer, more like a workaround:

Load index.
Delete it.
Mark it as new.
Change the datasource settings.
Save it again.

Source: https://www.drupal.org/node/2632880#comment-11208443


force a different page template based on node id?

This ought to do it:

function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $vars['theme_hook_suggestions'][] = 'page__node__' . $node->nid;
  }
}

And then call your template file page--node--123.tpl.php


How to target non admin pages (front end) from a module?

You can use the path_is_admin() function to determine whether or not a path is an admin page, so you can just use the reverse to determine if it's a non-admin page:

if (!path_is_admin(current_path())) {

}


No menus being displayed in SideBar First

First of all, Menu works on the sidebar.

For your case, it's definitely the 'Permission' issue.

Permission for menu items: For example, you have only 'Add Content' item in the Navigation Menu. When you are logged in as an admin you have that menu on the sidebar as you have the permission to add a content. To display this item to authenticated/anonymous users you have to configure permission from 'Admin Menu' > 'People' > 'Permission'. Please check the permission of your menu items and configure as required.

Permission for Blocks: By default menu blocks have no permission restriction. Please check your menu block's permission section from 'Admin Menu' > 'Structure' > 'Blocks' > 'Edit' the specific block > 'Permission' tab at the bottom.

I hope it will help you.


Compare two same fields with time difference in Views, using node revisions

This is a bit of a hackish solution.

What you need to do it create a field which would be unique per node on all the revisions. You could use the Computed Field instead of the normal field to crate this field and use the code below to computed the field

if (!$entity->nid)
{
 node_save($entity);
}

$entity_field[0]['value'] = $entity->nid;

This would set the value of the computed field to the nid of the node so that you dont have to bother about setting a unique value.

Now in the views create a view of the type content revision. (This would be done by selecting content revision from the dropdown near Show

Add the fields for which you want the revision data. Use the one which says  (historical data) at the end of it.

Now add the contextual filter with the computed field we created earlier. make sure the select the one with (historical data) at the end of it.

In the filters you can choose Content revision: Updated date and select the date range you want. you can also provide relative values such as -7 days to get the all the values before 7 days.

The computed field was used because I was not able to get the nid of the revisions. If any one has a work around on that please do make the required changes.


To update the routes you have to call RouteBuilder::rebuild:

\Drupal::service('router.builder')->rebuild();

This is not what you want to run very often during normal operation of the site. This can take several seconds. It's also not possible to run more than one update process simultaneously. So routes are in general static, even the dynamic ones.


How to approach implementing a custom page header for each page

You might want to look at a solution using Minipanels.

Minipanels are basically Panels (shipped together) that can be used as a block.

You could create a minipanel with the required content and assign that block to the header region for a particular page.

Alternatively, you could set it up as a content type with an image, title and teaser and then a template or view mode to render it in the header.


Media is like any other entity based on ContentEntityBase in Drupal.

// top of your file
use Drupal\media_entity\Entity\Media;

// in a function
$media = Media::load($id);
// do stuff with $media
$media->save();

edit:

In a method of a class you would not want to use Media:: but instead use entityTypeManager service to load the entity:

$media = $this->entityTypeManager->getStorage('media')->load($id); where entityTypeManager is injected to your class.


Drupal Webform not submitting sometimes right after clearing cache

Turns out that this issue was happening to me locally so it wasn't Memcache or Varnish that was causing this issue.  It turned out to be a webforms module.

Because I was embedding the form on another node the '#action' value was incorrect.  I didn't run into this issue in the past because the code was updated on a newer version of webforms.

One fix is to use hook_form_alter() to change the action:

if ($form["#node"]->type == "stage_one_form" && !path_is_admin(current_path())) {
  $alias = "/" . drupal_get_path_alias("node/{$form['#node']->nid}");
  $form['#action'] = $alias;
}

Another fix is to run the patch I created here.


db_query or db_select for getting content type fields

If you have your node object, you can use field_get_items to get the field values from the node.

$items = field_get_items( 'node', $node, 'field_name' );
// now $items is an array of values... you can manipulate...
// then use the field_view_value to build the render array
$specific_item = $items[0];
$item_build = field_view_value( 'node', $node, 'field_name', $specific_item );

Here's a link to the field_view_value API doc.

Use the devel module and sprinkle in some dpm()'s to understand the underlying data. It's pretty neat! :)


See https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21CommentLazyBuilders.php/function/CommentLazyBuilders%3A%3ArenderForm/8.2.x.

You create a comment entity and then get its form.

<?php
$values = array(
    'entity_type' => $commented_entity_type_id,
    'entity_id' => $commented_entity_id,
    'field_name' => $field_name,
    'comment_type' => $comment_type_id,
    'pid' => NULL,
  );
$comment = \Drupal::entityTypeManager()->getStorage('comment')->create($values);
$form = \Drupal::service('entity.form_builder')->getForm($comment);


"An illegal choice has been detected. Please contact the site administrator." with exposed sort fields

I've solved by setting a default value in the form alter callback for views exposed form

function mymod_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'yourviewname') {
    $_GET['sort_by'] = 'default_sort_name';
    $form_state['view']->set_exposed_input($_GET);
    $form_state['input']['sort_by'] = $_GET['sort_by'];
  }
}


How can I add new components to a fieldset?

It looks like setting the pid to the parent fieldset's cid achieves my goal.


How to change Drupal's default "Unable to send e-mail." message?

You can use String Overrides modules for overriding any string that passed through t().
Here are some details about this module from its project page:

Provides a quick and easy way to replace any text on the site.
Features:

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


From WidgetBase::form:
// Most widgets need their internal structure preserved in submitted values.
$elements += ['#tree' => TRUE];

When customizing the structure you also need to make sure the values get submitted correctly. For example by adding WidgetInterface::massageFormValues to your widget.
A much easier way though is to keep the standard structure, which is using property names as form keys, and add the container by #prefix/#suffix:
$element['label'] = [
  '#type' => 'select',
  '#title' => t('Label'),
  '#default_value' => isset($items[$delta]->label) ? $items[$delta]->label : NULL,
  '#options' => $options_for_label,
  '#prefix' => '
',
  '#suffix' => '
',
];


How to add filters to a custom entity type listing page

The simplest way is create a view like "Content View"
More information can be found in /admin/structure/views/view/content
Another way, you can create a form expose for that EntityListBuilder


How can I apply some value with HTML tags to a form element?

Use css.

Example:

If your $form['name'] is a div with an id wrapper,

Fazeela

Include a css file in your module file, particularly in hook_init function.

function NameOfYourModule_init(){
   drupal_add_css(drupal_get_path("module", "NameOfYourModule") . "/mycss.css");
}

mycss.css file

#wrapper{
    font-weight: bold;
}


Views contextual filters taxonomy name 2 fields using same vocabulary

If I understand your question correctly, out of the box the easiest way is to add a Contextual Filter Content: Has Taxonomy Term Id. This one does not care whether you have 1 field or 20 that reference taxonomy terms.  Further details within are whether you want to match from URL on term id or term name, etc.

I came across your question whilst seeking an answer to mine How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary which I think is different.


Newsletter can do what you need. The description on the project page:

Multiple newsletters lists configurable on existing terms
Plain text or HTML out of the box.
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on a single page.
Users can customize the terms in the list they subscribe to.
Custom template per list.
Statistics (CTR and Open-Rate).
Drupal 7 only.

I'm using it on my site and it works like you've mentioned.


The form action url is placeholdered to make the form cacheable when used on different pages:

Drupal\Core\Form\FormBuilder::prepareForm

  public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
    $user = $this->currentUser();

    $form['#type'] = 'form';

    // Only update the action if it is not already set.
    if (!isset($form['#action'])) {
      // Instead of setting an actual action URL, we set the placeholder, which
      // will be replaced at the very last moment. This ensures forms with
      // dynamically generated action URLs don't have poor cacheability.
      // Use the proper API to generate the placeholder, when we have one. See
      // https://www.drupal.org/node/2562341. The placeholder uses a fixed string
      // that is Crypt::hashBase64('Drupal\Core\Form\FormBuilder::prepareForm');
      $placeholder = 'form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM';

      $form['#attached']['placeholders'][$placeholder] = [
        '#lazy_builder' => ['form_builder:renderPlaceholderFormAction', []],
      ];
      $form['#action'] = $placeholder;
    }

The placeholder is replaced before the cached page is delivered to the client. See FormBuilder::renderPlaceholderFormAction and FormBuilder::buildFormAction

The confusion in your debugging attempts is caused by placeholders being replaced not only in rendered forms, but also in debug output you put on the page via kint() or print.


Does Quick Edit function work for embedded entities?

It does work, for Nodes, when set to Show: Content | Full Content.
However, it does not work for Users. Fairly expected as when you go to a user page, ex: /user/1 there is no quick edit feature there to begin with.


How to remove the shipping flat rate for particular products in Drupal commerce kickstart?

Try using these modules:

Commerce Discount Product Category
Commerce Discount


Programmatically create new Schedule Updates Entity Reference on Node

Here is one example of how to add a ScheduledUpdate to your 'host' entity, in your case a node.

$scheduled_update = ScheduledUpdate::create([
  'type' => 'node__sticky',
  'status' => ScheduledUpdateInterface::STATUS_UNRUN,
  'sticky' => NodeInterface::STICKY,
  'update_timestamp' => $timestamp,
  'entity_ids' => [$eventId],
]);
$scheduled_update->save();
$node->promote_event = $scheduled_update->id();
$node->save();

Good luck!


Prevent empty  item in Views (HTML List format)

It sounds like you want to override the row style output so that it doesn't output the wrapping li tag. There are other posts on here asking about that process. To get started though, in views, expand the Advanced section and click "Theme" - a window will then pop up showing you information on the template files for your theme.


Creating Drupal nodes from Javascript (Drupal 7)

Here's a few things you can try. Your scenario may require customizations or other workarounds.

First, make a content type with an image field.
 Second, in hook_menu, register a path and callback and post the image with ajax. You will have to post your image data on this url.

function MODULE_menu(){
   $item['path/to/post/node/data'] = array(
       'page callback' => 'your_callback',
       'access arguments' => array('create <type> content'),
   );
}

Then, setup you callback as

function your_callback(){
    // Storing image data to file
    $success = file_put_contents($file_path,  base64_decode($_POST['image_data']));
    // Creating node
    if($success){
      $node = new stdClass();
      $node->type = '<type>';
      node_object_prepare($node);
      $node->title    = 'Node Created Programmatically on ' . date('c');
      $node->language = LANGUAGE_NONE;

      $file_realpath = drupal_realpath($file_path);
      $file = (object) array(
        'uid' => 1,
        'uri' => $file_realpath,
        'filemime' => file_get_mimetype($file_realpath),
        'status' => 1,
      );
      $file = file_copy($file, 'public://');
      // field_image is assumed as the machinename of your image field.
      $node->field_image[$node->language][0] = (array)$file;

      node_save($node);

      drupal_json_output(array('status' => 'OK', 'message' => 'New image node content is created'));
    }else{
      drupal_json_output(array('status' => 'FAILURE', 'message' => 'There is some issue in order to create new image node.'));
    }

}


Automatic Item Number Creation (For article posting as a Reference for Quick Searching)

Option 1. You can use an existing node ID (NID).

Each node already has an ID and can be accessed via /node/[nid], [nid] being the ID of the node. Or you can generate a path alias by inserting <?php print l('link', 'node/' . $nid); ?>, $nid being the ID of the node. To retrieve NID of a current node, insert <?php print $node->nid; ?> into node.tpl.php.

Option 2. You can also use the combination of Automatic Nodetitles and Token module. This will allow you to automatically generate node title with the values from the Token.

Once the modules are installed, go to Structure -> Content Types, click on Edit, next to your content type. While on the Automatic title generation tab, select to Automatically generate the title and hide the title field, and in Pattern for the title, post a token from the options below; see the image below. There are many options with tokens, such as Unix timestamp (my favorite), random numbers and more.

Update:

For a truly random serial number, instead of using the Token module, I'd suggest using uniquid(); it generates a 13 character long random serial, no duplicates. This would be my choice. To do so, put this into "Pattern for the title" field, don't forget to check "Evaluate PHP in pattern":

<?php echo uniqid(); ?>

If you have spare time, there is also a Serial Field and Universally Unique IDentifier module, which also generate unique values.


Drupal 7. Webform textarea with a html editor

This is fixed by enabling wysiwyg, ckeditor and webform_html_textarea

Thank you


Is there anyway 'odd' and 'even' classes can be attached to node teasers so that they can be striped with different colored backgrounds?

Looking at the node.tpl.php doc page, there seems to be a way that you can print this in a node template.

Put the following in the node.tpl.php file (if your theme has no node.tpl.php file, just copy from modules/node):

<?php print $zebra; ?>

You can use Views module to generate node lists in the exact same criteria that Drupal core front page has.

Install Views module
There is a Views template called "front page" that you can edit.
Just save the View and make sure you have set the front page to this new views based page.

By default, Views adds odd/even classes to the node list. You can toggle this feature in field settings. Choose "Row style" to "nodes" and under settings, toggle this feature.


EntityFieldQuery get total of paged results

As usual, I find an answer soon after asking :P

If anyone's wondering, there is a global $pager_total_items https://api.drupal.org/api/drupal/developer!globals.php/global/pager_total_items/7


Ajax example dependent dropdown callback

The issue was fixed by changing one of the fields in the Content Type to List(text) instead of node reference. After this the "Illegal choice error" disappeared.


There is drush views-revert, which alone will give you a list of views to revert, or can also take multiple views names as arguments, as in drush vr archive frontpage.

So far, nothing like that exists for Panels.

However, if you were to use the Features module to export the Views and Panels, instead of a custom module, you could use the drush commands that Features provides.


How do I inspect from a user's view how a given page element was created by Drupal?

Think Firebug for Drupal?

Try the Drupal for Firebug module and associated Chrome/Firefox extension :)


Have you take a look at conditionals fields, works great for node-form and can help you to build your own code.

Oskar


You can set the default value for the contextual filter through URL and then in your code use $view->set_arguments() to pass the argument.


Menu is not creating in admin/settings page?

function pricepackages_menu()
{
    $items = array();
    $items['admin/settings/favorites-quotes'] = array(
        'title' => t('Manage Quotes'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_settings'),
        //'access callback' => TRUE,
        'access arguments' => array('access administration pages'),
    );
}


How do I get an array of user roles to use in #options?

The correct function name is:

user_role_names()


custom node template involving the use of quick tabs in drupal 7?

Go forth and tabbify with Quicktabs 3.0 for Drupal 7 gives some good examples of how to add custom content to quicktabs.


Don't think its possible with just configuration and/or contrib modules.

I believe you have to override hook_views_query_alter(&$view, &$query) and add  $query->addWhereExpression based on the current nodes date field.

Dig in core/modules/datetime/src/Plugin/views/filter/Date.php function opSimple($field)  and perhaps core/modules/views/src/Plugin/views/filter/Date.php function opSimple($field) to see how they properly use the addWhereExpression


Yes. The field prefix is populated by the RequestContext:: getCompleteBaseUrl() method, the underlying property, completeBaseUrl, is assigned from $GLOBALS['base_url'] if it's set.

You'll have to test that out to see if that's the case for you, because you might have a web stack configuration that causes Drupal only to see unencrypted requests (e.g. HTTPS only handled at your load balancer / proxy server level), thus displaying the HTTP base.


Create an image slideshow with multiple image fields per node

You can achieve this using Views Slide Show.... See this example I've done here http://www.cnngo.com/hong-kong/visit/hong-kongs-temporary-june-4-memorial-museum-568132 which is using Views Slideshow (ThumbnailHover) + Simply Scroll Jquery Plugin. See images below...


Get term value from user field and set that value to new field

$node->$term definitely isn't what you want. Taxonomy references are stored by tid, so

$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

should work


Custom theme: variable not made available in menu template

I think that it might work if you do like this,

function mytheme_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['current_user_name'] = $user->getUsername();
}

Remember to clear the cache.

After debugging, we found out this this code worked, in the case somebody runs into the same issue.

function themename_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['attributes']['uname'] = $user->getUsername();
}


Is a content type or profile a better choice?

You can use a profile, or a content type to expose information about a person. The difference between them is that a profile is always about an existing user account on the site.
For example, if your site is about emergent artists that will have a user account on your site, then a profile can be used from those artists to expose information about themselves. If your site is about famous past artists, then a content type can be used to expose information about them.

The other difference is that profiles are usually created from the users who want to add information to their own account. (The other alternative could be a user with the permission to administer users that adds a profile for another user.)
With nodes, out of the box, it's more difficult to limit who can create a node associated to the account of another user.

As for linking content types to a user profile, it is possible to use the Views module to show a page that, for example, on user/%user/profile shows those specific nodes that contain information about a user.


Removing username from personal contact form

You can customize the email with hook_mail_alter(&$message).


Why is my custom parameter converter class not used?

I think the condition in applies() doesn't match with the route parameters, try this:

  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'coupon_code_converter');
  }


Captcha is not a valid form element in Drupal 8. Since you haven't listed if you are using any other contributed modules, I am not sure what or where #type => captcha comes from.

I advise using Mollom to do captcha handling for forms.

https://www.drupal.org/project/mollom


How to give image instead of text in pager?

See How to change text-links to image links in the pager.
By using the theme_image() function Drupal should nicely format the <img> tag, and output it to your theme. Well, this works, but unfortunately somewhere in this theme_pager() process a l() is telling Drupal to only output plain text here.

The trick here is not to rewrite your whole pager functions. Have a look at theme_pager_link(); this function is building all the links that are used by the pager functions. When you look closer to the l() formatting the output is done using the following code:

return l($text, $_GET['q'], array('attributes' => $attributes, 'query' => count($query) ? implode('&', $query) : NULL));

You'll see the options aren't setting the HTML output. So I placed the whole function in my template.php (changing theme_pager_link() to `landrush_pager_lin()k) with a different output:

return l($text, $_GET['q'], array('attributes' => $attributes, 'html' => TRUE, 'query' => count($query) ? implode('&', $query) : NULL));

Note 'html' => TRUE.

Now l() is allowing me to print HTML tags (images!) within the pager function.


The comment/%/delete menu entry is wired directly to the comment_confirm_delete_page form. You can modify it with with a hook_menu_alter, and change the function from drupal_get_form to a page callback of your own design that will just delete the comment.

Example:

In your module file you'd need:

function mymodule_menu_alter(&$items) {
  $items['comment/%/delete']['page callback'] = 'my_comment_delete_function';
  $items['comment/%/delete']['page arguments'] = array(1);
  $items['comment/%/delete']['module'] = 'mymodule';
  $items['comment/%/delete']['file'] = 'mymodule.pages.inc';
}

And in your mymodule.pages.inc file you'd need:

function my_comment_delete_function($cid) {
  if ($comment = comment_load($cid)) {
    comment_delete($comment->cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('content', 'Deleted comment @cid and its replies.', array('@cid' => $comment->cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();

    drupal_goto("node/$comment->nid");
  }
  return MENU_NOT_FOUND;
}


Horizontally sliding gallery with visible neighbors?

That technique is most often referred to as a carousel.

I would recommend Owl Carousel module (or as a stand alone library depending on how custom you need it) as it is highly configurable and has support for mobile devices as well.

You can check out their (non-Drupal) demo here.


hook_page_alter in Drupal 8:

According to the change record Added hook_page_attachments(_alter)() and removed hook_page_build/alter() you should use hook_page_bottom:

function hook_page_bottom(array &$page_bottom) {
  $page_bottom['mymodule'] = ['#markup' => 'This is the bottom.'];
}

You have another issue, theme() is no longer available. But this is another question as it is unclear what you are trying to do with it. Probably you should use the template in a render array $page_bottom['mymodule'] = ['#theme' => 'TEST'];.

In D8 all page elements are in blocks now. The best approach would be to provide the extra content in a custom block and place it in the block layout in the bottom of the page. See comment from @Kevin.


how to associate multiple nodes with one node

I recommend that you model this from an object oriented perspective. I would create the following content types:

Event content type (composed of event, overview, agenda, live broadcast maybe)
Speakers
Resources
Venue
Sponsorship
Registration

The reason for embedding overview, agenda and live broadcast to the event is because they are closely related to to specific event and creating separate content type for them would be expensive (because there is a very less probability that two event have the same agenda or overview).

Whereas other content types such as Speakers, Resources, Venue, Sponsorship, Registration can be regarded as separate content types, because:

To allow referencing the same content type by multiple event nodes i.e. for example, you will have a speaker who would speak in several events, or a resource that would be useful in several events hence, you will be avoid loads of duplication/inconsistency etc.
The other reason to create separate content type is to achieve low coupling and high cohesion. Speakers are different than events, the best way would be to reference than to embed a a list of speaker into event content type. Fields of a Speaker content type, does not directly relate to an Event (i.e. Database normalization perspective)

This would give you a clean set of content types that are linked with each other using references and can be queries very easily using views, contextual filters and relationship.

Good luck.


Creating secondary menus, that are different based on the page being viewed

If you want to have different layout on different pages you can use power combo Omega + Context + Delta.
Using this modules you can create different layouts, different menu items and other things on different pages without codding.

See tutorial and Theory


You only need an update hook if you want that your module can be updated on production sites already using the module. If you write a new module or the module is still in development you can simply reinstall the module. If you have data you want to keep during development use drush entity-updates after changing the code of the installed module.


How to alter the default user permisions based on a returned value after login?

user_role_grant_permissions can help you. Or you are using modules which grant permissions based on users not on roles? If yes, look into code of module which control permissions per user to find proper function


Show form message only on initial load, but not after submit

Try
if (empty($form_state->getUserInput())) {
  $this->messenger()->addWarning('Some info you should know before submitting this form.');
}

See the discussions here: Avoid repetitive API calling in form rebuild while submitting


add your css file through your themes's .info file

  stylesheets[all][] = myStyle.css


How to read the session cookie with javascript?

If your theme is somewhat standard, you should be able to look to see if the body has a class of "logged-in" or "not-logged-in" and key off of that.  Eg,

if ($('body').hasClass('not-logged-in')) {
  // do whatever you want for anon users
} else {
  // do whatever you want for logged in users
}

or if all in jQuery:

$('body').hasClass('not-logged-in').doWhatEverHere();

EDIT ADDITION DUE TO COMMENTS :)

It appears that drupal uses httpOnly with its cookie:

https://www.owasp.org/index.php/HTTPOnly

so you won't be able to access it from the client.  So..... given that, you might want to investigate setting your own cookie upon login and deleting it on logout and looking for that, but suggesting that makes me make Bill the Cat noises :)


How can i maintain the database for CMS in Bitbucket for a Drupal used website

No. many have tried to version control databases and it simply does not work well.

If you want to manage config, you can use Features, which can save config and variables to code.


Try specifing the file where your functions are located.

Even if those functions are in the same file as your #submit callback, the file path may be needed.

$batch = array(
  'operations' => array(),
  'finished' => 'user_delete_tickets_batch_finished',
  'title' => t('Processing delete user tickets'),
  'init_message' => t('Deleting user tickets is starting.'),
  'progress_message' => t('Processing...'),
  'error_message' => t('Deleting user tickets has encountered an error.'),
  'file' => drupal_get_path('module', 'your_module') . '/your_module.module'
);


How do I add an anchor attribute to a route?

Thanks everyone!

I have solution my for problem.
You just had to add it to this my_module.links.contextual.yml file.

regions.taxonomy_term.edit_form_header:
  title: Edit this block
  group: region_taxonomy_term
  route_name: regions.taxonomy_term.edit_form_header
  weight: 10
  options:
    fragment: 'edit-group-header'


Automated database history save and recovery Drupal 7

Take a look at Backup & Migrate Module:

  Back up and restore your Drupal MySQL database, code, and files or
  migrate a site between environments. Backup and Migrate supports gzip,
  bzip and zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database
  tables to a file download or save to a file on the server or offsite,
  and to restore from an uploaded or previously saved database dump. You
  can choose which tables and what data to backup and cache data is
  excluded by default.


Get the ID that for the node that has been just created

If you need to alter the value of a node field right after the node has been created, you don't need that code. You just need to implement hook_ENTITY_TYPE_presave() and verify the node is new.

function mymodule_node_presave(EntityInterface $entity) {
  if ($entity->isNew()) {
    // The node has been created.
    // Access the node field using $entity.
  }
}

If then, for any reason, you need the node ID, you can access it with $entity->id().

I used hook_ENTITY_TYPE_presave(), assuming the node needs to be saved with the new field value.


Custom warning on when viewing cart (anonymous users)

The easiest way is overriding a default cart page template (cart page has been created with Views module, name - 'commerce_cart_form', display - 'default');

Create a template for Style Output
Copy the content of it
Views module provides logged_in variable in template_preprocess_views_view(&$vars) function, so you can check with that variable and display a text;

example (views-view-table--commerce-cart-form--default.tpl.php):

<?php if (!$logged_in): ?>
  MY MESSAGE FOR THE ANONYMOUS
<?php endif; ?>

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
  // Rest of code from Style Output
</table>


How do I disable the "Flood attempts IP blocking" functionality?

What you can do is adding the following code in the settings.php file.

$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;

In this way, the IP will not blocked.

user_login_authenticate_validate() contains the following code.

  if (!empty($form_state['values']['name']) && !empty($password)) {
    // Do not allow any login from the current user's IP if the limit has been
    // reached. Default is 50 failed attempts allowed in one hour. This is
    // independent of the per-user limit to catch attempts from one IP to log
    // in to many different user accounts.  We have a reasonably high limit
    // since there may be only one apparent IP for all users at an institution.
    if (!flood_is_allowed('failed_login_attempt_ip', variable_get('user_failed_login_ip_limit', 50), variable_get('user_failed_login_ip_window', 3600))) {
      $form_state['flood_control_triggered'] = 'ip';
      return;
    }
    $account = db_query("SELECT * FROM {users} WHERE name = :name AND status = 1", array(':name' => $form_state['values']['name']))->fetchObject();
    if ($account) {
      if (variable_get('user_failed_login_identifier_uid_only', FALSE)) {
        // Register flood events based on the uid only, so they apply for any
        // IP address. This is the most secure option.
        $identifier = $account->uid;
      }
      else {
        // The default identifier is a combination of uid and IP address. This
        // is less secure but more resistant to denial-of-service attacks that
        // could lock out all users with public user names.
        $identifier = $account->uid . '-' . ip_address();
      }
      $form_state['flood_control_user_identifier'] = $identifier;

      // Don't allow login if the limit for this user has been reached.
      // Default is to allow 5 failed attempts every 6 hours.
      if (!flood_is_allowed('failed_login_attempt_user', variable_get('user_failed_login_user_limit', 5), variable_get('user_failed_login_user_window', 21600), $identifier)) {
        $form_state['flood_control_triggered'] = 'user';
        return;
      }
    }
    // We are not limited by flood control, so try to authenticate.
    // Set $form_state['uid'] as a flag for user_login_final_validate().
    $form_state['uid'] = user_authenticate($form_state['values']['name'], $password);
  }

The limits are actually two: one for the case Drupal always has an IP, and one for when Drupal has also a user ID. The latter is for the case the user enters a username for an existing account; in that case, Drupal register the user ID, and the IP.
If you want to avoid also that case, then you need to add also this line to the setting.php file.

$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;


How to print alt or title field image in custom block programmatically?

You can load the node and then fetch the paragraph targetid . Later you can load paragraph targetid and then get all attributes of the image.

use Drupal\paragraphs\Entity\Paragraph;
use Drupal\node\Entity\Node;

$node = Node::load($nid);
$paragraph_field = $node->get("field_paragraph")->getValue();
$paragraph = Paragraph::load($paragraph_field[0]['target_id']);
$image_alt = $paragraph->my_image_field->alt;
$image_title= $paragraph->my_image_field->title;