Add inline JavaScript to end of page dynamically

You just use the following code.

$build = [
  '#markup' => 'SOME WEIRD ADS HTML HERE',
  '#attached' => [
    'library' => ['mymodule/mylibrary'],
  ],
];

Follow Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module to learn how to define a library for Drupal 8, and keep in mind that, by default, JavaScript files are added to the footer, as explained in LibraryDiscoveryParser::parseLibraryInfo().

  By default, JavaScript files are included in the footer.

Also, #markup is filtered out, as explained in Render API overview.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (For example, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.


Can an AJAX form request replace elements of different types?

I should try using #prefix/#suffix for wrapper instead the element itself. Also IMHO it's not a good idea mess around with the elements you send during build. Take in mind the the build is done every time you render the form, even for AJAX calls. A possible solution could be hide the second element using Form States API and put the Please make selection in your prior element.

public function buildForm(array $form, FormStateInterface $form_state) {
  // Code excerpt.
  $form['job_id'] = [
    '#weight' => 1,
    '#title' => t('Job'),
    '#type' => 'select',
    '#empty_value' => t('Please select a job'),
    '#options' => $formatted_jobs,
    '#ajax' => [
      'callback' => [get_class($this), 'showFiles'],
      'wrapper' => 'ajax-wrapper',
      'event' => 'change',
    ],
    '#required' => TRUE,
  ];

  // Render a hidden and empty list.
  $form['jobfiles'] = [
    '#weight' => 2,
    '#title' => t('Files'),
    '#type' => 'item_list',
    '#items' => [],
    '#prefix' => '
',
    '#suffix' => '
',
    '#attributes' => [
      'class' => ['invisible']
    ]
  ];

  return $form;
}

public function showFiles(array &$form, FormStateInterface $form_state) {
  $job_id = $form_state->getValue('job_id');
  $form['jobfiles']['#items'] = $this->_files((int)$job_id);
  // Remove the 'invisible' class.
  $form['jobfiles']['#attributes']['class'] = array_filter($form['jobfiles']['#attributes']['class'], function($v) {
    return $v != 'invisible';
  });
  // You could also return the element instead.
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('#ajax-wrapper', [$form['jobfiles']]));

  return $response;
}

Hope this may help you.

Update:
Replace $element with $form. Also worth checking the answer provided by @joshua-moore as it is valid too.


The warning appears because public://field/image is not included in the list of directories the open_basedir allows. Links are resolved, but an external path like public://field/image is not resolved to an internal path; for example, if the code is trying to read http://example.com/img_png/image.png and img_png is listen by the open_basedir directive, the warning will be shown.


It is common in pretty much every software project. It makes no sense to release a new version for every single change unless it is critical enough (e.g. security fix). So releases are e.g done on a regular schedule (Drupal core does one every month now).

It is common practice to list the issues that where implemented/fixed as part a release in the release notes.

There are usually multiple commits every day on Drupal core, imagine there would be a new version every time.

What's somewhat uncommon with Webform is that it they don't list their development snapshot releases on the project page. Those are automatically updated twice a day if there have been any commits. In case of Webform, that snapshot still exists, but, according to the description, should only be used for testing recently fixed issues: http://drupal.org/node/730862.

The quality of development snapshots can heavily vary between projects so it's generally not recommended to use them. One exception for example is if you encounter a bug in a module then it often makes sense to test the snapshot first if there is a newer version than the last release.


Views - Edit, view, delete node in dropdown

This can be achieved through contextual links. You can add new links through a custom module or with the Custom Contextual Links module (CCL).


Irreversible error when trying to upload image (too big) in a clone

What module are you using to clone a node? I recommend the Replicate module A workaround on your case now would be to alter the replicate functionality for the replication of image fields. You can clear the images field in code or copy the files yourself.

Here is an example for the replicate module to copy the images so your nodes don't use the same images because then you have unwanted behaviour on delete of one of the nodes (deletes the images):

/*
 * Implements hook_replicate_field_FIELD_TYPE().
 */
function replicate_custom_replicate_field_image(&$replica, $entity_type, $field_name) {
   // List of affected fields.
   $fields_list = array(
     'field_xxxx' => 'contenttype1',
     'field_xxxxx' => 'contenttype2',
     'field_xxxxxx' => 'contenttype3',
     'field_xxxxxxx' => 'contenttype4',
     'field_xxxxxxxx' => 'contenttype5',
   );

   if (in_array($field_name,  array_keys($fields_list))) {
     // Fetch field instance info.
     $field_instance = field_info_instance($entity_type, $field_name,           $fields_list[$field_name]);
     // Build destination path.
     $destination_path = 'public://' . $field_instance['settings']['file_directory'];
     foreach ($replica->{$field_name} as $language => $field) {
       foreach ($field as $key => $value) {
         // Fid can't be empty.
         if (!empty($value['fid'])) {
           $new_file = file_copy((object) $value, $destination_path);
           $replica->{$field_name}[$language][$key] = (array) $new_file;
         }
       }
     }
   }
 }


The variable you wish to test is $is_front, which is only true for the front page.

You can find a list of the variable available for page.tpl.php here.


How to add class only to top level ul in main menu

That example is missing some code.  Those two empty strings should not be empty.

There is a link on that page just above the code example to api documentation of theme_menu_tree() https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/7.x

On the api documentation page you can see it done correctly:

return '
' . $variables['tree'] . '
';


Indeed, setting maximum allowed packet size in MySQL worked like charm. To solve, we've went to the [mysqld] section of my.ini and added the following:

[mysqld]
max_allowed_packet=100M

then restarted the Windows server machine in order to restart MySQL.

The only difference in IIS is that the machine required a boot.


Routing path with Entity Reference field

The problem here is that controllers are specifically intended to return a result based on a given path. The result you want isn't dependent on a path, but rather on an operation performed on an entity.

What you'll want to use instead is one of the entity API hooks, found here: Entity CRUD, editing and view hooks

To respond to your entity being created, I recommend using:
hook_ENTITY_TYPE_insert()

function my_module_node_insert($node) {
  // Get ids for all Paragraph references stored in your field.
  $paragraph_ids = $node->get('field_paragraph')->getValue();
  // Get Paragraph storage handler.
  $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
  // Load Paragraphs from their IDs.
  $paragraphs = $paragraph_storage->loadMultiple( array_column($paragraph_ids, 'target_id') );

  // Iterate through your loaded Paragraph instances...
  foreach($paragraphs as $paragraph) {
    // Do your stuff to the paragraph.
  }
}

Similarly, if you need to update field_paragraph when you update your node, implement hook_ENTITY_TYPE_update().


How to know user submitted first content of a specific type?

While given answer works great, there are usually a variety of different methods to achieve your goals, one solution could be usage of a combination of Views and Views Bulk Operations (VBO) modules to achieve that

Create a view containing nodes of your desired type
Add a contextual filter and limits results to nodes written by logged in user
add a VBO view mode
in rules you can load a VBO items (check how)
Now if array is empty, created node is the first node of that type which the user has submitted

You also might do all the job with Rules, if you don't want this feature for many content types you can add a Boolean field to the user's account with default value of 'False' indicating if user has written his/her first content of desired type, then on node submit event you can check this field to recognize if this post is his/her first post of that type or not. Remember to set this field to True after submission of first content of desired type.

  The above approach saves some processing cause needs no query as it
  calculated once and used many times

You also can write a custom rules event (API), containing a query on nodes table with condition node.uid == user->uid and node.type == "TYPE_MACHINE_NAME", then if query is not empty, that means user has already submitted a content of that type. so return False.


Your controller is in a new request. If you stored the data in the database retrieve it from there. If you did not store the data in submit in some place it is no longer available. You could use a session variable or a url query parameter to transfer the data from the form submit to the controller:

public function myFormSubmit($form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect('route_to_controller', [], ['query' => [
    'Tel_number' => '123456789',
  ]]);
}

and the controller

public function showNumber(Request $request) {

  $build['test'] = ['#markup' => $request->query->get('Tel_number')];

  return $build;
}


Yes, hook_mail_alter() enables you to alter any email messages sent out from hook_mail() if you know the specific key associated with the email. In this case, the key is user_register_no_approval_required. From that point, all you have to do is parse the email message body for the relevant URL and save it to your desired location.

function MYMODULE_mail_alter(&$message) {
  if($message['id'] == 'user_register_no_approval_required') {
    //@TODO: Parse $message['body'] for email verification link and save it
  }
}


Body Summary field showing literal ampersand character code in view

This is to confirm and clarify the issue according to my findings.
1. I was able to reproduce your findings by using a fresh Drupa 8.7.3 install and after importing your view in which you used the {{ body__summary }} rewrite.

2. I was able to reproduce the error by enabling Display any HTML as plain text option in Basic HTML text format.
3. I was also able to reproduce the error by rewriting the view field output and choosing {{ body__value }} which basically prints the raw value of the body field.

My opinion is that 2 & 3 are normal behavior and it should be expected that in these particular cases the raw HTML is displayed. However, in 1, it seems a bug because the summary shouldn't be displayed as raw HTML; it should follows the same rules as the selected format.
I suggest to open an issue in Drupal issue tracker telling them about 1; maybe there is a reason behind this behavior, or if somebody already knows the answer, please elaborate.

Regards


How to add conditional javascript to theme?

This is how I've added html5shiv in my template.php file:

$html5shiv = array(
  '#tag' => 'script',
  '#attributes' => array( // Set up an array of attributes inside the tag
    'src' => drupal_get_path('theme', 'mythemename') . '/js/lib/html5shiv.js',
  ),
  '#prefix' => '<!--[if lte IE 8]>',
  '#suffix' => '</script><![endif]-->',
);
drupal_add_html_head($html5shiv, 'html5shiv');


How to change a node field when the output of a View changes?

Implement something like hook_views_pre_render() or hook_views_post_execute() and, every time your "Top 3" view is executed have your code iterate over the results and update the "Highest Ranking" field for each of the nodes in the top 3 as needed.

The only downside of this is that if your "Top 3" view is rarely ever executed then it's possible that a node could move into then back out of the Top 3 without the view ever being executed and thus without your code ever recording the node's presence in the top 3.  If you want to try to avoid this you might implement hook_cron and programmatically call your view every time cron is run.


Get menu link item from MenuLinkTreeElement

You can get the menu link content entity by accessing the uuid with the method getDerivativeId() of the plugin:

if ($link instanceof \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent) {
  $uuid = $link->getDerivativeId();
  $entity = \Drupal::service('entity.repository')
    ->loadEntityByUuid('menu_link_content', $uuid);
  $field_value = $entity->field_example->value;
}


Drupal 7 user register form in overlay on page load

I you need something like this site http://www.hospitalsreview.com/ has done for the sign up then you should try my module it will surely help you as you can see it is working on my site.

Sign Up Module


Add some custom fields in Views exposed filters and preserve their data to Url (GET)

I think I found it! I got to the the Views' theme folder and did what exactly I show here!

Then the data-passing through different pages needs some script and is done!


Increase weight range for child pages in book outlines (Book module)

Many people agree it's a big accessibility problem, but it isn't easy to solve and there always seem to be some obstacle.

I just posted about this, possible duplicate, very relevant for this question because the listed issues mention various methods on how to approach solving this and the obstacles you might encounter: How to increase book weight range for a same-level chapters.

The simplest way to solve it might be to rely on an outside sorting method, like Weight, and not on overriding the Book module. I don't have enough expertise to evaluate the difficulty level to modify the Book code, it just seems that way reading the lines and between them on those threads.


Why don't you use entity metadata wrapper?  your code will be:

$node = menu_get_object();
    if ($node->type == 'trailer_videos'){
           $wrapper = entity_matadata_wrapper('node',$node);
           $mynode = $wrapper->field_trailer_video_of->value();
           return $my_node;
     }

If you don't want to use entity module, use kpr of devel module to get the right syntax, as Ollie said quotes are needed.


How to create a list of users who did not submit some webform?

Step 1 - Introduce a webform submission flag

Install/enable the Flag module.
Navigate to /admin/structure/flags/add/node and create a flag (do not check the "global" checkbox). Let's assume you label it something like "Webform submission". For "Bundles" (on the same form), check "Webform".

Here is such Flag definition (in export format) you could use for it (just import it in your own site):

$flags = array();
// Exported flag: "Webform submission".
$flags['webform_submission'] = array (
  'entity_type' => 'node',
  'title' => 'Webform submission',
  'global' => '0',
  'types' =>
  array (
    0 => 'webform',
  ),
  'flag_short' => 'Webform submitted',
  'flag_long' => 'Indication that the Webform was submitted already',
  'flag_message' => 'Webform submission recorded',
  'unflag_short' => 'Webform NOT submitted',
  'unflag_long' => 'Indication that the Webform is not yet submitted',
  'unflag_message' => 'Webform submission recording removed',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 0,
    'teaser' => 0,
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

Step 2 - Register webform submissions

Install/enable the Rules module and create a Rule to flag the webform when it is submitted (by the user who submitted the webform and using the flag "Webform submission" (from Step 1).

Here is such Rule definition (in export format) you could use for it (just import it in your own site, which you can do if you have the 'Rules UI' enabled):

{ "rules_flag_a_submitted_webform" : {
    "LABEL" : "Flag a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "node:nid" ], "value" : "5" } },
      { "user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "webform_submission",
          "node" : [ "node" ],
          "flagging_user" : [ "user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 3 - List the webform submissions

Create a view (using the Views module), to list the user who have yes or no flagged the webform with the "Webform submission"-flag from Step 1).

Here is such Views definition (in export format) you could use for it (just import it in your own site, which you can do if you have the 'Views UI' enabled):

$view = new view();
$view->name = 'webform_submissions_by_users';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Webform submissions by users';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Webform submissions by users';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Flags: User's flaggings */
$handler->display->display_options['relationships']['flag_user_content_rel']['id'] = 'flag_user_content_rel';
$handler->display->display_options['relationships']['flag_user_content_rel']['table'] = 'users';
$handler->display->display_options['relationships']['flag_user_content_rel']['field'] = 'flag_user_content_rel';
$handler->display->display_options['relationships']['flag_user_content_rel']['required'] = 0;
$handler->display->display_options['relationships']['flag_user_content_rel']['flag'] = 'webform_submission';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: Flags: User uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'flagging';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'flag_user_content_rel';
/* Field: Flags: Flagged time */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'flagging';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['relationship'] = 'flag_user_content_rel';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'long';
$handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
/* Sort criterion: User: Uid */
$handler->display->display_options['sorts']['uid']['id'] = 'uid';
$handler->display->display_options['sorts']['uid']['table'] = 'users';
$handler->display->display_options['sorts']['uid']['field'] = 'uid';
/* Filter criterion: Flags: User uid */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'flagging';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['relationship'] = 'flag_user_content_rel';
$handler->display->display_options['filters']['uid']['value'] = '';
$handler->display->display_options['filters']['uid']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator_id'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['label'] = 'User uid';
$handler->display->display_options['filters']['uid']['expose']['use_operator'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
$handler->display->display_options['filters']['uid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'webform-submissions-by-users';

Fruit of your labor

If you import the above definitions of the flag, the rule and the view, and you have a few users submit the webform (= record their data), you can visit the relative path in your own site, which should then display a table that looks similar to this example:

Name            User uid   Flagged time
--------------+----------+--------------------------------
Demo.User     !          !
Famous.Dries  ! 8        ! Wednesday, May 11, 2016 - 19:13
Pierre.Vriens ! 19       ! Wednesday, May 11, 2016 - 18:07

For the above example, user "Demo.User" had not yet submitted the webform. The view contains an exposed filter so that you can limit the display to only those who submitted the form, or those who did not yet submit the form.

Start nagging users

If you would enhance your view from Step 3 with the Views Bulk Operations module, and you'd create a Rules Component (using the Rules module) to send an eMail, you could use it to eMail all those users in that view with some type of nagging eMail like "Please record your data...".

What's next?

The above doesn't take into account any webform submissions from before the above logic is implement. However it should be pretty forward to use a mixture of the above (4) modules, including VBO, to perform such one time only update (to also flag the users who already submitted the webform in the past). Anybody interested in knowing about that: Ask (a followup) Question ...


Get current currency symbol in drupal commerce

With Drupal 7, if you want to get the default (current) currency you can use  the following code.
$cur = commerce_currency_load();
$sym = $cur['symbol'];


How to add attributes to a specific field's image

One quick way of achieving this is to preprocess the field before it reaches Twig (in MYTHEME.theme) like this:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_field(&$variables, $hook) {
  if ($variables['field_name'] == 'field_avatar') {
    if (!empty($variables['items'])) {
      foreach ($variables['items'] as $delta => &$item) {
        $item['content']['#item_attributes']['class'][] = 'foo';
      }
    }
  }
}

Core's template_preprocess_image_formatter() then takes care of putting #item_attributes and the class into the <img> tag for you.

The normal way of offering alternative template names based on context is
implementing hook_theme_suggestions_HOOK() or hook_theme_suggestions_HOOK_alter(). In this case the latter as MYMODULE_theme_suggestions_image_alter().

But the problem here is that there's not much context about the field which will eventually wrap this image at this point. template_preprocess_image_formatter() only carries through the attributes that will end up on the image element itself.

You could be a bit sneaky and use the fact that we have already put the class (or some other identifier) into #item_attributes when preprocessing the field and use that to generate a new template name for the image once it gets to be rendered:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(&$suggestions, $variables) {
  if (!empty($variables['attributes']['class'] && in_array('foo', $variables['attributes']['class'])) {
    $suggestions[] = 'image-foo';
  }
}

It has the side-effect of adding an extra class (or other attribute) in your tag by default, but since you could now create image-foo.html.twig you could probably compensate for that in the template by removing it there if absolutely needed.

Now just make sure your "field identifier" is fairly unique (and recognizable) so you can figure out where that template suggestion in your theme debug output comes from in the future.


List nodes with Views 2 module, despite nodes having restricted permissions

Is there any way to update to Views 3? Because in views 3, under the Advanced > Other section you can change the Query settings options and make sure the Disable SQL rewriting checkbox is checked.


Change the rendered output of a Message entity

See the Messaging documentation, specifically this overview on new features. You likely want to override the tokens provided using a callback which is supported by the module:

  Callbacks: sometimes we can’t use the token system, for example if we
  need to show different results based on the value of _two different
  fields. This is an advanced feature, which is meant for developers,
  and is documented in the module.

I've not done this myself yet, but I've used the Message module and Views -- digging through the module and documentation should get you there now that you know it's possible.

From the message_example README it sounds like you want an activity stream:

  The UAS (User activity stream) view is dependent on Panels, as it uses
  "Panel fields" as a row plugin, along with the Message's partials.

Which you should be able to look at for inspiration in the example module.


How to redefine / override the default breakpoints in a Bootstrap sub-theme

There doesn't currently seem to be anything in the Bootstrap theme that supports this directly, and the theme doesn't appear to listen to anything in the Breakpoints module. The bootstrap breakpoints are hard-baked into the JS and CSS.

If you're not using LESS, this means the only realistic option is to override the CSS and JS with custom local files. I had a bit of trouble with this at first but it seems to be fine and doesn't seem to conflict with anything in the server-side theme code.

Create a customised version of Bootstrap with your breakpoints and other preferences, from http://getbootstrap.com/customize/
Install the module Bootstrap Library
Upload the custom bootstrap files to sites/all/libraries/bootstrap
Disable everything to do with CDN in your theme settings page


There are two module to control node access by user type. Node_Access_1 & Node_Access_2. Use which ever suits you. You will have to set the permission by editing each node, as I have implemented one from it in D7. I have never tried for VBO with it, so can't answer about multiple change..


I think your code is good enough to send email, but you need SMTP server to send the mail (which you has not specified), in case you have a mail server , the easy solution is install SMTP module which needs the SMTP server address and your are good to send email.

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


I am facing issue while posting on twitter using publish_away module?

I tried the module and it works fine. Follow these steps to enable auto posting to Twitter.

Go to https://apps.twitter.com, and click "Create New App".
In Application Details, enter the name of the App, enter some description, in website enter http://example.com, leave callback URL empty.
Agree with the user agreement after reviewing it, and click "Create new app".
Go to "Keys and Access Tokens" tab.
Please make sure you give "Read, write, and direct messages" access level to the app.
Click on generate the Access token. Keep this page open.
In a separate tab open http://example.com/admin/config/services/publish-away after logging in as admin.
Enter "Consumer key", "Consumer secret key", "Access token", and "Access token secret" from the app.
Hit Save. The account should now appear under the "Accounts" section.
Create new content of type news for testing, check the "publish to Twitter" checkbox, and save.
The article's link should get Tweeted by your Twitter handle.


Drupal Upgrade module: SQL table prefixes and upgrading from Drupal 7 to Drupal 8

It means that if you were to install another Drupal, 7 or 8 on the same database (zentech0_Benia), using prefix will prevent causing confusion/collision.

Ex:

having two tables named accesslog is confusing.

while having site1_acesslog, site2_acesslog you know which accesslog belongs to which site.

In conclusion, if you don't plan on installing another Drupal 7 or 8 in zentech0_Benia, (having 2 websites in the same database) then you don't need table prefixes.


Show the ID of referenced entities using tokens, instead of the label with link

Adding the solution given by Clive in the comments to my question as an answer :

[current-user:field_user_company:target_id]

= the token translating into the node ID of a referenced content type.


For now I didn't find any module for this but you can achieve this by playing around with pager CSS. Just like drop down menus. Pager also has an unordered list with ul and li. I tried it and somehow I was able to show pager as a grid on hovering it and it was working.
You have to do some more in it to achieve exactly what you want.

Here I have given you a rough idea and I think this will help you.


A quick look at the bootstrap toggle JavaScript code does not show any actual dependencies in it for the actual bootstrap theme.  You may be able to install the bootstrap_toggle module without the Bootstrap theme and it will work.

Won't hurt to try on a dev environment. :)


weird features behavior - constantly adding and removing entries from taxonomy.inc

Taxonomy Edge optimizes tree functions for taxonomies. It provides a transitive closure table data model for easily managing hierarchical terms. It was created to avoid recursive functions when fetching all children, and to avoid the not-quite-so-scalable memory footprint of taxonomy_get_tree().

The provided patch contains overrides for the core module Taxonomy in regards to taxonomy_get_tree() and taxonomy_select_nodes().


Drupal role does not appear in Views Filter

By default, views of content only get access to the UID of the author. Add a relationship to the user to gain access to all the user-related fields, including your custom ones


Is it possible to make a second "edit account" page that only allows users to edit some profile fields?

I had the same situation before and handle it with power full druapl feature hook_form_alter, we have 2 forms for user, registration and user edit

user_profile_form ( in editing)
user_register_form (in registration)

We just need hide your specified fields in edit manner So in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    global $user;

    if ($form_id == "user_profile_form") {
       // ym($form);
       // you also can perform this action for specified roles
        //if (!(in_array('blogger', $user->roles) || in_array('administrator', $user->roles))) {
            hide($form['field_mytest']);
            // hide other field with this method
        //}
    }

}

After that  field exists in registration as you can see below

and not exist (hide) in edit  manner

Also you can set them read only instead hiding them with $form['field']['#access'] = FALSE;

And another solution is using field permission module

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

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

As features that this module provides for us anonymous user( un-register user can edit those field and register user only see(readonly manner).


Translating strings to English from a second language

t() function

By Drupal architecture English is a system built-in language which is used as a source language in code.
t() function allows to translate from system language to any other language. It is simple and expected behavior.

UI

There are UI improvements in Drupal 8: http://hojtsy.hu/blog/2013-aug-20/drupal-8-multilingual-tidbits-12-english-can-now-be-translated

Comment about Drupal 7 "Custom English" and problems with default language:

  Using Drupal core alone, this was possible to achieve in Drupal 7 by
  configuring a "Custom English" language on the site with a language
  code different from "en", which then allowed you to replace text with
  your choosing. This quickly gets confusing though because then both
  the old "en" English language and your new "Custom English" will show
  up in language selectors, etc. If you disable the "en" English, then
  your old content saved with that langcode will not display properly.
  Its a whole can of worms. You may also use String overrides, but if
  you are using interface translation from core anyway, using one more
  module for the same task for a specific language is overkill.

i18n features

More complex translation features (like Content translation from core or i18n package) less depend on system language but often depend on default language. Usually you can add content piece in any language and then translate it to English without any problems.

Summary

In code use English only and translate it to other languages in UI.
Select default language once and do not change it.
For changing built-in English strings check out “Translating English strings” section in this article: http://www.packtpub.com/article/setting-basics-drupal-multilingual-site-languages-ui-translation (String Overrides / Custom English / settings.php)
Discover i18n package tools.


drupal_http_request times out on Google Maps geocoding URL

You cannot directly include url queries in the url when using drupal_http_request(). Use url().

$url = url('http://maps.google.com/maps/api/geocode/json', ['query' => ['address'=>'1200 Amphitheatre Parkway, Mountain View, CA', 'sensor'=> FALSE]]);
drupal_http_request($url);


My first step here would be try again. If you still get issues and there is nothing in the logs try increasing the memory limit.

Also there are some pressflow changes in htaccess, replace that roo.


Change the Source DB for migrating via Drush

in settings.php add the connection to the source database (that contains users you want to migrate)
$databases['myuserssourcedb']['default'] = [
  'database' => '',
  'username' => '',
  'password' => '',
  'host' => '',
  'port' => '',
  'driver' => '',
  'prefix' => '',
  'collation' => '',
];

in your migration yml file reference the source database as 'key' in the 'source'
id: migration_of_users
label: 'Migrate users from old database'
migration_group: migration
source:
  plugin: mypluginforusers
  key: myuserssourcedb  <-----This is the important line
process:


Eliminate the "Upload" button in Webforms

First, it's worth to remember that file will be uploaded when you push form's submit button, if user haven't uploaded it yet.
Second, you could use AutoUpload module:

AutoUpload is a user interface (UI) enhancement that initiates automatic upload of files minimizing the number of clicks required by a user.
Currently, users must select files, then press the "Upload" button. We found users often don't realize a button press is necessary and mistakenly think their image is uploaded when it's not.
This module removes the extra button press and hides the "Upload" button via JavaScript for a quicker, automatic file upload. When JavaScript is not enabled, it falls back to the "Upload" button.

I must admit that this module conflicted with my custom modules and themes, but as a code sample it was perfect. It's GPL, so tailoring it to your custom needs is perfectly legal.


Integrating FBA (or Amazon MWS) with Ubercart

There's Commerce Amazon fulfillment if you're not wedded to Ubercart, but it needs porting to D8.


After webform submission restrict/greyout certain fields when user goes back in to edit

From Programmatically modifying a webform with hook_form_alter():
function mymodule_form_alter( &$form, &$form_state,$form_id ){
  global $user;
  if (!$user->uid && $form_id == 'MY_WEBFORM_ID') {
    $form['submitted']['MY_FORM_COMPONENT']['#disabled'] = TRUE;
  }
}


Create new content node upon user creation with populated fields from user profile fields d7

This seems to have to do with porting data from a content node field to a user node field. I solved this by creating the User and then creating the node with data pulled from the user node fields.


For what it's worth you have a typo in your sample code, $startDate is being referenced as $startDatea - note the extra "a". As for a shorter version, try:

$startDate = variable_get('start_date', NULL);
$startDate = date('Y-m-d', mktime(0,0,0, $startDate['month'], $startDate['day'], $startDate['year']);

I suspect not jumping from numeric to string and then back again might save you a few cycles at the PHP layer.


Simplest way to let writers edit Views headers/titles without Views UI access?

You can use the  Views UI: Edit Basic Settings module:

  "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.


Disable email to admin on new user registration

There are a module for control this emails sendings:
MailControl


How do I add tabledrag with 'weight' to admin form

At the risk of oversimplifying, have you tried using or integrating Draggable Views?

If the items you are sorting are nodes (I'm not clear on this) it is a great option for achieving drag-and-drop sorting as you can assign as many fields to an entity as you'd like and set different sort priorities depending on the circumstances.  That as apposed to 'weight' which is a one size fits all number.


Undefined Index when adding a new field to any Content Type or Taxonomy

Sounds like an issue with your current Drupal version

  A patch to fix this has been committed to 7.x and will be available in
  7.15. In the meantime, visiting the image field settings form and clicking Save will resolve the issue

More info: http://drupal.org/node/1558548
Patch here: http://drupal.org/files/drupal-1558548-3.patch


No, or at least not, with XML Sitemap & Views module. There is no Views integration with the XML Sitemap module. Given how both these modules work (a view being defined by base table & XML sitemap trying to generate a list of all indexable site paths), I think you'd be better off looking for another solution to embed all your site paths into the site.


This blog post explains one way to do this: http://www.openbandlabs.com/blog/2009/06/programmatic-cck-content-type-creation


There is a problem with the public directory, it is not configured or it is not writable. You can check this with drush:

drush ev "var_dump(is_dir('public://'), is_writable('public://'))"

Result should be:

    bool(true)
    bool(true)

If these two conditions are true, then the checkboxes will be available.


There is a module exists that does just that: View Mode Page.

Check it out and inspect the source to see how it works.


Are spam registrations a threat to a Drupal 7 site

Will there be a number of authenticated users on this site who are not spammers, or does your project only require a few users to create content? If it's the latter, the best bet is to simply turn off user registration, and have the owner create accounts as needed. If the former, programs like Mollom should help with cutting down spam and the basic package doesn't cost.

As far as performance goes... if spammers can post content, the obvious issue is comment/content spam. You can use the Disqus module to mitigate this, i.e. offloading the work to Disqus. If not, then if you need to send emails to all users through a service, then you will necessarily have email list bloat. If the volume gets very high, then you could potentially have availability issues, though I don't see that very often.


I don't see anything wrong with your approach. '#markup' => $account->field should work. Do you have it nested under a key?

$form['static_field'] = array(
    '#markup' => $account->field
);


Is it good to declare API details as constants

I've seen both approaches, variables & constants, with storing API credentials. I've also seen private keys stored outside the webroot.

Security Concerns

In all these cases you have, roughly, the same level of security. An intruder needs to penetrate (code injection) and discover your credentials. You could argue that with constants or external files are more "secure" since an intruder is unlikely to know about those, whereas he will likely know the variables table will have many goodies in it, but as any security-minded person will tell you, security through obscurity just isn't security.

Anyone that has access to inject server-side code will eventually figure out how to grab everything if they're so motivated. Given that, your best bet for security is to prevent penetration in the first place.

Keep all your whole software stack (Drupal, contrib modules, web server, database, & OS) up to date.
Be proactive about monitoring any odd errors occurring in Drupal / web server logs.
Follow good programming practices (e.g. understand how to defend yourself against SQL injection, XSS, and other attacks)
Don't install modules / PHP libraries from an untrusted source
Keep up to date about any news with Drupal/PHP or any exploits related to your entire stack (e.g. drupal.org has security mailing list for recently discovered exploits)

Unless you're a high profile target, the most likely attacks you will see are script bots hitting you with well known exploits. As such, the above advice should keep you covered. Just keep in mind, the bigger you are the more time you should be investing into security.

Practical Concerns

With all that said, I'd say the only other difference between the different methods of securing credentials is usability. If these are credentials that a developer should only ever touch, constants/secure files should be fine. If these are credentials that can change (e.g. module reuse across many sites) and you want other non-developers to change them, then the variable approach is the way to go.


How to check if is anonymous user's first visit to site when using varnish

The varnish caching will not work if you use cookies : http://systemsarchitect.net/2013/07/08/reading-php-session-from-varnish-cache/


Where can I find the link between field answers and the user who submitted it?

Look for "entityform" table - column "uid" gives you user id of the user who submitted the form.


The requested page could not be found error appear in page but page is render correctly-drupal 7

It sounds to me like you only want to show said block on that page and nothing else. You might be better off implementing hook_menu() to register a callback (a page) which displays custom content, instead of creating an empty page and showing a block on that.

It might look something like this:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['currant-trustees'] = array(
    'page callback' => 'MYMODULE_currant_trustees',
    'title' => 'Currant trustees',
    'type' => MENU_CALLBACK,
  );
  return $items;
}
function MYMODULE_currant_trustees() {
  $content = 'This is where your content should go, just copy the code from the block content';

  return $content;
}


user_access( ) - Printing list 'variables' you can plug into?

You can see all the permissions on the /admin/people/permissions page.


How to know which name will have my view tpl file?

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7

See the suggestion for views templates.

If You calling a view block in your custom tpl.php use
echo views_embed_view('view_machine_name', 'block_1');
You can find out the display name by clicking the tab and check its name in the address bar of your browser: "#views-tab-block_1" gives you "block_1'.


Drupal Rule to deselect radio button item?

There is none that I'm aware of.

Radio buttons aren't meant to be deselected (a single selection is required). I would suggest using checkboxes to deselect an option or add a "None" option to your radio group.


Views exposed filter resets to first selected value

Derp derp derp. I had to turn off caching on the view.


How to use the Rules module to award userpoints to referring users?

Add a field to user registration form that collects the uid of the referring user. Then ask current users to invite other people to the site using a custom URL to user registration form and this URL should include as query parameter the uid of the referring user. Hook the user registration form and fill in the uid of the referrer based on the query parameter. You should hide the referrer field completely. Then you do counts in the database for how many paid users a given uid had invited. The referrer uid in regard to each user is kept in the custom user profile field and becomes meaningful in your situation if the user becomes a paid member.


Create a view for a specific content(Not for a specific content type!)

It sounds like you want to put a teacher tab on a node page of type department.

Create a view that shows content (nodes). Filter it to only show teachers. Add a relationship to the department.

Add a contextual filter of nid, and set the relationship (to department) you created on that contextual filter. Hide the view when the filter value is not available, and add validation to it that confirms that it is a node nid belonging to a department.

Add a path to the view: node/%/teachers. Add a menu entry. Set it to menu tab, and give it a title of 'Teachers'.


How can I import/rewrite settings/content types/blocks/etc from live with the newly developed features on dev?

IMHO, using git for that works quite well.

You have a production branch and a development branch (and possibly many feature branches). Locally, you are on the develop branch, you make your changes there, export and commit your changes there

Before you do a deployment, you switch to production branch, do a config export ,sync it down, commit it, merge develop into production, do a local config import to make sure that things are consistent and then deploy.

A useful presentation for this is https://de.slideshare.net/nuvoleweb/advanced-configuration-management-with-config-split-et-al, for example slide 39, although that focuses more on working with multiple developers, but the process with production is similar.


Include file with functions in node.tpl.php and execute them on node content

Implementation Issues

Included a file in node.tpl.php
I have a function which, afterwards I want to call from a node's content-body

Sorry but I think these are not following best practices. As you can see If these was possible then it would have worked because it's just including a PHP file and calling a function in it but I think Drupal doesn't do it that way and runs the PHP in the body field way before node.tpl.php w/c results to no included PHP file at that time yet.

Suggested solution

Might I suggest, it's better for us to:

Create a custom module
Add your helper functions there with any structure of the files you can but following Drupal standards.
Use Drupal hooks if needed because if you place your functions in the .module file, it will be available already for use.

One example of this way is after adding your helper functions into the .module file and want to execute/run functions when viewing the node, you can use hook_node_view. Maybe add some scripts, remove data, alter data and etc. and you can also do conditional statements there if you want to run specific things for a specific content type.

This just doesn't align your site with best practices but makes it easier to maintain in the long run with less technical debt.

Hope this helps you to be able to call/execute your needed functions on nodes.

UPDATE

You can remove the PHP file inside your theme and transfer the functions/codes inside it in the .module file. After that, you need to Clear All Caches then that will make your functions available or callable.

You don't need to use the include_once or hook function.


How to add a confirmation form upon submission of user profile form

You can add your own submit handler in front the of the predefined submit handler using hook_form_alter().

The #submit property is an array of submit handlers and it allows multiple values. Use array_unshift() to put your handler in front of the predefined handler.

Your code will look something like this:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if ($form_id = 'target_form') { // make sure it's the right form
    // add my handler
    array_unshift($form['#submit'], 'my_submit');
  }
}

function my_submit( $form, &$form_state ) {
}

When the form is submitted, it will run my_submit() before the predefined submit handler.


image_formatter is to render an entity field, you can't use that without having that.

Try using a render array for the link, like this:

$type_link_nested_array = [
  '#type' => 'link',
  '#title' => ['#theme' => 'image_style', '#style_name' => 'large', '#uri' => $uri, ],
  '#url' => Url::fromUri('https://www.drupal.org'),
];


How to add extra arguments/parameters to ajax callback function?

Drupal doesn't have a mechanism to do that, no. As mentioned in the post you linked to, there's no need to pass that data to Javascript and then back to PHP though - just keep it in the form:

function mymodule_form($form, $form_state) {
  $form['button'] = array(
    '#type' => 'button',
    '#ajax' => array(
      'callback' => 'my_callback_function',
      'wrapper' => 'my_target_area',
    ),
  );

  $form['#foo'] = array($group1, ...);

}

function my_callback_function($form, $form_state) {
  $arguments = $form['#foo'];
  return $form['my_target_area'];
}


How to find number of assigned content to all user

Basically you need to add the entity reference field using relationship to the view. Then use aggregation to find the count.

Refer https://www.ostraining.com/blog/drupal/entity-reference-views/ on how to create view using entity reference field.
To find the count, you can use aggregation. For using aggregation you can refer https://drupal.stackexchange.com/a/31542/48290.


View in block doesn't sort by date whereas page does

I figured out I needed to change the sort option inside the contextual filter.


How do I programmatically change the user ID in a order?

It should be as simple as:

$order->setCustomer($user)->save();

Or if you only have the user ID and don't want to load the account object:

$order->set('uid', $uid);
$order->save();


How to block users from editing a node of a content type? (D7)

Oops: My bad.  I had given authenticated users "bypass node access" permission to deal with a pending bug in the apache_solr module.  Once I dropped this permission, everything worked the way it was supposed to.

Sorry for cluttering up things...


How do I add custom tab in the user profile page?

Your problem is in the mymodule.routing.yml file, the big problem is the place of user: \d+, this line must be under the requirements: section, the other problem is the indentation. So the final code should be:

mymodule.account:
  path: '/user/{user}/custom'
  defaults:
    _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
    _title: 'Custom Settings'
  requirements:
    _permission: 'access content'
    user: \d+

And of course you need the form class definition in src/Form/MyModuleUserSettingsForm.php

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class MyModuleUserSettingsForm.
 *
 * @package Drupal\mymodule\Form
 */
class MyModuleUserSettingsForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'simple_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#maxlength' => 64,
      '#size' => 64,
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
    ];

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {  }

}

And a mymodule.info.yml file to complete your module (in this case named mymodule)

name: My Module
type: module
description: 'My module'
core: 8.x
package: Custom

Reference:
Structure of routes


How to create a view that automatically shows all fields as a table, even if new ones are added to the entity?

I've run into exactly the same use-case. So far my intuition has been to create a fieldset to which the client can add fields, and develop a new Views plugin to add a whole fieldset to a view using every field's defaults. (The challenge here is that each field has different parameters to configure when you add them to a view.)


Take a look at Configuration -> Organic Groups Global Permissions (drupal/admin/config/group/permissions). There you will find really fine grained controls over who can view and edit nodes and fields on your group pages.


Token to get the last component of [node:url]

[node:title] will give you the node title.


The join() method doesn't return the query object to isn't chainable.

If you change your code to this you should be fine:

$polls_query = db_select('poll', 'p')
  ->extend('PagerDefault')
  ->limit(3);

$polls_query->join('node', 'n', 'n.nid = p.nid');

$polls_query->fields('p', array('nid'))
  ->condition('p.active', 1, '=')
  ->orderBy('n.created', 'DESC');

// etc...


Remove “base theme” declaration from YOURTHEME.info


Renaming a webform handler - old class stuck in DB despite clearing cache

Sometimes, especially with a local dev environment, after you have tried every other route the only other avenue is to restart the PHP service and/or reboot the server/VM. This should clear system caches and often times will resolve this issue.


buy one get one free Ubercart discount module?

It looks like Ubercart Discounts (Alternative) can do you you ask:

  Features

  Filter both products required for the discount to apply and qualifying products that receive the discount based on multiple products, taxonomy terms, node authors, or product classes.
  The above filters allow for a discount like: buy 3 of any of X product and get a discount on any of Y product.
  Attempts to automatically add free products to the cart for codeless discounts.
  Discount # of products, a percentage or a fixed amount off.
  ...

I don't have any personal experience with the module, but it looks promising.


How to remove tags from display in form?

The item element type is a form element, Drupal\Core\Render\Element\Item.

This means that it gets a form element wrapper by default.

Rather than rendering the  wrapper in the Twig template, you could include it in the render array, and add form.card.a and form.card.b as its children:

// In your form handler class

function buildForm($form, $form_state) {
  // ...

  $form['card_link'] = [
    '#type' => 'html_tag',
    '#tag' => 'a',
    '#attributes' => [
      'href' => '/card?id=' . $this->getCardLink()
    ],
  ];

  $form['card_link']['a'] = array_merge($form['card']['a'], [
    '#prefix' => '
',
    '#suffix' => '
',
  ]);

  $form['card_link']['a'] = array_merge($form['card']['b'], [
    '#prefix' => '
',
    '#suffix' => '
',
  ]);

  // ...
}

The template then simplifies to this:

{{ form.card_link }}


By default, the Date field's Views integration sets a +/- 3 year range for date filters. If you want to expand this beyond this range, set the Starting year & Ending year settings to Other.

This option will let you enter an arbitrary year from which your select box will start and end.


How do I change a field type from integer to decimal?

Ok, I found a good solution to solve my problem.

Modules required

Helper
Devel (this is not strictly necessary)

Steps

Enable Helper module;
Enable Devel module;
Enable the block Execute PHP;
Paste and execute this code in the block: FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
Edit display format for node where the field is being used;
Edit Views where the field is being used to fix the format settings (If necessary);

If you don't want use Devel and can use Drush:

Enable Helper module;
create a new file in root Drupal folder, i.e. name it: intToField.php

<?php
FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
?>
launch the drush command: drush src intToField.php
Delete the file;
Edit display format for node where the field is being used;
Edit Views where the field is being used to fix the format settings (If necessary);


How to debug users geting automatically logged out for unknown reasons?

This issue is solved by updating this setting

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


You can use hook_views_query_alter and alter the views query by merging your custom query with the views SQL query itself.

Also there is an option in "advanced" section - theme suggestions
There you can write your custom query to fetch results into tabular format.


Image Resize Filter not working with WYSIWYG + CKeditor?

For re-sizing of images instead of using Image Resize filter you colud use the feature of drupal 7 itself ie by setting up an File Type for your image.

You could set up a File type you should go to Configuration -> Media -> File types -> Manage Display

There are basically 6 types of image file type that you could use

Link
Default
Preview
Large
Original
Small

These are the default file type that you can select and are there with there default values so we could override the default values by our own values and could use that file type for uploading our own images of particular size.


How can you refer to content ID from underlying URL while adding a new node?

It seems that the node in the original link is only for the source page, not for the page in question when Drupal determines which data to pass into the contextual filter. Instead, I wound up creating a new URL path pattern and filtering on the basis of that structure. Then I could add token-using links to various pages, with the contextual filter picking up the pattern of those paths.

You can find a full write-up at the Drupal forums:

https://www.drupal.org/node/2905210#comment-12238299

Thank you again for your help! :)


Is there any possibility to migrate translations from Drupal 5 based project to Drupal 7 project?

Solution: There is a build-in possibility to export translation strings for each language into .po files in Drupal 5 projects as well. Export form is available under the "admin/settings/locale/language/export" admin menu.


One option would be to preprocess the field:

function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_tags') {
    array_walk($vars['items'], function(&$el) { $el['#options']['attributes']['class'][] = 'some-class'; } );
  }
}


How can I compare a view token with a string?

But it always goes for the else part even if the token value is "Foo &
Bar"

This is because by default Views adds classes to your field:

Which means field_category is actually equal to
Foo & Bar

and since
Foo & Bar
 is not equal to Foo & Bar your conditional always goes to the else.
If you uncheck the "Add default classes" in your category field settings, your conditional should work now. Unless... your field is linking to something so it would still be Foo & Bar and not equal.
As 4k4 commented, you can instead use field_category__value to get the raw value and not have to uncheck the "Add default classes".


Finally found out what the problem was. It was the Metatag module that copied the content in the body (using tokens) and used it as metatag description text. So by simply editing the metatag description field I got rid of the problem.


Views 3 has been completely changed; the API has been rewritten. Make sure Calendar is compatible with that version of Views.
Check the Calendar issue queue to see if there are reported issue.


Prorgrammatically generated quicktab does not display content

I have found the solution to the problem through some experimentation. It appears that the value for bid must take the form of: module_name_delta_block_delta. To illustrate this, here is an example:

$tabs[] = array(
  'title' => t($title),
  'type' => 'block',
  'bid' => 'catalogue_search_delta_books_journals_search',
  'hide_title' => TRUE,
);

The module name is: catalogue_search.
Then you need the text: delta
Finally the block delta name: books_journals_search.

I did not see this documented anywhere so hopefully this will help others with the same problem.


Make visible the article in Draft and Needs Review mode to other members of the community group

Is the below permissions checked from permission tab ? If it's not then set the below permissions:

Workbench Moderation:

View all unpublished content
View the moderation messages on a node
View moderation history
Use "My Drafts" workbench tab
Use "Needs Review" workbench tab

Also let me know which version of workbench moderation module you are using .


How to get parent node from a attachment in drupal8 search api results

$file should be instance of Drupal\file\FileInterface but in this case $file is null so you should check first on $file something

function hook_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->storage->id() == 'saa' &&
    $view->current_display == 'page_1' &&
    $field->field == 'fid') {
    $fid = $variables['output']->__toString();
    $file = \Drupal\file\Entity\File::load($fid);
    if ($file && $file instanceof Drupal\file\FileInterface) {
      $file_usage = \Drupal::service('file.usage')->listUsage($file);
      $variables['output'] = $file_usage;
    }
  }
}


Form API + Module: Nested default value variable_get doesnt behave the same as unnested variable_get

I'm pretty sure system_settings_form() only looks for variables defined at the root of the $form_state['values'] array.

Since you have '#tree' => TRUE on your fieldset element this will not be the case. If you remove the '#tree' => TRUE' line, the value of your nested element will be saved in a variable called 'unnested_example_item' as you expect.


Nice attempt, but no the template file is not the best place for that.

I would work on including the ads in your View result rather than trying to hack the template file.

Does your view show rendered content?  Easy, make a new content type that contains your ads and include that content type in your filter.

Does your view show fields?  Same thing, just make sure the ad content type has the same fields as the content you're showing in the grid.


View filtered by a Date field's value being in "last month" shows July content on July 31

Try to use 'last day of last month' or 'first day of last month'.


Control content type availability based on day and time

This is quite straight forward with rules.

Create a page called "Order Form Unavailable" with your message about products only being available during the day.
Enable the PHP Filter module.
Create a rule with event "Content is viewed" of type "Order form Webform" (Or whatever)
Add condition "Execute custom PHP code".

Add the following into the PHP text area...

if( (date('H') < 9) && (date('H') > 17) ){
 // before 9AM and after 5PM
 return TRUE;
}

Add action "Page Redirect" to redirect the user to the "Order Form Unavailable" page.


Finally, someone redirected me to the right place

Here's the missing code that does the trick:

location ~ \.php$ {
            error_page 418 = @rewrite;
            recursive_error_pages on;

            fastcgi_split_path_info ^[^=](.+\.php)(/.+)$;
            include fastcgi_params;

            if ( $uri = /index.php ) {
                    break;
            }

            if ( !-e $document_root$fastcgi_script_name) {
                    return 418;
            }

            #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
            fastcgi_read_timeout 240;
            fastcgi_pass  127.0.0.1:9000;
}

Source: http://wiki.nginx.org/Drupal

(link suggested in https://groups.drupal.org/node/405038)


Custom placeholder markup when leveraging #lazy_builder in elements

I know this is an old question, but for anyone who stumbles upon it via a search engine (like I did), then the answer is that as of right now, you can't provide custom placeholder markup, but there is a Drupal.org issue with patches that adds this functionality, so it's possible that the feature will eventually be available in the Big Pipe module without a patch.


Remove " edit Article " and [current-page:pager]

If you indeed removed tags in global and content settings, then they should not appear when creating new nodes. What you are looking at is probably a node that existed before you changed the meta tag settings.


How can I add products to cart programmatically?

To add particular product id you have your product id and current user id you can easily do.
Send the Product id and user id to this function this will add your product to the user cart.

This is the custom function used. The main part here is the commerce_product_line_item_new() and commerce_cart_product_add() this will add the product to that particular user cart.

function add_product_to_cart($pid,$uid=0){
    global $user;
    $uid = isset($uid) && !empty($uid) ? $uid : $user->uid;
    $line_item = commerce_product_line_item_new(commerce_product_load($pid));
    commerce_cart_product_add($uid, $line_item);
}

Hope this will help :)


Make sure you've chosen the right method under "MENU TOKEN OPTIONS":

With this options enabled, I was able to create a menu item using the token [node:content-type:name]


$GLOBALS['conf']['cache'] = FALSE;

See also module CacheExclude, here are some more details about it:

  This module provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.


Moving a DB table into a different module

The simplest way is to uninstall your existing module completely (not just disable), cut the schema definition from the old to the new, then enable both modules. The uninstall will remove the table, and the install will add it back in from the other module.

You'll also want to get rid of the cleanetica_advanced_update_1() function from your current module as that could cause some interesting inconsistencies if left unchecked.


Importing large flat-file data sources with Drupal 7 with Views 3 integration

My gut tell me that this plan will make your servers catch on fire...

Seriously, if you are churning that much data, then I think you need to keep the data in an external datasource and then integrate it with Drupal.

My initial thought would to use two databases for the external data, so that you can do the weekly import w/o disturbing things too much.  In other words, get database A up and running, and then import into B.  When the import is done, make B the live source.  Then wipe and import into A.

I have done a lot of integration of external datasources into Drupal, and it really isn't that hard.  I gave an overview in Transition plan for PHP5 abomination to Drupal.  That was for Drupal 6, but the same thing basically applies to Drupal 7.   Essentially, you simulate what CCK / Fields API does with your own interface.

Not having a UUID for the weekly database really throws a wrench in the works, though.  That part requires a lot of though, more that can be provided in a Q/A forum like this.

If you really do want to go down the import route, I would bail on Feeds and Migrate and write your own import script.  Basically, you do the initial bookstrap process from index.php, query your datasource, make your nodes, and then save them.  Programmatically making nodes is easy.

The best way to start out with this is to make a node with the UI, then print_r it, and replicate the object with code in your import script.  Taxonomy, files, and noderefs, are hard parts, but you just need to get familiar with these portions of the API to build up these object properties.  Once you have a valid node object, then you can just do a node_save().  Make sure you set a very large limit with set_time_limit() so your script runs.

EDIT BELOW TO ADDRESS CLARIFICATION/EXPANSION:

Personally, we stopped using the contrib module based approaches for data imports a while ago.  They do work mostly well, but we just ended up spending way too much time fighting them and decided the cost/benefit was too low.

If you really need the data in Drupal proper, then my opinion about a custom import script hasn't changed.   One of the modules you reference could be used as a starting point for how to build the node objects, then just loop through your data build nodes and save them.  If you have a PK, you can easily add in logic to search the database and node_load(), modify, and save.  An import script is really only a few hours work if you know the Drupal API.

If views integration is a key (and it sound like it is based on the edit) and you want to do the external tables approach, then your best option is do do a custom module and implement hook_views_data to get your data into views.  More than likely, you will custom module anyway to support your datasource, so adding this hook shouldn't be that much more work.  The TW and Data modules should have some example to get you going.

Personally, though, I have never found the views integration with external data to be really worthwhile.  In the cases where I have considered it, the data was just too "different" to work well with a views based approach.  I just end up using the method I described in the "abomination" link above.


According to the module documentation, you can do this:

  If you want to add honeypot to your own forms, or to any form through
  your own module's hook_form_alter's, you can simply place the
  following function call inside your form builder function (or inside a
  hook_form_alter):

<?php
  honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
?>

  Note that you can enable or disable either the honeypot field, or the
  time restriction on the form by including or not including the option
  in the array.

  You can also use Honeypot's API to modify the time delay for forms,
  add or remove protections for certain forms, etc.


Display all nodes with identical field value to current node

The way I've always handled this is to build the view in question using the "field value to match" as a Contextual Filter. For the Contextual Filter's settings, choose "Provide default value", for the type choose "PHP Code", and for the "PHP contextual filter code", load the current node and grab it's field value,

$node = menu_get_object();
return $node->field_domain['und'][0]['value'];


How do you print nothing from a Field template? (field--field_name.tpl.php)

This tutorial might be helpful http://akyl.net/how-extract-and-theme-drupal-7-fields-out-renderpagecontent


Entity Reference field fails when choosing from more than 1000 items

I haven't tested whether Oracle's performance with Entity Reference is substantively worse than another backend such as MySQL.

However, implementing the workaround detailed here and converting a Drupal user.module query to a dynamic form to also implement partitioning worked, albeit with a 50 second execution time and a hugely increased PHP memory requirement. This is because of multiple complex queries across the whole node set.

Switching to use of the references module and the node_reference content type has vastly improved performance.


Form API Ajax trigger callback with size of input

You can do this:

1) Decide on an event name. In this code, the event name will be 'overminlength'

2) In the form element being defined using the Form API, set your #ajax as normal, but set the #ajax 'event' to the event name chosen in step 1:

'#ajax' => [
  'wrapper' => 'some_wrapper',
  'callback' => 'some_callback',
  // Set the custom event here:
  'event' => 'overminlength',
],

3) Create a custom JS file and attach it to the field

'#attached' => [
  'library' => ['mymdodule/mylibrary'],
],

4) Add a $.keyup() listener to the field.

In the callback, count the number of characters in the field
If it's more than X characters, call $.trigger(), and trigger the event from step 1

(function($, Drupal) {

  "use strict";

  function fieldwatcher(context) {
    $(context).find("#edit-myfield").once("fieldwatcher").each(function() {
      $(this).keyup(function() {
        // Change '3' to the number of characters after which you want to
        // trigger the ajax.
        if ($(this).val().length > 3) {
          $(this).trigger("overminlength");
        }
      });
    });
  }

  Drupal.behaviors.testScript = {
    attach: function(context) {
      fieldwatcher(context);
    }
  };

}(jQuery, Drupal));


Webform AJAX submission, same problem with multiple approaches

I've solved the problem with using jquery.form plugin and submit the form via AJAX with the help of this plugin.

I've found this solution in this answer

https://drupal.stackexchange.com/a/23650/9297


How can I show only first level terms on a dropdown taxonomy exposed filter?

This question is very similar to How Can I add a Hierarchical taxonomy Select in views filters and when editing content in Drupal 7

I will say that the easiest method I can see is to add an exposed field by the name of "Content: Has taxonomy terms (with depth)" this way you can select the vocabulary(unfortunately only one) and also select the depth.


I'm assuming you're on a shared server. Here are some options.

Option 1 - Downgrade PHP.
Although it might not be the safest choice, as both the PHP and Drupal is probably no longer supported, you can do the following.

Some hosts allow to specify a different PHP version in php.ini.
Rent a cheap VPS, which will allow you to set the PHP version.
Some shared hosts specialize with older PHP versions, make a switch.

Option 2 - Use backup and migrate modules.
There are a number of backup and migrate drupal modules which will make the migrating process easier. This would be a safer choice, but the downside, is that you'll loose your theme and you might have to upgrade to ->5, ->6 and only then to ->7. Here are a few modules to look at

Backup and Migrate
Backup

Option 3 - Start from scratch, import in bulk.
It's both safe and probably the best choice. Set up a new site and a theme. Export the data from the old site, using feeds, or other Drupal modules and import it into the new site using modules like Migrate.

I would advise to upgrade to D7, since the support for D6, not alone D5, will be dropped soon.


Your module needs to implement hook_form_alter() to add '#ajax' arrays to the elements that trigger a change in the form. The #ajax elements will include 'wrapper' and 'callback' elements that specify the html ID of the part of the form to replace and a function in your module that returns the part of the form that is being replaced.

For example, if the element 'my-element' should be replaced, add

'#prefix' => '
',
'#suffix' => '
'

to the form array with key 'my-element'. The element that triggers the replacement will get

'#ajax' => array(
   'wrapper' => 'my-element-id',
   'callback' => 'my_callback',
   'method' => 'replace',
),

Here is the callback function:

function my_callback($form, &$form_state) {
    return $form['my-element'];
}

Your hook_form_alter() will hide/show elements and generate your custom messaging depending on $form_state (which it will read when the ajax callback happens).


How to use Views with Fields Collection and filter on where used

I hope you are creating a view of the type Registration in that case you can add a contextual filter of the type Registration: Host entity ID

Now when you add the nid of the main node you would see the registration specific to that node.

Note : To get the Registration: Host entity ID as a contextual filter you need to enable the Registration Views module.


How to provide the “Privacy policy link” correctly on EU COOKIE COMPLIANCE module?

Actually it's better you'd report issues like that on drupal.org and not here on Drupal Answers.

The recent EU Cookie Compliance updates happened in a rush when during the ongoing development a security hole was found. Because of that a lot of half-ready new features got released.

It happens I just released a patch which may be related to your problem, see https://www.drupal.org/project/eu_cookie_compliance/issues/2985543.

But you may not necessarily need the patch. All you need to do is to update to the latest version, then go to the module's config page and choose a method (default, opt_in etc.). Choose default to turn back to the initial method before the most recent updates added additional methods.

If that doesn't work try to follow the steps from https://www.drupal.org/project/eu_cookie_compliance/issues/2985613#comment-12685609 which was a fix for the 7.x branch but may apply for D8 as well.

Last but not least, double-check that the link you provided either goes to an existing internal route or is an external link.


Can a form triggering an ajax call reload itself on drupal 7?

Your form id is 'questions-list-table' but you have 'wrapper' => 'question-list-table' (letter s is missing). You might also want to be explicit with 'method' => 'replace' since the ajax is causing problems.

You should add a '#submit' => 'submit_function' and modify your $form_state in that function instead of trying to modify it in the ajax callback.

Why do you rebuild and render the form in your ajax callback? I think you just want to return the part of the form to replace - in this case, $form itself.


Subnavigation doesn't show with the Bartik theme

Just set it as expandable in structure/menus.


You can run a custom query:

SELECT TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'database_name'

to list all the tables in your database and the engine that's in use for each.

Alternatively you could log into your database using phpMyAdmin and select your database...you'll see the engine in the Type column in the list of tables.

Personally I'd recommend Navicat for MySQL, it's a very nice MySQL GUI and makes finding out things like this very easy.

Source: http://www.electrictoolbox.com/mysql-table-storage-engine/


I'd have to see the html, but find the class that wraps each field (the border is applied to that) and use a float left with some right margin. Find what class wraps both of them and apply overflow:hidden to that. The fields should now look like what you want.


No, it unfortunately does not.

Redis and Authcache are two completely separate systems/concepts, one cannot be used in place of the other.

Redis is a key/value store, primarily used in Drupal as a cache backend.

Authcache provides the mechanism to store/serve cached pages to authenticated and un-authenticated users alike. It uses a cache backend such as Redis for storage, but it is not itself a cache backend.

On the flip-side, Redis is a dumb key/value store, that has no concept of authenticated/unauthenticated users. It cannot be used to replace the functionality provided by Authcache, which is necessary to (amongst other things) build appropriate cache ids based on the user's authentication status, and persist rendered pages, or parts of pages.

The How does Redis compare to Authcache?  thread you linked to, in the (now deleted) comments, puts it nice and succinctly:

  the question isn't about Authcache, it's really "Memcached vs Redis".

Which I agree with, and is actually what the original revision of your question was asking. So it kind of all makes sense.

Just in case you're basing the question on this obsolete bit of information from the Pantheon docs:

  "Redis adds caching for authenticated users, which can greatly alleviate request bottlenecks..."

Please note that advice has now been removed as it was misleading. Redis does not provide caching for authenticated users in and of itself, but it can be a part of that process if Authcache is enabled over the top.

BTW I should add that I wish Redis did make Authcache redundant - I'm right in the middle of converting a large social site to use authcache, and it's not an easy process. The above 'knowledge' has been gathered through extensive reading and back-and-forth with the Pantheon engineers.

Also, slightly off topic but possibly relevant to your decision making process: the Pantheon engineers recommend the authcache approach over something like ESI, because of the increase in the number of app-server bootstraps. So if you're looking for an advanced caching solution for auth'd users, authcache is probably the best way to go.


Views - how to replace the pager with a slider

Views Slideshow sounds like the ticket https://www.drupal.org/project/views_slideshow.
FlexSlider might do the same, but also responsively.


You don't have to delete everything.  Using database viewing/querying software (phpMyAdmin, dbForge Express, etc.), you can identify exactly which view is causing problems allowing you to remove only one view or attempt to fix it.

It is detailed in this answer: https://drupal.stackexchange.com/a/105393/8506


How to theme a select box with multiple selection enabled

The Improved Multi Select widget sounds right up your street:

The Improved Multi Select module replace the default multi-select boxes with two pannel list and search.
The first panel holds the options that are available, and the second panel holds the options that have been selected.

It looks pretty good too:


recent forum topics on sidebar of home page, recent articles and forum topics on article pages, recent articles on forum page

Sounds like something that would be easiest to accomplish with the Views module (seeing as you're using the Advanced Forum module you should already have it installed). It allows you to create blocks with the necessary content and then you can just adjust the block settings to get them displayed where you want.


Maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.


How to create a fixed width image style for all landscape and portrait images?

Scale only scales the image so it looks proportionate. It will go with either the height 580px or width 580px, which ever is closer.

If you want your image to be exactly 580px x 580px you could use Resize but you will see your image will look stretched.

The only other option that will give you the exact 580px x 580px is Scale and Crop

If you are afraid that something important will get cut off, you can use this awesome module:

Focal Point by DA's own bleen

  Focal Point allows you to specify the portion of an image that is most
  important. This information can be used when the image is cropped or
  cropped and scaled so that you don't, for example, end up with an
  image that cuts off the subject's head.

Then use Focal Point Scale and Crop as your image style effect.


Webform no duplicate selections with multiple select lists

You can do it by writing custom module. If you want to go for a contributed module, the Webform Validation module does that

This module adds an extra tab to each Webform node, allowing you to specify validation rules for your Webform components. You can create one or more of the predefined validation rules, and select which Webform component(s) should be validated against those. By using the hooks provided by this module, you can also define your own validation rules in your own modules.
The following validation rules are currently included:
Numeric values (optionally specify min and/or max value)
Minimum length Maximum length Minimum number of
words Maximum number of words Equal values on
multiple fields Unique values on multiple fields
Specific value Require at least one of two fields
Require at least one of several fields Minimum number of
selections required Maximum number of selections allowed
Exact number of selections required Plain text (disallow
tags) Regular expression Must be empty (anti-spam:
Hide with CSS) Words blacklist Must match a
username


Rather than using Feeds, I suggest using the core Migrate module.  There is also a core plugin for converting dates during migration, FormatDate.  This will allow you do specific the input format and the output format.  I believe, this process configuration would work in your case:

process:
  field_date:
    plugin: format_date
    from_format: 'F j, Y'
    to_format: 'Y-m-d'
    source: event_date

If Feeds is your preferred method, then you can try the Feeds Tamper module.  Based on the plugin list for Drupal 8, I think you would need to do a "String to Unix timestamp" tamper on the field, followed by a "Unix timestamp to Date" tamper, using 'Y-m-d' as the format string. However, I haven't used Feeds and Feeds Tamper in a long time, and would typically write custom tampers for something like this.


As per the comments from Jaypan, the first thing to do is extending SearchBlockForm so you can give it a custom ID. Put the code in mymodule/src/Form/MymoduleSearchBlockForm.php.
Add the following code in the custom class (in this case, FoobarblkBlock) to create a custom block. Put the code in mymodule/src/Plugin/Block/FoobarblkBlock.php

/**
 * @file
 */
namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Creates a 'Foobar' Block
 * @Block(
 * id = "block_foobarblk",
 * admin_label = @Translation("Foo Bar block"),
 * )
 */
class FoobarblkBlock extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function build() {
      $form = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\mymodule\Form\MymoduleSearchBlockForm');
$form->setFormIdentifier('some_custom_value');

return \Drupal::formBuilder()->getForm($form);
}

Place the block in the required region.
The resulting form will be:

<form action="/search/node" method="get" id="search-block-form-some-custom-value" accept-charset="UTF-8">


Theming Views' exposed form is hard because it doesn't behave like most forms and use its own label mechanism. So, you can't simply use a form_alter hook to add #prefix and #suffix to elements. But using THEME_preprocess_views_exposed_form, you can craft your own suffix/prefix mechanism:

function THEME_preprocess_views_exposed_form(&$variables) {
  if ($variables['form']['#id'] == 'views-exposed-form-VIEWNAME-DISPLAYID') {
    foreach ($variables['widgets'] as $id => &$widget) {
      switch ($id) {
        case 'first_date_id':
          $widget->prefix = '
';
          break;
        case 'last_date_id':
          $widget->suffix = '
';
          break;
      }
    }
  }
}

and in the template file

<fieldset>
    <legend>Filters</legend>

            <?php foreach($widgets as $id => $widget): ?>
                <?php if (!empty($widget->prefix)) print $widget->prefix; ?>

                    <?php if (!empty($widget->label)): ?>
                        <label for="<?php print $widget->id; ?>">
                            <?php print $widget->label; ?>

                    <?php endif; ?>
                    <?php if (!empty($widget->operator)): ?>

                            <?php print $widget->operator; ?>

                    <?php endif; ?>

                        <?php print $widget->widget; ?>

                <?php if (!empty($widget->suffix)) print $widget->suffix; ?>
            <?php endforeach; ?>

                <?php print $button ?>

</fieldset>


There's no built-in function for loading a block by string, but you can use a simple SQL query to get the ID of the block using a string.

$block_name = "Your block name";

$block_id = db_query("SELECT bid FROM {block_custom} WHERE info=:info", array(":info"=>$block_name))->fetchField();

$block =  module_invoke('block', 'block_view', $block_id);
print render($block["content"]);


How to add a Custom Serializer to alter the Output of REST EXPORT

The plugin was missing the proper annotation (added now in the question). Views plugins use Annotation Discovery.

Adding something like the following solved the problem:

/**
 * My custom serializer
 *
 * @ViewsStyle(
 *   id = "hindi_custom_serializer",
 *   title = @Translation("Hindi Custom Serializer"),
 *   help = @Translation("Serializes views row data using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class HindiCustomSerializer extends Serializer {
  ....
}

Also worth noting that you don't need to include the implements CacheableDependencyInterface since is already declared by the \Drupal\rest\Plugin\views\style\Serializer plugin which you are extending from.


views_embed_view not working with multiple values argument

From views_embed_view doc comment block:

  @param ...

  Any additional parameters will be passed as arguments.

That means any params comes after params $name and $display_id will consider as contextual filer so you should call views_embed_view like:

views_embed_view('articles_list', 'block_1', '11', '13');

Take a look at Twig Views Module do the same.


Try first with a hardcoded node id. Once that is working, check if the node id in URL is working.


How would I paginate to 5 results in each page this query?

The better way to use db_select with called as query extender.

Here is an example

$query = db_select('rss_table')
  ->extend('PagerDefault')
  ->limit(5);

Then theme_pager() can be used for outputting a pager.

For more detailed example check out

Either way to use pagination

 function pager_array_splice($data, $limit = 9, $element = 0) {

             global $pager_page_array, $pager_total, $pager_total_items;

                $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
                $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
                $pager_total_items[$element] = count($data);
                $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
                $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
                return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

 $query = db_select('rss_table','t');
            $query->fields('t');

           $resultget=$query->execute();

           $result = $resultget->fetchAll();
              $limit=5;
              $output = pager_array_splice($result, $limit);
              $html='';

   foreach ($output as $dbrow) {

                    $items[]=(array)$dbrow;
                    $title = $dbrow->title;
                    $description = $dbrow->description;

$html.="         //HTML code here//       ";

 }

  $output1 = theme('item_list', array(
    'items' => $items));

    echo $html;

You can use it as in the form of table too or append it to the form as well. This is the way to use pagination.

Use this code to modify as per desired output.

Hope it works for you!