Share one back office (database) over three drupal websites

Teeyo,

You can do this with the domains module that can be found here:
https://www.drupal.org/project/domain

The installation instructions can be found here:
https://www.drupal.org/node/477372

Don't forget to edit your settings.php file ;-)

I used the module myself a couple of times, so if you need any assistance, just let me know :-)


Custom filter disabled after approximatively 45 minutes

After several tests and investigations, the culprit was the distant MySQL server which had a too short wait_timout. During cache refreshing operations the server used to go away before filters beeing applyed, leading to caching unfiltered pages. Using a MySQL server with no wait_timeout has solved this problem, without changing any setting elsewhere.


How can I add custom fields to Commerce Discounts?

You'll need to implement the field api to attach fields to certain entities.  Or you could within hook_entity_info() (I think), there is a 'fieldable' array key you could set to TRUE.  From there, you may need to programmatically add a field to it.  A good way to get field definition code is to use Field Inspector module, add a field to an entity using the UI, and export that field definition as a base to code yours.


Change content location in node template

you need to change the page-user.tpl.php to be able to remove the class from the content region. see here How can I create page.tpl for user’s profile page?


Associate an 'event' content type with a 'project' content type

First of all i totally agree with Molot's comment.

Just to help i will provide my opinion on how to do this:

Use the Node reference url widget module in combination with the Field Permissions module. With the 1st you can create an "Add an Event" link for every Project node and set the fallback behaviour of the field as autocomplete and with the 2nd you can set the permissions for that node reference field.


my base_path is empty do I need to set this manually or is something else wrong?

You haven't printed/returned any of your examples. It should be

print base_path();

global $base_path;
print $base_path;

print $GLOBALS['base_path'];

or

return base_path();

global $base_path;
return $base_path;

return $GLOBALS['base_path'];

Depending on the context.

A line with just a variable on it is valid PHP, but it won't do anything with the variable unless you tell it to.

EDIT

It's also worth considering what exactly you're expecting base_path() or $base_path to contain. The docs say this:

  Returns the base URL path (i.e., directory) of the Drupal installation.

  base_path() adds a "/" to the beginning and end of the returned path if the path is not empty. At the very least, this will return "/".

Unless you have your Drupal installation in a sub-folder of the web root (e.g. http://localhost/drupal/), this function/variable will always give you the value '/'.


How to make dynamic google map in block?

you could start by creating a custom module if you want , there's plenty of tutorials on the drupal website to help you get started then , in the block template add the js you need to create that map with the coordinates you want  . or using views , like in this post
 hope it helps


How can I programmatically display a block?

There are two types of blocks, and the method for rendering the two is a bit different:
Content Blocks
Content blocks are blocks that you create in the interface. They are much like nodes configurable data structures, with fields etc. If you want to render one of these, you can do what you would normally do with entities, load them and render them with the view builder:
$bid = ??? // Get the block id through config, SQL or some other means
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->
  getViewBuilder('block_content')->view($block);
return $render;

Plugin blocks
Blocks can also be plugin, defined in various modules. An example could be the breadcrumb block. If you want to render these, you will need to use the block plugin manager.
$block_manager = \Drupal::service('plugin.manager.block');
// You can hard code configuration or you load from settings.
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// Some blocks might implement access check.
$access_result = $plugin_block->access(\Drupal::currentUser());
// Return empty render array if user doesn't have access.
// $access_result can be boolean or an AccessResult class
if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
  // You might need to add some cache tags/contexts.
  return [];
}
$render = $plugin_block->build();
// In some cases, you need to add the cache tags/context depending on
// the block implemention. As it's possible to add the cache tags and
// contexts in the render method and in ::getCacheTags and
// ::getCacheContexts methods.
return $render;

Config entities
Shared for the two types are blocks, are that once you insert them into a region, you will create a config entity that has all of the settings for the block. In some cases it will be more useful handling config entities. Since the same block can be place in multiple regions with and with different configuration, it can get more tricky using the block config entities. The nice thing is that you might want to render a block with specific configuration, the bad thing is that config ids can change by messing with the interface, so the code might end up not working after letting users use the block interface.
$block = \Drupal\block\Entity\Block::load('config.id');
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);
return $render;


How add/update a record conditionally based on existence of primary key?

No, you do not "must know if the record already exists or not". If you will look at drupal_write_record source code, you will see these lines:

 if (empty($primary_keys)) {
    // We are doing an insert.

On else, this function will update instead of insert. The only problem with this is that Drupal's record system expects you will leave key management to Drupal. No saving at arbitrary key, because it breaks autoincrement.

If you need to manage keys on your own, use lower level db_merge function instead.


The input element has no close tag, so this is not really a well-formed question.

That said, what you are probably looking for is hook_form_alter() which you would implement in your own custom module to alter this particular form element.

Have a look at the #field_suffix propery for how you could append some arbitrary markup to your element.


How to set webform message below the submit button?

Try form alter method you can add text like following:

 $form['some_text'] = array(
      '#markup' => '
Some text
'
    );

Hope it will help!!


You can use a Taxonomy vocabulary with 2 level heirachy. Something like this:

Restaurants

Restaurant type 01
Restaurant type 02
...

Shops

Shop type 01
Shop type 02
...


That is coming from the AddThis service (media sharing icons). You maybe copied a link from there or if you are using that module, you selected to track the shared links.

If it's your widget, you can disable it by removing a line in JS (there is something like "track = true" in the widget code).


Refer to the field api documentation here. You do not have to add permissions to block the delete. All you need to do is add the "locked" attribute to the field definition.

  locked (integer): Whether or not the field is available for editing.
  If TRUE, users can't change field settings or create new instances of
  the field in the UI. Defaults to FALSE.


Although I didn't find how to do it with views, I have found an alternative solution using views hooks.
First I have to unset the pager, because I need all records to sort. Only if it's this view and this sort criteria.

function MYMODULENAME_filters_views_pre_execute(&$view) {
  if (('shop' == $view->name) && ($view->exposed_raw_input['sort_by'] == 'field_product_commerce_price_amount_decimal_desc')) {
    $view->query->set_limit(NULL);
    $view->query->set_offset(NULL);
}}

After this, I reorder the $view->results as I need in another hook:

function MYMODULENAME_views_post_execute(&$view) {

    if (('shop' == $view->name) && ($view->exposed_raw_input['sort_by'] == 'field_product_commerce_price_amount_decimal_desc')) {

    $milista = array();
    foreach($view->result as $clave=>$valor) {
        $prdd = node_load($valor->entity);
        $producto = commerce_product_load($prdd->field_product['und'][0]['product_id']);
        $price = commerce_product_calculate_sell_price($producto);
        array_push($milista,array(0=>$clave, 1=>$valor->entity, 2=>$price['amount']));
    }

    if ($view->exposed_raw_input['sort_order']=='ASC') $ordenado = SortByKeyValue($milista, 2);
    else $ordenado = SortByKeyValue($milista, 2, SORT_DESC);

    $listafinal = array();
    foreach($ordenado as $datos) {
        array_push($listafinal, $view->result[$datos[0]]);
    }

    // Now, the pager
    $itemsperpage = 16;  // default items per page
    if ($view->exposed_raw_input['items_per_page']) $itemsperpage = $view->exposed_raw_input['items_per_page'];
    $page=1;
    if (isset($view->query->pager->current_page)) $page =  $view->query->pager->current_page;

    $indice = $itemsperpage * $page;

    if (($indice>sizeof($listafinal)) && ($itemsperpage!=0)) $indice = sizeof($listafinal) / $itemsperpage;

    $listafinal = array_slice($listafinal,$indice,$itemsperpage);

    // Lastly, I change the view results
    $view->result = $listafinal;
  }
}

To sort the array, I used the next functions:

function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
    if (empty($data) or empty($sortKey)) return $data;

    $ordered = $data;

    if ($sort_flags==SORT_ASC) uasort($ordered,'cmpasc');
    else uasort($ordered,'cmpdesc');

    return $ordered;
}

function cmpasc($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] < $b[2]) ? -1 : 1;
}

function cmpdesc($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] > $b[2]) ? -1 : 1;
}

I hope this solution could help someone with my same use case.


How to make exposed timestamp filter accept human readable date

I ran into this issue on D7. I enabled the views query and noticed that the values were being passed as human date to the query rather than timestamp.

So what I did was use hook_views_query_alter and converted them to timestamp.

Example code (D7 code)

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'list_employers') {
    foreach ($query->where[1]['conditions'] as $con_key => $con_val) {
      if ((strpos($con_val['field'], 'node.created = ') !== FALSE) &&
        empty($con_val['value'])) {
        $date = $con_val['field'];
        $date = str_replace('node.created = ', '', $date);
        $date = date('m/d/Y', $date);
        $start = strtotime($date . ' 12:00 AM'); // convert to timestamp
        $end = strtotime($date . ' 11:59 PM'); // convert to timestamp
        unset($query->where[1]['conditions'][$con_key]['value']); // remove default condition
        $query->where[1]['conditions'][$con_key]['field'] = 'node.created';
        $query->where[1]['conditions'][$con_key]['value'][0] = $start;
        $query->where[1]['conditions'][$con_key]['value'][1] = $end;
        $query->where[1]['conditions'][$con_key]['operator'] = 'BETWEEN';
      }
    }
  }
}


I had custom code in my module...

function custom_node_presave($node) {

  if(isset($node->field_gallery_images)) {
    $node->field_gallery_images[LANGUAGE_NONE][0]['alt']=$node->title;
    $node->field_gallery_images[LANGUAGE_NONE][0]['title']=$node->title;
  }

}

Commenting it out stopped the error


Field Collection Major Error! Help Needed!

Check your maximum_input_vars setting in php.ini

I recently had a similar issues with a repeating field collection once we added a certain amount.  We bumped from 1000 to 10000, but I feel that was excessive.


Help me to understand what element_child() does

Suppose you have an array as the following (it's an array as accepted from the form API):

  $form['example_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Testing text'),
    '#default_value' => '',
    '#size' => 45,
    '#maxlength' => 45,
    '#required' => TRUE,
    '#description' => t('This is an example form demonstrating forms usage in the installer profiles tasks. Enter any text to see what happens.'),
  );

  $form['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
  );

  $form['errors'] = array();
  $form['#action'] = $url;
  $form['#redirect'] = FALSE;

If you execute element_children($form) will return an array containing the following indexes:

example_text
continue
errors

When $key is a string $key[0] is the first character of that string. The value of !isset($key[0]) || $key[0] != '#' is TRUE when the string $key is empty, or when the first character of that string is not #; array_filter() returns an array containing the keys and values for which the function referred as second argument returns TRUE.

The reason to do this is that, in the array used by the form API, keys starting with # are considered properties of that form field (or of the form), while keys that don't start with # are considered child of that form field; in the example code I used, '#redirect' is a property of the form, while 'example_text' is a form field that is child of the form.


Cannot load module uninstall page - says module does not exist

It turned out there was a markdown.settings entry in the database (in the config or cache_config table, I forget which). I deleted this row and then it was possible to install and then uninstall the module.


How can I change the display of government field in drupal commerce shipping address?

There is not currently a way to do this with the Address Field module. One of the Address Field maintainers has addressed that this in the works for 2.x release. In the meantime, the only way to do this is with a custom module. Someone has already written up an example of how to do this, specifically using Egypt as an example.


The error see to be on some cache file of drupal's admin_menu. The js aggregated file browser is requesting is being refused by Drupal by 503. You may get some pointers to this issue here https://groups.drupal.org/node/28604

Try clearing all the Drupal caches using "drush cc all" command. Are you using any js aggregation on Drupal side? Try changing to https://drupal.org/project/advagg?


How to remove "Time Zone" element "user_register_form" form using hook_form_alter

EDITED

As @KrishaWeb and @Kevin said:
Drupal 8 provided admin path at: admin/config/regional/settings to do it.


local language variables to use in code for queries(NOT GLOBAL LANGUAGE)

If the user is logged in, you can the global $user variable. The language object is then $user->language. For an anonymous user, you can use a session variable or a cookie. There's a module to use cookies: Language Cookie

To use a session variable:
On the "Detection and Selection" configuration page, set "Session" as the first detection method. To set up the variable, click the "Configure" link on that page. You should see

Then you just need links to set the user's language. Something like

http://yoursite.com/?language=en and http://yoursite.com/it?language=it
at the top of the page.


Render a referenced node via token in field

If I understand you correctly, you are trying to render a node inside another node.

In the past, I have used the Display Suite module to perform exactly this task.

With DS you can create custom view modes for content types. For example, for your media content type, you can create a new view mode called 'Embedded' and structure the display to include the fields you want.

Then, in your first content type, you can set the entity reference field to display a rendered entity and select the view mode you just created. The node page will display 'both' nodes as you've structured them.

Note: DS also exposes a Token view mode for you to be able to manage how the token version of a content type gets rendered. The token view mode is useful if you must use tokens (i.e. inject node into the body text), however rendering the entity just in the field formatting should cover a majority of the use cases.

DS is actually quiet deep in functionality - I use it for every build to structure content types, render html in the way I want, etc.

Hope that helps.


How to create page of multiple entity reference fields

In the parameter of your entity reference field, you can set the number of values allowed. Just set it to 2 to answer your needs.


OK i found the solution.

I had to use Arguments ( contextual filters ), and in argument i would use php code as validator and than just get todays day with simple code:

$day = date("j");
return $day;

Hope this helps someone in future.


How do I override the username in forum views?

Took me more than two months to figure this one out, but the answer is obvious once you know it.

Yes, there is an explicit hook for this. It is named: hook_username_alter.

D'oh!


Also you can use qTip

  qTips are stylish tooltips that can be configured and styled (more to
  come in later releases) to fit nearly any website's design.


How to programmatically change settings of input filters and activate them?

If you read the API page for the functions you mentioned in your question, you can easily see that there is a bug(or a feature) that it does not load populate $filter->filters indeed.

For a workaround, you could do something like this, with the help of filter_list_format()

$format_id = 'full_html';
$filter_id = 'your_filter';

First, load the format object

$format = filter_format_load($format_id);

Now, since we do not have the $filter->filters populated, we do so by loading the currently enabled filters.

$filters = filter_list_format($format_id);
foreach ($filters as $filter_id => $filter_opts) { //Convert to an array, which is expected by the save function.
  $filters[$filter_id] = (array) $filter_opts;
}

You can now make changes in the filter that you are interested in.

$filters[$filter_id]['status'] = TRUE; //Enable.
$filters[$filter_id]['settings']['something'] = 'foobar';

Inject filters to the format we have already loaded.

$format->filters = $filters;

Save!!

filter_format_save($format);


You can easily recreate your required feature by implementing a custom theme negotiator. This requires a little custom programming.

First, create an own module (in the following example, we'll call it mymodule). Within that module, create a mymodule.services.yml file, that lets Drupal know about your theme negotiator service:

services:
  mymodule.theme_negotiator:
    class: Drupal\mymodule\Theme\MyModuleThemeNegotiator
    arguments: ['@request_stack']
    tags:
      - { name: theme_negotiator, priority: 1000 }

The important parts here are the service tag theme_negotiator and a high enough priority, that ensures the negotiator will be called before any other negotiators. If you want to just change the default theme dynamically but let route specific theme negotiators still apply, use a priority < 0.

As you can see, we also mentioned your custom theme negotiator service class MyModuleThemeNegotiator located in the namespace Drupal\mymodule\Theme, and as argument the current request stack (as we can use it to get the request headers).

So let's create a folder src/Theme in your module and add a MyModuleThemeNegotiator.php like this:

namespace Drupal\mymodule\Theme;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * My Custom Theme Negotiator.
 */
class MyModuleThemeNegotiator implements ThemeNegotiatorInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a MyModuleThemeNegotiator object.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    // This method must return TRUE, if your headers
    // fulfill the desired requirements.
    if (
      $this->requestStack->getCurrentRequest()->headers->has('myheader')
      && $value = $this->requestStack->getCurrentRequest()->headers->get('myheader')
      && $value == 'myvalue'
    ) {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    // This method returns the ID of the theme that shall be
    // used, if your theme negotiator applies.
    return 'mytheme';
  }
}

Alter the header/values to match your requirements, clear your caches, and your theme should be applied.


How to get taxonomy term reference fields value translated in twig

Maybe I poorly explained the question but the solution was possible without preprocess.
In a content type, the referenced field with a taxonomy is called field_lorem
For this Entity reference field (Type of item to reference : taxonomy term), we select in Manage display (admin/structure/types/manage/content_type_name/display) « Rendered entity » instead of Label :

In the node template (node--lorem-ipsum-content-type--full.html.twig), we have simply {{ content.field_lorem }}
Then, we are able to see twig suggestion template name for this field based on taxonomy_term.html.twig :

In this twig, we can style independently all of the fields of the taxonomy term :
    {{ content.field_image[0] }}

    <p>{{ name[0] }}</p>

With this solution, translation of vocabulary terms works and we are able to have a custom template with all the field (in example an image field and name of the term)


Create a subtype of Panel & style it with a template

when I have to create this type of "landing pages" I m usually following these steps.
1/ The Layout.
Create a Panel Page. Admin > Structure > Panel > New panel page
1A/ If you want to get ride of header/footer region > there is an option for that.
1B/ If you want to keep these regions, but diplay other blocks, go to Admin > Block > your block > Configure > Visibility settings > and setup the thing whith the page settings.
2/ Then your content.
What I'm usually doing here is depending on what you try to achieve, but if you are displaying only 1 event content, create a content type event is probably not the right approach.
But my point is, now you can create a page with what you want. So think about what you want to display (do you need a view of items ? do I need a block ? some blocks? do I need some beans ?) and architecture it as it was a standard page. Just prefix all you items type with one commun name, so you will be able to retrieve them later.
I hope it helps
Cheers


How can I modify the Quick Edit Module to have a better UX for end-users?

You can check https://www.drupal.org/project/simpler_quickedit to do exactly what you need


Drupal : How to remove the  and  tag from content when using syntaxhighlighter

I can't answer this 100% but my first hunch was "hrm, filter ordering" and look, the project page draws your attention to:

  Very important!!!: ordered the input format filters as follow:

  HTML filter or Wysiwyg filter or whatever HTML filters you use. They must come before.
  Syntax highlighter. This come after any and all filters that can modify content input.
  Line break converter. This must be after, If you see <br/> at the end of every line in your output, then you know what's wrong.


Session is not getting maintain in settings.php drupal 7

You can't start session_start() the second time, since Drupal is already started it.

So either remove it, or wrap it into the condition, e.g.:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

Parsing input user variables is not a good idea, so it's better if filter it out, e.g.

$_SESSION['data'] = filter_input(INPUT_POST, 'year', FILTER_SANITIZE_STRING);

or better use db_escape_table().


Output tabs and content in different regions?

I am also trying to achieve the same result. I found this patch for an older version of quicktabs that never really got off the ground I guess.

http://drupal.org/node/1085116

I think it would be an appropriate feature.

EDIT:

Using a few ideas from the patch above, I have come up with a quick mod that splits the block into two blocks for each tab instance. Just edit your quicktabs.module as follows.

Simply add a second block definition:

function quicktabs_block_info() {
  $blocks = array();
  foreach (quicktabs_load_multiple() as $qt_name => $quicktabs) {
    $blocks[$qt_name]['info'] = $quicktabs->title;
    $blocks[$qt_name . '_qt_content']['info'] = $quicktabs->title . ' - Content';
  }
  return $blocks;
}

Then alter the block_view function as such:

function quicktabs_block_view($delta = '') {
  $block = array();

  // Check if it is the content block or not
  substr($delta, -11) == '_qt_content' ? $content_tab = 1 : $content_tab = 0;
  if($content_tab) {
    $delta = substr($delta,0, strrpos($delta, '_qt_content'));
  }

  if ($qt = quicktabs_build_quicktabs($delta)) {
    if (isset($qt['content']) && !empty($qt['content'])) {
      $block['content'] = $qt['content'];
      $block['content']['#contextual_links']['quicktabs'] = array('admin/structure/quicktabs/manage', array($delta));
      $block['subject'] = check_plain($qt['#title']);
      // remove either the tabs or content depending on the block
      if($content_tab){
        unset($block['content']['content']['tabs']);
      }else{
        unset($block['content']['content']['container']);
      }
    }
  }
  return $block;
}

It isn't the most elegant mod, but it does the job with little changes. All you have to do is add the original block (tabs) and the new contant block to wherever you want.


How to creat graphs/plots in Drupal, using python library matplotlib, updated in real time if possible?

I don't think there is an out-of-the-box solution for this. You probably already found the Charts module, but that does not seem to support on the fly updates.

So you would need to create your own module. You could then send your data with an ajax call and redraw the graph using that data  (the form api in Drupal 7 has excellent support for this; create a fieldset with its own div in which you put the graph). I'm working with Highcharts (which I really like) in my own modules and do something similar.


How to programatically hide node field on viewing?

You could make use of the hook_preprocess. If its on the specific entity such as the case of a paragraph it will look something like this where I am hiding some labels from a view based on some condition:
function [MODULE_NAME]_preprocess_paragraph(&$variables){
    $paragraph = $variables['paragraph'];
    // Get the parent bundle.
    $parentBundle = $paragraph->getParentEntity()->bundle();
    //check View type
    if ($parentBundle && $parentBundle == 'category_views') {
      if ($variables['content']['field_language_name']['#object']->get('field_language_name')->value != 'English') {
       //Removing labels
        unset($variables['content']['field_language_name']);
        unset($variables['content']['field_language']);
      }
    }
}


Two 'add to cart' buttons using different attributes

A. Enable Ubercart Cart Links (part of core).
B. Add necessary attributes and make sure you have a default attribute set.

With UC cart links, you can perform the add-to-cart functionality with many different AND DYNAMIC arguments. Without making a new add-to-cart button using Form API or complicated setups.

You can,

Add any quantity of any number of products to the customer's cart, with specific attributes and options for each added product, if applicable.
Display a custom message to the user.
Track the click for display on a store report.
Empty the customer's shopping cart.
Redirect to any page on the site.

Basically you make a URL that will, when opened, adds given items with given parameters to the current user's cart.

cart/add/e-p123_a1o2

See above link. When opened, it will first empty the cart (e), adds product/node ID 123 to the cart(p123) with attribute of ID 1 (a1) and that attribute's option ID 2 (o2).

You can see a very good help instructions on help section of uc_cart_links module's admin page (admin/help/uc_cart_links) .

You can build the URLs using Drupal's url() or l() functions.

Put these snippets in your node.tpl.php file of the product node type (node--product.tpl.php) where you want to display buttons.

<?php
 print l(
      t('Buy the large version'),
      'cart/add/'.$node->id.'_a101'
    );
  ?>

<?php
 print l(
      t('Buy the small version'),
      'cart/add/'.$node->id.'_a102'
    );
?>

if you are putting this code in a block or anywhere other than node.tpl.php or variants, change $node->nid to arg(1) . This arg(1) thing will only work if the button is being displayed in full content page.
if you are placing these buttons in a View, replace $node->nid with the appropriate node ID by adding a node: ID field and tokens.
If you want to see attribute and option IDs, go to attributes page and you will see the attribute/option ID which is a numeric one.

Good luck!


When I update my database schema with drush entity-updates. I get an error

Sounds like you are trying to update existing field order_total in uc_order. You can't update it since you have some data in it already. Remove content that uses it (orders), and try again.

Also note that drush entity:updates currently doesn't support all changes (e.g. changing table keys). See this Change Record for information on providing a hook_update(): https://www.drupal.org/node/2554097


flex slider with unique links and no links

To do that you can simply:

Add new text field to your content type and name it Link for example.
Add this field into your view, hide it by check 'Exclude from display' in views field settings and move it above your banner image field.
Open views settings for the banner image field, under 'Rewrite results
' section check 'Output this field as a link' and put replacement pattern for your link text field in 'Link path' input, e.g. [field_link].
Save your view and now each banner is linked to any path you specify in the Link text field or is not if you leave this field empty.


The admin/structure/types page is created via the hook_menu() in the node module:

$items['admin/structure/types'] = array(
  'title' => 'Content types',
  'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
  'page callback' => 'node_overview_types',
  'access arguments' => array('administer content types'),
  'file' => 'content_types.inc',
);

which shows that the page is generated by the node_overview_types function in content_types.inc:

/**
 * Displays the content type admin overview page.
 */
function node_overview_types() {
  $types = node_type_get_types();
  $names = node_type_get_names();
  $field_ui = module_exists('field_ui');
  $header = array(t('Name'), array('data' => t('Operations'), 'colspan' => $field_ui ? '4' : '2'));
  $rows = array();

  foreach ($names as $key => $name) {
    $type = $types[$key];
    if (node_hook($type->type, 'form')) {
      $type_url_str = str_replace('_', '-', $type->type);
      $row = array(theme('node_admin_overview', array('name' => $name, 'type' => $type)));
      // Set the edit column.
      $row[] = array('data' => l(t('edit'), 'admin/structure/types/manage/' . $type_url_str));

      if ($field_ui) {
        // Manage fields.
        $row[] = array('data' => l(t('manage fields'), 'admin/structure/types/manage/' . $type_url_str . '/fields'));

        // Display fields.
        $row[] = array('data' => l(t('manage display'), 'admin/structure/types/manage/' . $type_url_str . '/display'));
      }

      // Set the delete column.
      if ($type->custom) {
        $row[] = array('data' => l(t('delete'), 'admin/structure/types/manage/' . $type_url_str . '/delete'));
      }
      else {
        $row[] = array('data' => '');
      }

      $rows[] = $row;
    }
  }

  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. Add content type.', array('@link' => url('admin/structure/types/add'))),
  );

  return $build;
}

So, one way I can see to do this would be to in your module, do a hook_menu_alter() and point the page callback to a function in your module and just add to the core one's functionality, eg, something like this:

function YOURMODULE_menu_alter(&$items) {

  $items['admin/structure/types']['page callback']='YOURMODULE_node_overview_types';
  unset($items['admin/structure/types']['file']); // or point it to YOURMODULE_pages.inc if need be

}

and then basically just copy the code from node_overview_types() into YOURMODULE_node_overview_types() and then put in your functionality, eg, change the colspan to 5 or 3 and add in the l() to your menu item.

NOTE:  Of course, if the node module is ever updated you'll have to keep that in mind and possibly redo this.  So, yes, since a render array is returned, you could instead modify this in any number of hook alters before the page is rendered. If you want to look into this approach, Render Arrays in Drupal 7 is a good place to start.

ADDITION:

For completeness, this is one way you could use a hook_page_alter():

function YOURMODULE_page_alter(&$page) {

  if ($_GET['q']=='admin/structure/types') {

    $types = array_keys(node_type_get_types());

    $page['content']['system_main']['node_table']['#header'][1]['colspan']++;
    foreach($page['content']['system_main']['node_table']['#rows'] as $type => &$row) {
      $row[]='New menu link goes here for ' . $types[$type];
    }

  }

}

instead of the hook_menu_alter() approach above.  But also, obviously, it too relies on the structure of the array returned by the node module.


Ubercart thumbnail saving in sites/default/files - Its messy - How would I get it to save in a specified folder?

Try the File (Field) Path Module:

  The File (Field) Paths module extends the default functionality of
  Drupal's core Upload module, the FileField module and many other File
  Upload modules by adding the ability to use node tokens in destination
  paths and filenames.

  In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.

This can be applied to the Field holding the image


Fetching node field values programmatically

I think you should leave the database structure and focus on the entities concept.

This brings you to a simpler approach using entityTypeManager  to get nodes and filter them by whatever you want.

$query = $this->entityTypeManager()->getStorage('node')->getQuery();
$nids = $query->loadByProperties(
    [
        'type' => 'content_type',
        'status' => 1,
        'field_name' => 'value'
    ])
    ->execute();


Adding an active menu trail to the main ul, in the html.tpl.php?

Use menu_tree_page_data to get an array of the menu items. Set the trail accordingly there.

Example: http://brightplumbox.com/30Drupal7API/#/7/4


Trying to update taxonomy menu item with hook_taxonomy_menu_update

If you're just adding a class, I wouldn't rely on a hook from the taxonomy menu contributed module at all. Do it at the theme level like this.


How to stop Drupal for setting node changed date on creation?

You should be able to preserve the original changed time by first setting a custom property on the node object, say $node->modified, in your migration script prior to calling node_save(), and then implementing the node_presave hook:

/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {
  $node->changed = $node->modified;
}

This will work since node_save() sets $node->changed prior to calling all modules which implement hook_node_presave().


How to programatically add block to Drupal 7 page tpl AND respect visibility rules?

Turns out the solution was in how I was rendering the blocks.

Using this code to render my block added the block to Drupal's "knowledge" of the block being on the page.

$block = block_load($module, $bid);
$blockStuff = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = drupal_render($blockStuff);
print $output;


What causes my Rules error when trying to send an email if profile field contains some value?

Use Data selector account:field-YourField


How to disable breadcrumbs for certain pages?

Your Breadcrumb is a block that you place in Block Lay-out. Then just change its visibility.


How to force a specific user in the Author textfield in Rules Create Entity

You will have to fetch a user entity first. There's an action called fetch entity by id, which will allow you to select user as type and specify the user id.

At the bottom you can assign label and machine name for the variable that will be made available.

make sure to do the fetching before creating the new entity, else this variable won't be available.


There's no native URL field type in Drupal 7 but the Link module provides one with lots of features

  With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs.

Profile2 profiles are entities so adding a link field to one will be an easy task through the UI.


Separating user edit form into small descent form

No need for custom forms!

Profile2 will do all of the items you require! Here is the handbook to get you started.

This will let you have different forms (tabs) on the /user page and you can also choose which of those "subforms" you want on the user registration.


looking for views gallery module compatible with lightbox module

Have you tried Views Slideshow with Views Slideshow Xtra?
Here are some more details about these modules (quotes included are from their project pages):

Views Slideshow:

... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

Views Slideshow Xtra:

... is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in  overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.


The field collection is an entity in it's own right; the values stored against your node are a list of field collection item ids that you'll need to load manually to loop over. Something like this:

// Get the field collection items.
$fc_fields = field_get_items('node', $node, 'field_field_collection_field');

// Extract the field collection item ids
$ids = array();
foreach ($fc_fields as $fc_field) {
  $ids[] = $fc_field['value'];
}

// Load up the field collection items
$items = field_collection_item_load_multiple($ids);

// Loop through the items and extract field values
foreach ($items as $item) {
  $link_fields = field_get_items('field_collection_item', $item, 'field_link');
  $link = array_shift($link_fields);
  $url = $link['url'];

  $site_name_fields = field_get_items('field_collection_item', $item, 'field_site_name');
  $site_name = array_shift($site_name_fields);
  $name = $site_name['value'];
}


How can I show only 3 countries in country list (select box)?

I think you are trying to shorten the country select box in user registration form and user edit form. You should not hack the contributed modules. You could create your own module and override the forms using hook_form_alter().

I assume you have a custom module and you could implement hook_form_alter() to update the country list as you need. Here is the code in mymodule.module tested in my test site:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if( $form_id == 'user_register_form' || $form_id == 'user_profile_form' ){
        $countries = array( // define the countries you want
            93  => 'Afghanistan',
            355 => 'Albania',
            213 => 'Algeria'
        );
        $form['sms_user']['gateway']['country']['#options'] = $countries; // update sms country select box.
    }
}

But, to access the field group sms_user, your module must have the heaviest weight, otherwise you won't be able to update $form['sms_user']['gateway']['country'].
You can make sure your module is heaviest by creating yourmodulename.install.

/**
 * Implementation of hook_install()
 */
function mymodule_install(){
    # Fetch max module weight from "system" table.
    $max_weight = db_query("SELECT MAX(weight) FROM {system} WHERE type = 'module'")->fetchField();
    # Make sure this module is the heaviest one in order to run last
    db_update('system')
        ->fields(array('weight' => $max_weight+1))
        ->condition('name', 'mymodule')
        ->execute();
}
/**
 * Implementation of hook_uninstall()
 */
function mymodule_uninstall(){
    db_delete('system')
        ->condition('name', 'mymodule')
        ->execute();
}

If you are expert, you can tweak the weight field of your module in the system table to make it heaviest without creating yourmodulename.install, but not recommended. You may need to flush all caches after you implemented this.


Mapping existing file against a new content type

I think the File Field sources module will solve your problem.  (The D7 version works directly with the core Field module).  It will, among other things, allow you to re-use files by an auto-complete textfield.

Btw: Any file appearing in file_managed can only appear once in that table, so you should not be allowed to do what you try to do in your first approach.


In file settings you specify a temp path and a files path, which is what is used by Drupal.

The temp path which could be /tmp, but it could also be default/files that is entirely up to you. the temp file folder is where files are uploaded to after being submitted in a form. After validation checks, file_save_upload should be used to save the file. There is no reason for the file to be saved to the default/files folder and then be moved, as it can be saved directly to whichever folder you want. I do believe that is how the imagemodule does it..


Using Feeds to import multiple languages

Import from two xml files (on for each language), my empiric solution  :

I created two feed imports.
I forced the language field for each one.
Two separated nodes were created for each content (one in each language) but it didn't links the translations.
So I used a SQL query to finish the job, it's based on the feeds uuid

Note: In order for this to work your GUID must match between the two sources. If you have set that to the node title it is important that you turn off the option to replace content as it will update the previous import :/

UPDATE
    node n,
    feeds_item lng1,
    feeds_item lng2
SET
    n.tnid = lng1.entity_id
WHERE
    (
        n.nid = lng1.entity_id
        OR
        n.nid = lng2.entity_id
    )
    AND lng1.id='feeds_importname_for_lng1'
    AND lng2.guid=lng1.guid
    AND lng2.id='feeds_importname_for_lng2'


I would recommend using the Flag module, as it provides this functionality for users upon install. The Nodequeue module is intended for admin-configured lists.


How can I enable JavaScript form validation for AJAX submit buttons?

I had the same question this morning. Here's how I got it to work.

Add an invisible button and specify the #ajax on that.

$form['actions'] = array(
  '#type' => 'actions',
  'submit' =>array(
    '#type' => 'submit',
    '#value' => 'Submit',
  ),
  'validation-hack' => array(
    '#type' => 'button',
    '#value' => 'validated',
    '#attributes' => array('style' => 'display:none'),
    '#ajax' => array(
      'callback' => array($this, 'doSomething'),
      'event' => 'click',
      'progress' => array(
        'type' => 'throbber',
        'message' => 'Example...',
      ),
    ),
  ),
);

Then add a submit handler on the form that stops the form submission and then calls click on the hidden button.

  (function($, Drupal) {
    Drupal.behaviors.example = {
      attach: function(context, settings) {
        $(context).find('#example-form-id').submit(function(evt) {
          evt.preventDefault();
          evt.stopPropagation();
          $('#edit-validation-hack').click();
        });
      }
    }
  })(jQuery, Drupal);

Hope this helps you, or anybody else that may stumble across this.


According to  t() documentation you can pass specified language it t() function.

As Example below code return French translate of language string without consider current site language.

  $fr_value = t('language', array(), array('langcode' => 'fr'));


How do I upload an image to the public:// directory?

If you want to create the code for saving the image yourself, you could do

$response = drupal_http_request($url_image);

if ($response->code == 200){
  $file = file_save_data($response->data, 'public://' . 'foldername/' . $filename);
}

And in $file->fid you'll find the fid you need.


How to get more info on error during clone?

This looks like an SQL error and not an Aegir one so I'd recommend searching for that error specifically.  However, the conventional way to get more output for a failed Aegir task would be to run the following on the CLI:

drush @hostmaster hosting-task --force --verbose --debug TASK_ID


Fields are definitely the best method for storing this data.

You can combine fields with the Field Permissions module:

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

With that module you'll be able to specify exactly which fields the user should be able to view/edit.


Entity base field requires value despite setRequired(FALSE)

Your field was likely created in the database with setRequired(TRUE) which means your field cannot contain NULL values. If you change your field to setRequired(FALSE), then NULL values will be allowed.

Inspect your *_field_data table and check if the field schema IS_NULL = TRUE, if not, then you will need to update your field schema by running an update hook. See Write update functions for entity schema updates for information on how to update your entity schema.

If you have not deployed your module anywhere other than locally then it should be safe to modify your database directly without creating an update hook.


How to properly restrict node access (including update/delete) based on field value?

What's the proper way to implement the node restriction?

Don't re-invent the wheel ... The Group module is what you should be looking at.
It creates groups as entities, making them fully fieldable, extensible and exportable. For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

More info

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


You need 2 extra ANDs, right below the highest level (1st) OR.

And EACH of the 2 ORs you already have, and the Data comparison that preceeds those ORs, you need to move them below the extra AND. So that in the end it looks like so:

OR

AND

Data Comparison (A=Maandag)

OR

Text Comparison (B=16:00)

Text Comparison (B=17:00)

Text Comparison (B=18:00)

Text Comparison (B=19:00)

AND

Data Comparison (A=Woensdag)

OR

Text Comparison (B=13:00)

Text Comparison (B=14:00)

Text Comparison (B=15:00)

Text Comparison (B=16:00)

Here is how "I" would translate the above logic:

We accept a date that is either on Monday (line 2 to 8) OR (line 1) Wednesday  (line 9 to 15).
If you want a date that is a Monday (= line 3), we insist (via the AND in line 2) that you pick a timeslot that fits for us on Monday.
To pick a timeslot for Monday, you have a choice (OR in line 4) of 4 options (ie those in line 5, 6, 7 or 8).
Similar Rules, oeps rules, apply for Wednesday, as expressed in line 9 to 15.

If after these changes your Rules Action(s) still don't get executed (because something else is wrong in any of these Rules Conditions, and/or you're not using an appropriate Rules Event), then move on to Rules debugging, as explained in "How can I display the value of a variable inside a condition?".

PS: just to make sure your "Text Comparison" condition behaves as you expect/hope it to do, create a temporary clone of your rule with only 1 Rules Condition (= 1 such text comparison), with same Rules Event and same Rules Action. That way you can either narrow down your problem, or exclude that as a possible reason why it still doesn't work.


How can I print render just location city in teaser view

The dirty way is : don't user "render".

Just print it:

print $content['field_event_location']['und'][0]['city'];


Varnish 3.0 and Drupal 7, get registered user to always have non-cached content

You seem to be missing Vary: Cookie in addition to Vary: Accept-Encoding. You may add it in vcl_deliver using something like this:

if (resp.http.Vary !~ "Cookie") {
    set resp.http.Vary = resp.http.Vary + ", Cookie";
    set resp.http.Vary = regsub(resp.http.Vary, "^,\s*", "");
}


How to find node that a file is attached to

Create a view of files.

Add a relationship 'File Usage: Content'

Add a field 'title' and set the relationship on it to the one you created above.

Adjust the rest of the view as needed, ie add contextual filter Content: Image:fid


How To Wrap Drupal Form API in html div structure [in my Drupal theme files (.tpl file)]

It will be hard to implement this html as it is. You have to create a custom form using form api of drupal and use its arguments to make the html nearly same like your design. But still there will be css changes respectively. Let me edit Email field for you

    function mycustomform($form, &$form_state){
    $form['email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
      '#prefix'=>'

',
      '#suffix'=>'

',
      '#attributes'=>array('placeholder'=>'Enter your email address')
    );

    $form['password'] = array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
      '#prefix'=>'

',
      '#suffix'=>'

',
      '#attributes'=>array('placeholder'=>'Enter your password') // No use because it will show dots or *
    );
    $form['login'] = array(
      '#type' => 'submit',
      '#value' => t('Login'),

      '#prefix'=>'
',
      '#suffix'=>'',
      '#submit'=>'custom_user_login',
      '#attributes'=>array('class'=>array('primary_btn')) // No use because it will show dots or *
    );
    $form['register'] = array(
      '#type' => 'submit',
      '#value' => t('Register'),
      '#submit'=>'custom_user_register',
      '#prefix'=>'',
      '#suffix'=>'
',
      '#attributes'=>array('class'=>array('primary_btn')) // No use because it will show dots or *
    );
return $form;
}

function mycustomform_validate($form, &$form_state){
    //Add checks for already registered user
}

function custom_user_login($form, &$form_state){

      if($uid = user_authenticate($username=$form_state['values']['email'], $password=$form_state['values']['password']))
    {
      user_login_submit(array(), array('uid' => $uid));
      return true;
    }
    else
    {
        return false;
    }
}

function custom_user_register($form, &$form_state){
    $new_user = array(
  'name' => $form_state['values']['email'],
  'pass' => $form_state['values']['password'], // note: do not md5 the password
  'mail' => $form_state['values']['email'],
  'status' => 1,
  'init' => $form_state['values']['email'],

);

// The first parameter is sent blank so a new user is created.
$user = user_save('', $new_user);
if($user->uid){
drupal_set_message('User saved successfully');
}else{
    drupal_set_message('Error in saving user','error');
}
}

Hope it will help you.


I was able to find the webform-calendar.tpl.php file that you used Drupal 7 - Change webform date select to textfield with calendar popup.

Basically what it does is adds a text field and hides the drop down date field.

I figuredout that the date field output is controlled in webform.js

You'll need to change from

  // Set up the jQuery datepicker element.
  $calendar.datepicker({
    dateFormat: 'yy-mm-dd',
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('-');
      $webformDatepicker.find('select.year, input.year').val(+date[0]).trigger('change');
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[2]).trigger('change');
    },
    beforeShow: function (input, inst) {
      // Get the select list values.
      var year = $webformDatepicker.find('select.year, input.year').val();
      var month = $webformDatepicker.find('select.month').val();
      var day = $webformDatepicker.find('select.day').val();

      // If empty, default to the current year/month/day in the popup.
      var today = new Date();
      year = year ? year : today.getFullYear();
      month = month ? month : today.getMonth() + 1;
      day = day ? day : today.getDate();

      // Make sure that the default year fits in the available options.
      year = (year < startYear || year > endYear) ? startYear : year;

      // jQuery UI Datepicker will read the input field and base its date
      // off of that, even though in our case the input field is a button.
      $(input).val(year + '-' + month + '-' + day);
    }
  });

to

  // Set up the jQuery datepicker element.
  $calendar.datepicker({
    dateFormat: 'dd-mm-yy', // changed
    yearRange: startYear + ':' + endYear,
    firstDay: parseInt(firstDay),
    minDate: startDate,
    maxDate: endDate,
    onSelect: function (dateText, inst) {
      var date = dateText.split('-');
      $webformDatepicker.find('select.year, input.year').val(+date[2]).trigger('change'); // changed
      $webformDatepicker.find('select.month').val(+date[1]).trigger('change');
      $webformDatepicker.find('select.day').val(+date[0]).trigger('change'); // changed
    },
    beforeShow: function (input, inst) {
          // Get the select list values.
          var year = $webformDatepicker.find('select.year, input.year').val();
          var month = $webformDatepicker.find('select.month').val();
          var day = $webformDatepicker.find('select.day').val();

          // If empty, default to the current year/month/day in the popup.
          var today = new Date();
          year = year ? year : today.getFullYear();
          month = month ? month : today.getMonth() + 1;
          day = day ? day : today.getDate();

          // Make sure that the default year fits in the available options.
          year = (year < startYear || year > endYear) ? startYear : year;

          // jQuery UI Datepicker will read the input field and base its date
          // off of that, even though in our case the input field is a button.
          $(input).val(day + '-' + month + '-' + year); // changed
        }
      });

4 lines changed, I marked them with // changed

Save the new file in /sites/themes/YOURTHEME/js/webform.js

You can use hook_js_alter to replace the JS file.

/*
 * Implements hook_js_alter
 */
function YOURTHEME_js_alter(&$javascript) {
  if (!empty($javascript['sites/all/modules/webform/js/webform.js'])) {
    $javascript['sites/all/modules/webform/js/webform.js']['data'] = drupal_get_path('theme', 'YOURTHEME') . '/js/webform.js';
  }
}


Table in custom form + empty values in form_state

When you want to get the HTML of the table you must use the renderer service.

In Drupal 8:

$html = \Drupal::service('renderer')->render($form['table']);

Or better, use dependency injection :)

In Drupal 7:

$html = drupal_render($form['table']);


In Style settings you can add a class to your fields.

To achieve your look, move the picture above the title.
Then add css class to your picture field.
Then add the following css code to your theme's .css file .pictureclass { float: left; }

BONUS INFO
In Format Settings, you can add classes to your rows

In css class, you can add a class to your entire view


Is it possible to make the Book Outline a mandatory field when creating a new book page?

EDIT: On review, I see this question is D7 specific. There may be subtle things wrong with my code snippet. It should be fundamentally the same.

If something should never happen, I prefer to make it never-an-option.

If you want to make all book pages default to being new books:

/**
 * Implementation of hook_form_FORM_ID_alter() for node_form.
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (book_type_is_allowed($form['#node']->type)) {
    // Remove the "none" option.
    unset($form['book']['bid']['#options'][0]);
  }
}

Once that's done, you can leave it be or set $form['book']['bid']['#default_value'] explicitly to be a new book, or a specified book bid of your choice. It will probably naturally fall into creating new books, as that is the first option in the selector after you remove none.


How do I add a password field on registration form?

Go to Account Settings (admin/config/people/accounts) and uncheck the Require e-mail verification when a visitor creates an account checkbox.

  With this setting disabled, users will be logged in immediately upon
  registering, and may select their own passwords during registration.

If you want both (Password field + email verification), use the User registration password module


Go to your parent menu item, edit it and click on the 'Show as expanded' checkbox. Now all the children menu items should be visible from the top level.


1) Hide all your fields (check mark exclude from display)

2) Add a Custom Field

3) In your custom field, put everything there using the tokens. (click on relacement patters, it will show you the tokes u can use).

For Example:

[logo]

[off]

[download cupon]

[expires]

Then go to the jcarusel module folder and look for the css file and strip the css that you don't want (like the current borders) and use your "whatever" div to create your own borders.


You need to use another flag to identify anonymous visits.
Flag value is always boolean , true or false. So you cannot have a default value to identify whether it's visited by anonymous.

What you can do is use a rule

Check visitor is anonymous
If yes set a flag called "anonymous_visit" to that particular node
Use above information in your views to display nodes

Above rule sets flag on view of a node, If you want to add flag by default to a content then your rule event should be on node create add xx flag to node...

You can also use flag api with node api hooks to achieve above.. See flag api below example..

Flagging or Unflagging an item
You use the $flag->flag() method to either flag or unflag an item. Example:

<?php
$flag = flag_get_flag('bookmarks') or die('no "bookmarks" flag defined');
// Flag node #456:
$flag->flag('flag', 456);
// Unflag node #456:
$flag->flag('unflag', 456);
?>
The signature of this $this->flag() method is:

<?php
function flag($action, $content_id, $account = NULL, $skip_permission_check = FALSE)
?>


maxlength depending on nodetype (contenttype)

You could use hook_node_presave to set the maximum length of a fields value before the node is saved or inserted in the database.

For example, to force a field field_dummy for a node of type article to a maximum of 50 characters you could do like this:

function HOOK_node_presave($node){
  if($node->type == 'article'):
    // force the field to max 50 characters
    $node->field_dummy[$node->language][0]['value'] =
       substr($node->field_dummy[$node->language][0]['value'], 0, 50);
  endif;
}


Drush 8.0.3 is unable to update D7 modules

You could be hitting this issue - there is a bug if you have a version control system such as SVN installed.

If it is this bug, the error should go away if you pass --version-control=backup.  Of course you will then lose some integration with your version control system.


there is no way to add a stylesheet and be global for all the themes you have inside sites/all/themes

The unic way is that all your different 40 themes were subthemes of one parent theme then you can have your styles in the parent theme and all your subthemes will inherit the styles of the parent, there is no other way...


How can I change the way content titles are generate and displayed?

If the title field is uneditable, that might have been done through another module or custom code (Automatic Entity Label?) that is setting the title text. I would edit the content type, and look down at the bottom and see if there are any content type settings that would be determining the title (not the "manage fields" page, but the main edit page for the content type). You might be able to re-enable editing.
https://www.sierraclub.org/admin/structure/types/manage/station_playlist (? not sure if this link is exactly right, a guess...)

A work around would be to add a custom field that is your custom title, and then edit your view(s) to use the custom title if it exists. (The short version of how to do that would be to make the regular title hidden, and then add the new field, and use the if empty setting to populate with the text from the title.)

But figuring out how the title field is made uneditable and fixing it from there would probably be best in the long run.


It got worked by adding language and format for terms. Please see below code.
  Given "test_new" terms:
    | name           | parent      | description          | format     | language |
    | Test term one  | Test parent | term one description | plain_text | en       |


How to merge two different pages on one page

Hide the tab on the user account page.

function MY_MODULE_menu_alter(&$items) {
  $items['user/%user_category/edit/profile']['access callback'] = FALSE;
}

Then, merge the profile2 form with the user account form itself :

/**
 * Implements hook_form_FORM_ID_alter() for the user edit form.
 */
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if (($type = profile2_get_types('profile')) && $type->userCategory) {
    if (empty($form_state['profiles'])) {
      $profile = profile2_load_by_user($form['#user'], 'profile');
      if (empty($profile)) {
        $profile = profile_create(array('type' => 'profile', 'uid' => $form['#user']->uid));
      }
      $form_state['profiles'][$profile->type] = $profile;
    }
    profile2_attach_form($form, $form_state);
  }
}

From http://www.jide.fr/english/add-profile2-form-directly-on-the-user-edit-form


"Illegal choice full_html in Text format element" when submitting form programatically

You can try this.It works i think so

$form['formItem'] = array(
     '#type'=>'text_format',
     '#title' => t('Field Label'),
     '#value' => 'This is my value',
     '#format'=>'full_html',
);


Try to specify the destination part of your drush command without the quotes, like so:

  --destination=sites/all/modules/_features

Curious to see if this helps ...

Updated answer, now related to the new error after "edit1" in the question: Try running the comment again, but now with this slightly corrected command (note the "--destination" instead of "-destination"), like so:

  $ drush @sitebl fe --d --destination=sites/all/modules/_features  briselames_content_type  node:page_lycee


How to make autocomplete return nid and name?

Take a look at the examples module's ajax_example_autocomplete.inc file. You'll need to add a validation function that looks up the nid from the node->title:

  $result = preg_match('/\[([0-9]+)\]$/', $title, $matches);
  if ($result > 0) {
    // If $result is nonzero, we found a match and can use it as the index into
    // $matches.
    $nid = $matches[$result];
    // Verify that it's a valid nid.
    $node = node_load($nid);
    if (empty($node)) {
      form_error($form['node'], t('Sorry, no node with nid %nid can be found', array('%nid' => $nid)));
      return;
    }
  }
  // BUT: Not everybody will have javascript turned on, or they might hit ESC
  // and not use the autocomplete values offered. In that case, we can attempt
  // to come up with a useful value. This is not absolutely necessary, and we
  // *could* just emit a form_error() as below.
  else {
    $nid = db_select('node')
      ->fields('node', array('nid'))
      ->condition('title', db_like($title) . '%', 'LIKE')
      ->range(0, 1)
      ->execute()
      ->fetchField();
  }


Using Drupal 101, and assuming that you have one Department page per department, and one Employee page per employee, and assuming that each employee can be associated with more than one department ...

First add a node reference field to the Employee content type (field_department). Set it to reference the Department content type and set the number of values to unlimited.

Then create a view of Content type:Employee.

Add a Relationship on Content:Department (field_department) and make it Required.

Then add a Contextual Filter on Content:NID. Have it use the Relationship you have just created and configure it to Provide Default Value: Content ID from URL when the filter is not available.

Under Advanced > Query Settings check Distinct. This type of query might produce duplicates.

Place the View block on the Department page, and this will restrict the list to employees related to the department currently being viewed.

A similar approach can be used with term reference fields, but you would require two relationships (first to the term, then from the term to the other content type). I cannot speak about the List module as it appears to be discontinued on D.O.


I have do a preprocess function in my file ".module" like this

/**
 * Implements hook_preprocess_page()
 */
function MYTHEME_preprocess_page(&$vars) {
  $vars['get']['date'] = \Drupal\Component\Utility\XSS::filter($_GET['date']);
}

but not sure that correct


Paginate views by first letter of Node title

Views comes with a nice default glossary view out of the box. Go to /structure/views/view/glossary/edit, enable it and set it to filter for your content type. viola.

And in case you are  wondering where the Magic happens then you would find it in the contextual filter MORE options.


How to resolve the 403 error when creating a new node via RESTful module?

For headers you only need Content-Type and Authorization.

Your POST url needs to be http://fischer.dev:80/entity/node (this is only for POST).

If you are going to PATCH or DELETE, the url would then be the url of the node, Ex: http://fischer.dev:80/node/1 that you want to update (patch) or delete.

PS: Not really sure why you have port numbers in your url, and why you were using port 81 instead of 80, using http://fischer.dev/entity/node should be good enough.


Ajax problem on node edit page trigger whole submit

The problem was due to the contrib module admin_language not handeling properly the ajax callback url on node edit page.

I had to add these url to be included in the config "Use administration language on only the listed pages." :

system/ajax
media/ajax
media/ajax/*
media/*/ajax


Geofield Display Format Data Options (Using Bounding Box)

i had the same problem and found a quick and dirty solution:
in the referenced file Point.class.php the following function throws the error:

  public function __construct($x, $y, $z = NULL) {
    // Basic validation on x and y
    if (!is_numeric($x) || !is_numeric($y)) {
        throw new Exception("Cannot construct Point. x and y should be numeric");
    }

adding "echo $x;" before the "throw" showed me the problem:
the numbers for $x and $y where in the wrong "local" format.

e.g. 9,34124 instead 9.34124

  public function __construct($x, $y, $z = NULL) {
    $x = floatval(str_replace(',', '.', str_replace('.', '', $x)));
    $y = floatval(str_replace(',', '.', str_replace('.', '', $y)));
    // Basic validation on x and y
    if (!is_numeric($x) || !is_numeric($y)) {
     throw new Exception("Cannot construct Point. x and y should be numeric");
    }

is my dirty fix for this...

regards
nicolaj


Attach view of content by author only to the user page

I haven't used this module, but according to the project page:

The placement of the view in the entity's content can be reordered on
the "Field Display" administration page for that entity, like other
fields added using the Field UI module.

So you should be able to configure this at Manage Display for users: /admin/config/people/accounts/display.  You can customize the display separately for Default and Compact, and you can create more view modes (different display configurations) as necessary.
Another way to do what you're doing (attach a view to users only on the user page) would be to use Layout Builder, which is included standard with Drupal.

Make a view that shows the user's content with contextual filters in a block.
Enable Layout Builder module.
On /admin/config/people/accounts/display, check Use Layout Builder, open Layout Builder, and then add the block.


You can try this code:

use Drupal\menu_link_content\Entity\MenuLinkContent;

$node_id = 1;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

dpm($result);


How to integrate some fields into a node more efficient?

if it's Drupal 7, I think this can works.

if(isset($content['fieldname'])):

echo render($content['fieldname']);

endif;


Media with WYSIWYG not converting media tags to markup

I was having this same problem and have solved it. My problem was not rendering the text in the correct format in the template. So if you are using a custom theme, .tpl or whatever you need to make sure you render it correctly. I had it like this:

<?php print $node->field_main_body['und'][0]['value'] ;?>

Changing this to proper rendering using field_view_field fixed it for me:

<?php print render(field_view_field('node', $node, 'field_main_body', array('label'=>'hidden'))) ;?>

Hope that's helpful


How to unpublish content that is under moderation

You can enable the default revision for all the states. If there is any transition in any state from publish to draft or any state.


Field_image empty after database export and import

I am assuming that the Images are showing as uploaded in the backend. But when trying to view it on the front it is coming broken. you can check the file system path in the drupal admin it should be sites/default/files

if the file path is not the issue, then look at here(https://www.drupal.org/node/920840) there was a thread going around the warning and seems to be resolved. #22 could be the solution to look.


Regardless the used VCS, here is what I put in my code repository

A .make file used to download Drupal core, contrib modules and contrib themes and apply patches (if required)
a module folder with only the custom modules
a themes folder with only the custom themes
A build script to

run drush make on the .make file to download Drupal core and contribs to a (VCS ignored) dist folder
copy the modules folder to dist/sites/all/modules/custom
copy the themes folder to to dist/sites/all/themes/custom

This to

properly track changes to the custom code
properly track used core and contribs versions (in the .make file)
prevent core or contribs hack
allow proper patching (Drush Make requires the applied patches to be on publicly accessible)

For the build script, I use Phing but any scripting languages (ant, bash, php, ruby, etc.) could be used. With some additional work, the build script can also be used to run automated test (SimpleTest) and code validation (php -l and Coder Review).

I try to have as much configuration as possible exported into code. Mainly by using exportables through the Features module and by having a project specific profile to define and update non-exportable configurations through its hook_install and hook_update_N implementations. See The Development -> Staging -> Production Workflow Problem in Drupal and the Code driven development: using Features effectively in Drupal 6 and 7 presentation.


Is it possible to show notification in MacOSX or Safari?

I dont know what the Wordpress module does.

But for the server running the website you can send notifications to the OS using Drush Notify (built into Drush version 6).

From the readme it has a few example functions:

drush_notify_send(): Send a message to notifications center and audio.
drush_notify_send_text(): Send a message to notification center.
drush_notify_send_audio(): Send a message to audio system.


Expose a view's filters both in a block, and in the actual view

The accepted answer did not work with Drupal 7 for me.
I followed http://www.drup-all.com/blog/exposed-filters-form-your-custom-block-drupal-7 with success. Code below:

/** implements hook_block_info() **/
function test_block_info(){
  $blocks = array();
  $blocks['custom_exposed_filter_form'] = array(
    'info' => t('Exposed filter form'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/** implements hook_block_view() **/
function test_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'custom_exposed_filter_form':
      $block['subject'] = t('Exposed filter form');
      $block['content'] = _test_get_exposed_filter_form();
    break;
  }
  return $block;
}

/** Function to get the Exposed filter form **/
function _test_get_exposed_filter_form(){
  // Get a view from the database or from default views . "test" is the view name.
  $view = views_get_view('test');
  // Set the display as current.
  $view->set_display('page');
  // Acquire and attach all of the handlers to the view.
  $view->init_handlers();
  $exposed_form = $view->display_handler->get_plugin('exposed_form');
  return $exposed_form->render_exposed_form();
}


It seems some of the variables are not defined properly. It is recommended to define variables properly to avoid some security vulnerabilities or bugs. Although PHP doesn't create any execution error.

To Solve this, you may choose any of below choices.

1.) Properly declare variables - Recommended

$value = isset($_POST['value']) ? $_POST['value'] : '';

2.) Set custom error handler function

set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)

http://php.net/manual/en/function.set-error-handler.php

3.) Disable E_NOTICE from reporting - Fix

error_reporting( error_reporting() & ~E_NOTICE ).


Voting Api + Vote Up / Down = Vote Power

The vote will be casted by calling the Voting api function votingapi_set_votes(). But if you want to change the votes before sending it to Voting api there is hook for this called hook_vud_votes(&$votes) which you can use.

Update:
The api file mentions a hook called hook_vud_votes(&$votes) to alter the vote but in their code they are invoking the hook using drupal_alter(), so the right hook to implement is hook_vud_votes_alter(&$votes), I think it is mistake in their api doc.


How do I invoke JavaScript in AjaxResponse?

Best way is probably to add your own custom command :

<?php
namespace Drupal\demo_test\Ajax;
use Drupal\Core\Ajax\CommandInterface;
class DemoTestJsCommand implements CommandInterface
{
    public function render(){
        return [
            'command' => 'demoTestJsCommand',
        ];
    }

}

And JS :

Drupal.AjaxCommands.prototype.demoTestJsCommand = function (ajax, response) {
    alert(1);
};

Then, you just have to add

$response->addCommand(new DemoTestJsCommand());

in you form's response.


hook_form_alter - validation function does not get called in Internet Explorer

The Form API works via PHP and is executed in its entirety on the server. There really should be no question of browsers being involved in the equation. That is, unless you are doing something with JS (or CSS/anything client side) that might affect form input.

I would:

Clear all my caches.
Ensure that I'm working on the same page, site (and as the same user) in both FF and IE.
When you mention "printing the $form info", I assume that you are using the Devel module. If you aren't, you should be. Devel's dpm() function is the best way to debug these things by adding diagnostic print statements in each step - the form, the validation hook and the submit hook.


Views sorting by number of values in field

Enable Aggregation in View settings.
Add Your Multiple Field in Sort Criteria
Select Count as Aggregation Settings
Select Sort Criteria - Asc , Desc

PS: Do not add same field to field list , it will lead to multiple results in the view


How do I automatically generate image styles?

Image derivatives will be automatically generated once requested and not-yet existing.

But if you are asking how to programmatically create image derivatives checkout ImageStyle::createDerivative.

Here's a sample snippet were I did exactly that:

$field_name = 'field_my_image';
$image_style_name = 'my_image_style';
$image = [];

// Get the original image URI.
$original_image = $node->{$field_name}->entity->getFileUri();

// Load the image style.
$style = \Drupal::entityTypeManager()
  ->getStorage('image_style')
  ->load($image_style_name);

// Get the styled image derivative.
$destination = $style->buildUri($original_image);

// If the derivative doesn't exist yet (as the image style may have been
// added post launch), create it.
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}

// Do whatever else you need to do.
$image['url'] = file_url_transform_relative($style->buildUrl($original_image));
$properties = $node->{$field_name}->first()->getValue();
$image['alt'] = $properties['alt'];
$image['title'] = $properties['title'];


Filling form with user entered values after submit

Drupal 7

If you are not redirecting and want to preserve the values in the Form API fields add $form_state['rebuild'] = TRUE; on the submit handler.

/**
 * FORM submit handler.
 */
function FORM_form_submit($node, &$form_state) {
  // Rebuild the form and keep the filter values.
  $form_state['rebuild'] = TRUE;
}

Drupal 8

In Drupal 8 you would use $form_state-> setRebuild();

See public function FormState::setRebuild for more detail.

Custom submit handlers in Drupal 8 are dealt with differently — here is some useful discussion on Drupal 8 submit handlers.


How to translate menu items with migrate?

I don't see anything obviously wrong in your code, but it would have been a better idea to post the 2 full examples (and ideally, you should try first a simple example that can be imported without custom plugins)

Note that for the second YML file (the translation) you don't need to import most of the stuff: you basically need to process the id, the parent, and the title, no need for nid or 'link/uri'.

As the documentation for this is scarce, I'm posting a working example (using JSON, not CSV).

YML for the first migration:

id: menu
label: JSON feed of menu links
migration_group: menu
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - modules/custom/migrate_custom/artifacts/menu_en.json
  item_selector: data
  fields:
    -
      name: mlid
      label: 'Unique Id coming from API'
      selector: id
    -
      name: country_migration_id
      label: 'Unique Country Id coming from API. Used to create the relation with the nodes'
      selector: country_migration_id
    -
      name: name
      label: 'Country name'
      selector: name
    -
      name: parent_id
      label: 'Parent menu link id'
      selector: parent
  constants:
    path: 'entity:node/'
  ids:
    mlid:
      type: string
process:
  menu_name:
    plugin: default_value
    default_value: 'main'
  nid:
    plugin: migration_lookup
    migration:
      - country
    source_ids:
      country:
        - country_migration_id
  title:
    plugin: get
    source: name
    language: 'en'
  'link/uri':
    plugin: concat
    source:
      - constants/path
      - '@nid'
  parent:
    plugin: menu_link_parent
    source:
       - parent_id
       - 'main'
  external:
    plugin: default_value
    default_value: 0
  expanded:
    plugin: default_value
    default_value: 0
  enabled:
    plugin: default_value
    default_value: 1
  langcode:
    plugin: default_value
    default_value: 'en'
destination:
  plugin: entity:menu_link_content
  bundle: menu_link_content
  no_stub: true
migration_dependencies:
  required:
    - country
dependencies:
  enforced:
    module:
      - migrate_custom

YML file for translation:

id: menu_ca
label: JSON feed of menu links (Catalan)
migration_group: menu
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - modules/custom/migrate_custom/artifacts/menu_ca.json
  item_selector: data
  fields:
    -
      name: mlid
      label: 'Unique Id coming from API. Used to match the original language of the menu links'
      selector: id
    -
      name: name
      label: 'Country name'
      selector: name
    -
      name: parent_id
      label: 'Parent menu link id'
      selector: parent
  ids:
    mlid:
      type: string
process:
  menu_name:
    plugin: default_value
    default_value: 'main'
  id:
    plugin: migration_lookup
    migration:
      - menu
    source_ids:
      menu:
        - mlid
  title:
    plugin: get
    source: name
    language: 'ca'
  parent:
    plugin: menu_link_parent
    source:
       - parent_id
       - 'main'
  external:
    plugin: default_value
    default_value: 0
  expanded:
    plugin: default_value
    default_value: 0
  enabled:
    plugin: default_value
    default_value: 1
  langcode:
    plugin: default_value
    default_value: 'ca'
destination:
  plugin: entity:menu_link_content
  bundle: menu_link_content
  no_stub: true
  translations: true
migration_dependencies:
  required:
    - country
    - menu
dependencies:
  enforced:
    module:
      - migrate_custom

menu_en.json:

{
    "data": [{
        "id": "1_CHE",
        "country_migration_id": "CHE",
        "name": "Switzerland",
        "parent": 0
    }]
}

menu_ca.json:

{
    "data": [{
        "id": "1_CHE",
        "country_migration_id": "CHE",
        "name": "Suïssa",
        "parent": 0
    }]
}


How can I get a checkbox to return True/False?

It depends how you want to use the true/false value.

Case 1

You could change the data in a validation handler. In hook_form_alter, something like:

$form['#validate'][] = 'my_great_handler';

Then:

function my_great_handler($form, &form_state){
  $form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value']
    = ($form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value'] == 1);
}

Not sure what that would do for you, though.

Case 2

If you want to show users true/false rather than 1 or 0, you could change that in a template. Create a template for the field, and add something like:

Checkbox: <?php print $checkbox1 == 1 ? 'True' : 'False'; ?>

Case 3

If you want to save the data in a custom data store, you would add similar code right before the save, in hook_node_save, or some such.


How to pass a field value from a parent node to its entity referenced children nodes when saving the parent node form

One option is to use hook_ENTITY_TYPE_update() and hook_ENTITY_TYPE_insert().
// Top of .module
use Drupal\node\NodeInterface;

function MYMODULE_node_update(NodeInterface $node) {
  _MYMODULE_set_department_employee_company($node);
}

function MYMODULE_node_insert(NodeInterface $node) {
  _MYMODULE_set_department_employee_company($node);
}

function _MYMODULE_set_department_employee_company(NodeInterface $node) {
  if ($node->bundle() == 'department') {
    $dept_company_id = $node->DEPARTMENT_COMPANY_FIELD->target_id;
    foreach ($node->DEPARTMENT_EMPLOYEE_FIELD->referencedEntities() as $employee) {
      // Only update the employee company if it's different.
      if ($employee->EMPLOYEE_COMPANY_FIELD->target_id !== $dept_company_id) {
        $employee->EMPLOYEE_COMPANY_FIELD->target_id = $dept_company_id;
        $employee->save();
      }
    }
  }
}


Views block link defaults to target="_blank" using rewrite output

Print the results from the views template.you can rewrite the views template for that specific field and check the link that whether its external or internal using the drupal function url_is_external and you can add the attribute target="_blank" to those views fields that are external urls.

Off topic suggestion : if you want all external links on your website should open in new tab then you can use the extlink module to open all external links in new tabs.

  External Links is a small module used to differentiate between
  internal and external links. Using jQuery, it will find all external
  links on a page and add an external icon  indicating it will take you
  offsite or a mail icon  for mailto: links.


Is there a module that shows when you last updated or modified an installed module?

AFAIK, no module, but ls -l in your module directory should give you the dates of last updates.

Btw. it is trivial to create a module that does this. Just throw a module wrapper around something like:

$modules = '/www/sites/all/modules/'; // Path to your module directory.
$output = shell_exec('ls -l ' . $modules);
echo "<pre>$output</pre>";


Taking over a url and getting variables from url

I would suggest looking into the Data module. I does pretty much everything (and more) what you're describing in your request.


Add user to a group after the user makes a comment in that group

The answer is ... yes, it is possible ... and easy to do ... with Rules.

If anyone coming across this is new to Rules or needs a refresher I highly recommend Johan Falk's free screencast series. It's excellent. http://nodeone.se/en/learn-the-rules-framework

See the screenshot for how I did it, and also the exported Rule below.

{ "rules_lambeth_comment_join_group" : {
"LABEL" : "lambeth comment join group",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "og", "comment" ],
"ON" : [ "comment_insert" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "og_group_ref" } }
],
"DO" : [
  { "og_subcribe_user" : {
      "user" : [ "comment:author" ],
      "group" : [ "comment:node:og-group-ref:0" ]
    }
  }
]
}
}


The basic logic goes like this:

$nodes = entity_load('node', FALSE, array('type' => 'the_type'));

foreach ($nodes as $node) {
  $node->field_image[$node->language][0]['alt'] = $node->title;
  $node->field_image[$node->language][0]['title'] = $node->title;

  node_save($node);
}

You should probably split that up into a batch job if you have a lot of nodes.

I'm also pretty sure you could make a quicker solution using VBO and some custom PHP but I don't have time to flesh that out right now.


Whatever data is returned must be encapsulated in a div element of the same id as the wrapper.

This fixed the problem for me :)

function raffle_create_form_type_steam($form, &$form_state)
{
    if($form_state['values']['raf_prize_type'] == 'hardware')
    {
        return "

";
    }
    else
    {
        return  $form['raf_steam_option_game_append'] = array(
                '#type' => 'checkbox',
                '#title' => 'Check if Steamer has game in library',
                '#description' => 'Does not allow gamer to join raffle if said gift already exists within gamer\'s steam library',
                "#prefix" => "
",
                "#suffix" => "
"
            );
    }

}


Is it possible to inherit a cck into another CCK and assign multiple values to it

From the first look at this, it seems you are wanting to create a cck content type with a multiple value filefield field so you can upload multiple pdfs per node.

If that is the case, make sure you have the FileField module installed if D6 (it's in core in D7) and then you can, after creating the content type, add a field, select it's type to be File, and then in configure, allow it to have 1,2,...10 or any number of values.

After that, everything "just works," including Views.


I think you should be using hook_user_login instead of hook_init.


Display Jalali (Shamsi) Date in Archive View

there are patch file in datex folder for patching datex to jalali support.

patching datex module for convert date to jalali.

path: modules\datex\drupal-jalali_support-0-0.patch


Easiest & most efficient way to embed vimeo code into blog post

I would create a field to input just 60771416 instead of the whole iFrame. Then use the theme_field to wrap with iFrame and set attributes accordingly. Gives me more flexibility for the output. As well as its modular. The Google Analytic module do similar stuff.


UPDATE database field with value from other table

Given the specific nature of your SQL statement, it would appear db_query() is the way to go. Just be sure to do it as an update hook in your .install (so you can drush updb) to implement smoothly.


I think you need to specify a filed name inside a paragraph in the header array, like field_date_paragraph.DATE_FIELD_NAME (This behavior is, also supported inside condition method)
And here is the issue about lack of documentation https://www.drupal.org/project/drupal/issues/1924622


I ended up inheriting the kernel and will adjust it as needed be.

Something like:

namespace Drupal\Core;

use Drupal\Core\Site\Settings;

class DrupalCliKernel extends DrupalKernel {

  public function bootstrap() {
    static::bootEnvironment();
    $this->setSitePath('sites/default');
    Settings::initialize($this->root, 'sites/default', $this->classLoader);
    $this->boot();
  }

}

And then:

use Drupal\Core\DrupalCliKernel;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalCliKernel('prod', $autoloader);
$kernel->bootstrap();

// Drupal is bootstrapped now.

Not yet sure if I miss something important, but I am most likely not using this, but instead relying on using HTTP requests that the worker will use as Drupal is too coupled to the HTTP request. Just putting it out if someone come here to try to accomplish something similar and want a jump-start.


How does a menu item get hidden with the Domain module?

I did a project this summer that used Domain Access to split a site into desktop and mobile versions of the website.  The client wanted to be able to target pieces of content for the desktop, mobile, or both.

If a piece of content is in a menu, the the domain rules will decide if that piece of content is available, which is what you are seeing.  This is done with the standard node_access methods, which grant permissions rather than take them away.

I think you have a two options here.

I think proper thing you should do it to send the node to all or multiple affiliates, which should be an option when you edit the node.

If you want to go the node_access route, then I suspect you need to clear caches and also rebuild the node permissions.  I totally forget where this option is in the UI, but you essentially need to call node_access_rebuild.  The easiest way is probably with drush

drush php-eval 'node_access_rebuild();'

Just keep in mind that the link will appear in the menu, but the node will also be viewable.  The two go hand in hand.


How to set product price with rules on checkout

You must be using the product pricing system, which requires a rule assigned to the "Calculating the sell price of a product" event. Rules on this event can make use of a variety of Line item related actions to manipulate the unit price of the line item, and you'd just add conditions to your rule to only apply pricing based on the product SKU.

See the FAQ on Rules data selection for information on checking the product SKU:

https://drupalcommerce.org/faq/rules-field-data-selection


Template.php - Hiding Specific Element on Node Edit

As fast solution, verify the value returned from arg(2) is different from 'edit'.

   function mytheme_preprocess_page(&$vars, $hook) {
      if (in_array('page__mypagetype', $vars['theme_hook_suggestions']) && arg(2) != 'edit) {
        $vars['custom_element'] = my_custom_element();
      }
    }


automatic logoff when leaving a page for a particular user and node/page combination

AFAIC you can get current node id from Drupal JS object. Having those id you can send Ajax request to Drupal which performs logout (http://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user_logout/7)

About JS events for this task you should look on other forurms


How to resolve 'Fields pending deletion' and force deletion of said field?

You could force field deletion using drush with the command:

drush php-eval  'field_purge_batch(500);'

or you could install devel module and go to /devel/php and run

field_purge_batch(500);


How to access the raw content of a views field, for use with Services Views

You can do it using relationships! Under Advanced, add the relationship File Usage: File. Then go add a new field, and you'll see File: Path.

Alternatively, you could use the Image URL Formatter module. This allows you to print an image as a URL. Then in the field settings in Views select this under 'Format' for the image field. The module has some features that would be harder to achieve with the relationship, but for most cases the relationship should work.


Setting up local dev, "call to undefined function" from a module that I uninstalled a few months ago

Most of the time this a cache problem.

First try to clear the cache via Drupal (Clear cache button). Or use Drush (drush cc all).
You can clear the cache tables by truncating them. Check all the tables with cache_ prefix.
If #1 and #2 didn't fix the problem then check if you have Memcache or similar installed. Flush the cache as well.
Another thing could be APC or similar opcode cache.


Issues sending HTML email with Simplenews module

Check out the following modules, in their configuration it's easy to set email system and html format:

Mail System.
SMTP Authentication Support.

Select mime mail in the config of mail system. Also make sure that content text format and newsletter settings is full html and it should do it.


Add callback to existing migrate field mapping

With some debugging and looking at code, it turned out to be pretty easy. All of the mappings are MigrateFieldMapping objects in $this->codedFieldMappings, so it's just a matter of getting a reference to that object and calling the callbacks() method. For example, to add a callback to the body field, you would use:

$this->codedFieldMappings['body']->callbacks('my_callback');


Rule set username after changed user email

You can look at this:
https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_save/7

It will run after a user is created and if a user is edited.   You can update the data as required.


Though I don't think this solves your problem of not wanting the content included in the feature at all, there are 2 ways that I know of to be able to create blocks that don't use numerical ids, and that can therefore be safely included in a feature.

Boxes
Beans

Personally, I prefer the Bean approach, since the Bean Bundles are fully fieldable, allowing to create very advanced types of blocks. Both of these modules however essentially allow you to create blocks that have machine_names (feature proof) as opposed to numerical ids, which as you know are a royal pain in the ass when it comes to features integration.

EDIT: actually, now that I think of it, Bean does not create blocks with machine_names - it uses numerical ID's. It is the Bean Types (think Content Types) that have machine_names. So, if you want blocks with machine_names, Boxes is the way to go.


Features 8.x-3.7 not writable on Window's Ubuntu

It looks like you are using something like a virtual machine (Vagrant?) with a shared windows file system.  The problem is that Windows permissions don't map well to Linux ones.  That is why the chmod error is happening.

You may need to get your webserver running under the same user you share the file system under, e.g. the vagrant user.

Personally, I have never gotten a stable way to have Features write to a windows share. There always seemed to be a gotcha in the ones that worked.  I've just excepted that I had to download the feature archive, unpack it, and copy it to the site on the Windows side.

But your situation may be different.