$form_state['values'] AJAX I have the following form:
Displayed at Page load

$form['platform'] = array(
  '#type' => 'select',
  '#title' => t('Select a Platform'),
  '#options' => array(
    0 => t('- Select -')) + $options,
  '#default_value' =>  0,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_select_callback',
    'wrapper' => 'replace_model_div',
    'effect' => 'slide',
   ),
);

I'm trying to pull out the $form_state['values'] to determine if another select field should be shown. However I'm not sure how this will ever get called without a submit function.

To be Displayed after option is selected

 if (isset($form_state['values']['platform'])) {
 $platform_value = $form_state['values']['platform'];
 $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data} WHERE vid = $platform_value";
 $result = db_query($sqlmodel);
 $options = array();
   foreach ($result as $row) {
     $model_options[$row->vid] = t($row->name);
    }

$form['model_wrapper'] = array(
  '#type' => 'select',
  '#title' => t('Select a Model'),
  '#options' => $model_options,
  '#options' => t('$platform_value'),
  '#prefix' => '
',
  '#suffix' => '
',
);
}
return $form;
}
function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper'];
}

If I am understanding AJAX properly even though on a select change my AJAX call will happen to render the model_wrapper. There is nothing in the AJAX call that will re-evaluate the if (isset function, and as such the model_wrapper section will never display.

Full story and objective: AJAX dependent select

The reason it's not working is because the
 with an ID of replace_model_div doesn't exist when the form is first built. So when the AJAX replace happens, there's no target container to append it to.

All you need to do is re-structure you form slightly (and remove the second #options array added to the second select):

$form['model_wrapper_container'] = array(
  '#type' => 'container',
  '#prefix' => '
',
  '#suffix' => '
',
);

if (isset($form_state['values']['platform'])) {
  $platform_value = $form_state['values']['platform'];
  $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data} WHERE vid = $platform_value";
  $result = db_query($sqlmodel);
  $model_options = array();
  foreach ($result as $row) {
    $model_options[$row->vid] = t($row->name);
  }

  $form['model_wrapper_container']['model_wrapper'] = array(
    '#type' => 'select',
    '#title' => t('Select a Model'),
    '#options' => $model_options,
  );
}

And a small change to the callback:

function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper_container'];
}


Is it possible to include external libraries in a twig template? I think I know the answer, because I tried to attach an external library like this:

{% set location = {'type': 'external'} %}
{{ attach_library('//example.com/example.js/v3/example.js', location) }}

This did not attach the desired library, am I missing something, or is this a non-starter?

Add external files in libraries: https://www.drupal.org/developing/api/8/assets

See the section on "CDN / externally hosted libraries".


How do I run PHPUnit tests? Having just kind of gotten my head around Simpletest functional testing in Drupal 8.x, I've now started trying to use PHPUnit testing since Simpletest has been deprecated in Drupal 9.1.x.
I started by looking at the instructions on Running PHPUnit tests. However, when I get to the step on running the tests I get this.

Fatal error: Uncaught Error: Class "Drupal\Tests\node\Functional\NodeTestBase" not found in /opt/drupal/web/core/modules/node/tests/src/Functional/PagePreviewTest.php:22

This looks a bit like an autoload issue to me. I ran the following command to verify it was effectively so.
php -r "require_once('autoload.php'); var_dump(class_exists('\Drupal\Tests\node\Functional\PagePreviewTest'));"

The command outputs bool(false).
My knowledge really ends here. The documentation seems to be moot on this, and it looks like I'm not the only one with this problem. (See How to run PHPUnit tests?).
How do I run PHPUnit tests?
This is the Docker file content that can be used to reproduce what I described in the question.
FROM drupal:9.1.0

RUN composer require -n \
  phpunit/phpunit:9.5.0 \
  phpspec/prophecy-phpunit:2.0.1 \
  symfony/phpunit-bridge:5.2.1

RUN cd web/core; phpunit -c phpunit.xml.dist modules/node/tests/src/Functional/NodeTestBase.php

Building this causes the error I described above.

I believe the problem is that you are using the sample phpunit.xml.dist instead of copying it to phpunit.xml and then making a few teaks for your installation.
Part of the phpunit.xml file is setting up the autoloader to find test classes and modules (they are not in the normal autoloader). And you tend to get some really weird errors if you don't set up the DSN for the database (to run Kernel and Functional tests).
I would do the following (adjust paths as needed ; I'm looking at a core-dev project right now and not a live site).

In your install, do composer require --dev drupal/core-dev:~9.1.0. You may want to tweak the version number, depending on you you have core defined.
Make sure you are running the binary from vendor/bin in your install.  I suggest looking into direnv.
Copy phpunit.xml.dist to phpunit.xml and edit

SIMPLETEST_BASE_URL
SIMPLETEST_DB
BROWSERTEST_OUTPUT_DIRECTORY
to reflect your installation.

Then cd to core, and run
../vendor/bin/phpunit -c phpunit.xml --testsuite unit

This should start to loop through the Unit tests. Abort that if they look like they are working, and then do
../vendor/bin/phpunit -c phpunit.xml --testsuite kernel

Then, if that looks OK you can start to run your own tests.
All of that said, it is much easier to run individual tests through PhpStorm. You just need to got through the preferences to point to the right PHP interpreter, and set a few things for phpunit.
In your case, it may be better to just start the drupal:9.1.0 container, and then shell into it for initial testing before updating the Dockerfile.


Copy data from Webform submission to a node? I have pre-existing node authored by each user. However, for presentation purposes, I use a Webform to collect data from the user.

Existing Node: Assessment

field_question1
field_question2
field_question3

Webform

field_question1
field_question2
field_question3

On submit, I would like to compare "the user submitting the Webform" with the author of existing nodes, then set the field values of the submitter's existing node with the new values from the submitted webform.

This worked well in Drupal 7, but in Drupal 8 I don't seem to understand the syntax, nor do I see a place to set up or pass variables.

Can this be done in the current state of Drupal 8 Rules?

Can this be done in the current state of Drupal 8 Rules?

To my knowledge the answer to your question is No (it's part of what this is all about).

If you're in for getting a better understanding about all this, then have a look at these links:

Roadmap.
Architecture.

One never realizes what has been done, only what remains to be done ...


Views block contextual filter question I have a content type called slides, for now it has an image field, a body, a title and a link field (linked to the page that the slide is advertising... by the way some pages are views).

So for now I made a Views block to make them all appear in a Slideshow and it works. But now I would like to create a new Views block that will only show the slide related to the page you visit. So for example, on the homepage you have the slideshow of all my slides but when you click on one of them, you go visit the specific page advertised (e.g. contact slide linked to contact page).

But when you visit the page, you should see the new block with the specific slide related to the page. I search for answers and I think Contextual filter is the option to use in Views, but I am not accustomed to it and the examples that I found are not exactly using available value for me.

I am thinking I might be able to filter the slides vs the path they have vs the page they are on. But I am not sure if it's possible and have no idea how to do it. So please let me know how or send me a few thoughts on where to look at. Thanks!

Also display the block on slides content in full page view, and in your view add the contextual filter "Content: Nid" with the following settings :

  Provide a default value : Content ID from URL

It will be automatically filtered, but will still display all slides on your home page


Cannot set menu link content field values in *links.menu.yml I added a field to the menu_link_content entity, but am unable to set the value of this field in my my_module.links.menu.yml.

Here is my hook_entity_base_field_info:

/**
 * Implements hook_entity_base_field_info_alter().
 */
function my_module_admin_menu_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() != 'menu_link_content') {
    return;
  }

  // Create the base field definition for the allowed roles. This field will
  // reference user entities.
  $fields['my_module_admin_menu__show_role'] = BaseFieldDefinition::create('entity_reference')
    ->setName('my_module_admin_menu__show_role')
    ->setTargetEntityTypeId('menu_link_content')
    ->setLabel(t('Roles able to see the menu link'))
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
    ->setSetting('target_type', 'user_role')
    ->setDisplayOptions('form', [
      'type' => 'options_buttons',
      'weight' => 0,
    ]);
}

In my my_module.links.menu.yml, I provide a menu link like so:

my_module_admin_menu.article:
  title: 'Article'
  menu_name: admin-per-user-role
  url: internal:/node/add/article
  parent: my_module_admin_menu.create
  bundle: menu_link_content
  my_module_admin_menu__show_role:
    settings:
      target_type: user_role
      handler: default
    target_id:
      - authenticated

The link shows up, but doesn't show the field:

When a link is added via the menu UI, the field is shown:

Menu links discovered in *.links.menu.yml are not menu link content entities and therefore don't contain the field you have added to the entity. If you want to fill this field with data programmatically, create an instance of the entity:

$link = MenuLinkContent::create([
  'title' => 'Article',
  'menu_name' => 'main',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'entity:node/1']],
  'custom_field' => 'custom content',
]);
$link->save();

The content of *.links.menu.yml seems a bit odd. The title field is the only required value and you can see that the link is discovered and the title is displayed in the screenshot. The other values are optional. Check the documentation about which values you can use in this file https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links

The field seems to be for some kind of access control. You shouldn't do this in the menu link. Instead control the permissions of the target. Menu items are only displayed for users who can access the target.


Add a single image field to a view (not its nodes, the view itself) I would like to know if it is possible to have an image field in the setup of a view, that I could then display in front-end, on top of the view via the views-view template.

So far, I can only find topics about how to add an image field to nodes of the view. I want this image field to be related to the view, just like the "view title" field.

Views are all about rows of data. To achieve what you want, you have two options:

Create .tpl file for your view, put <img> tag in it
Attach view to a node using, for example, Viewfield module. In that node create image field you want.

First option is faster, second one allows easier image changes.


How to map Address field module sub fields (City, State, etc.) to specific (individual) fields in Salesforce? Address module: https://www.drupal.org/project/address
Usually Salesforce mapping doesn't allow to add Address module subfields in the mapping.

We can resolve this by using typed_data module. https://www.drupal.org/project/typed_data
This is a required module for Salesforce Suite installation.

In the Field Type select Properties,Extended
then select the name of the field associated the Address field Module corresponding to the Salesforce field.


Where do I place custom PHP code (functions, classes) when creating a theme? WordPress has a place for it - functions.php, which is included automatically. Is there one for Drupal?

The theme's template.php is used for logic and data processing. See the Drupal theming guide.

From the guide:

  For all the conditional logic and data
  processing of the output, there is the
  template.php file. It is not required,
  but to keep the .tpl.php files tidy it
  can be used to hold preprocessors for
  generating variables before they are
  merged with the markup inside .tpl.php
  files. Custom functions, overriding
  theme functions or any other
  customization of the raw output should
  also be done here. This file must
  start with a PHP opening tag "<?php",
  but the close tag is not needed and it
  is recommended that you omit it.


How is webform node type is defined in webform module? Reading the webform module code I could not figure out how webform content type is defined. I only found this piece of code:

function webform_node_type($op, $info) {
  $webform_types = webform_variable_get('webform_node_types');
  $affected_type = isset($info->old_type) ? $info->old_type : $info->type;
  $key = array_search($affected_type, $webform_types);
  if ($key !== FALSE) {
    if ($op == 'update') {
      $webform_types[$key] = $info->type;
    }
    if ($op == 'delete') {
      unset($webform_types[$key]);
    }
    variable_set('webform_node_types', $webform_types);
  }
}

In variable table of drupal database I found the following webform_node_types variable: a:1:{i:0;s:7:"webform";}. When applying variable_get to this variable I recieve an array of 1 element with value - 'webform'.
Please help me understand how webform node type actually is defined and how it works?
Thanks

The initial webform content type is created during install as an entity of type node. The code can be found in the webform_install() function:

$webform_type = array(
  'type' => 'webform',
  'name' => st('Webform'),
  'base' => 'node_content',
  'description' => st('Create a new form or questionnaire accessible to users. Submission results and statistics are recorded and accessible to privileged users.'),
  'custom' => TRUE,
  'modified' => TRUE,
  'locked' => FALSE,
);
$webform_type = node_type_set_defaults($webform_type);
node_type_save($webform_type);
if (variable_get('webform_install_add_body_field', FALSE)) {
  node_add_body_field($webform_type);
}

Additionally it might be worth noting, that you can turn any content type into a webform by checking the appropriate setting on the content types main configuration page. You can think of webform as an add-on extension to other content types. To find out which content types are "webform enabled" you should use the provided API functions. In webform-7.x-4.0-beta for example that would be webform_node_types().


Access webform by checking predefined codes If I set up a webform with one component "authrization code", which is predefined by my side. People can access the form only when they get the authorized unique code from me. Is there any way to realize this? I tried a module "webform invitation", but have the same problem as described "any code is accepted"(my system is D8.64,php7.0). If I add a text field for code validation, I don't know where to predefine those codes and how to check. Another question is how can I produce those unique codes and transfer them to QR codes so that people can scan them to automatically fill in the form? Appreciate for any help in advance!

You can create a custom module with a hook_webform_access() callback that looks for authorizations codes.

The below hook grants access to the default Contact form via /form/contact?code=secretcode. Make sure to go to /admin/structure/webform/manage/contact/access and remove 'Create submissions' access to the Contact form.

/**
 * Implements hook_webform_access().
 */
function CUSTOM_MODULE_webform_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
  // List of webform ids and authorization codes.
  $webform_authorization_codes = [
    'contact' => 'secretcode',
  ];

  // Get the current webform.
  /** @var \Drupal\webform\WebformRequestInterface $request_handler */
  $request_handler = \Drupal::service('webform.request');
  $webform = $request_handler->getCurrentWebform();
  if (!$webform) {
    return \Drupal\Core\Access\AccessResult::neutral();
  }

  // Get the webform id.
  $webform_id = $webform->id();
  if (!isset($webform_authorization_codes[$webform_id])) {
    return \Drupal\Core\Access\AccessResult::neutral();
  }

  // Get get the code.
  $code = \Drupal::request()->get('code');
  if (empty($code)) {
    return \Drupal\Core\Access\AccessResult::neutral();
  }

  // If 'submission_page' (aka create) and authorization code is correct,
  // then grant access.
  if ($operation === 'submission_page' && $code === $webform_authorization_codes[$webform_id]) {
    return \Drupal\Core\Access\AccessResult::allowed();
  }
  else {
    return \Drupal\Core\Access\AccessResult::neutral();
  }
}


Change states in hook form alter I am trying to change the states via the the following code:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  ...
  case 'my_form_node_form': {
    $form['my_file_field']['#states'] = array(
      'visible' => array(':input[id="my_id"]' => array('value' => 'my_value'),
    ),
  );
 }
}

but, my file field is not becoming visible after my input id is selected, instead is already visible.

If this is a file field attached to an entity, and not (for example) a managed_file element type, then the actual <input> element is contained further down the render array. At the moment you're probably attaching the JS to the wrong element (a container rather than the input).

Try something like this instead:

/**
* Implements hook_form_alter()
*/
function my_module_form_alter(&$form, &$form_state, $form_id) {
  ...
  case 'my_form_node_form': {
    $form['my_file_field'][LANGUAGE_NONE][0]['fid']['#states'] = array(
      'visible' => array(
        ':input[id="my_id"]' => array('value' => 'my_value'),
      ),
    );
  }
}


How to alter the user login response data I'm just looking into adding some more data to the Drupal 8 API user login response.

curl --header "Content-type: application/json" --request POST --data '{"name":"username", "pass":"password"}' http://drupal8.localhost/user/login?_format=json

The response is like:

{
    "current_user": {
        "uid": "100",
        "roles": [
            "authenticated"
        ],
        "name": "username"
    },
    "csrf_token": "4gRg8XElB1jRp3xu1a4vm2oYiTCXLaoO8Ii72Dwe1kd",
    "logout_token": "gnUt53JZcM7KEFizLOFe996DTXgEqj7RyzhMwsmUssZ"
}

How can one add additional data to the user login API response?

I've looked into adding a custom Normalizer, but seems a bit tricky to intercept the /user/login response and curious if any other suggestions on it, thanks.

OK, I'd like to post one more answer approach, using the response event listener (with thanks to @Berdir). This is the one I'm using in the end as it avoids duplicating the login function logic. The previous answer may still be useful if you want to alter the actual login logic flow as well.

The event subscriber class

<?php

namespace Drupal\example\Listener;

use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Serialization\Xml;
use Drupal\Component\Serialization\Json;

/**
 * Class ExampleLoginListener.
 *
 * @package Drupal\example
 */
class ExampleLoginListener implements EventSubscriberInterface
{

  /**
   * @var path.current service
   */
  private $currentPath;
  /**
   * @var jwt.authentication.jwt service
   */
  private $jwtAuth;

  /**
   * Constructor with dependency injection
   */
  public function __construct($currentPath, $JwtAuth) {
    $this->currentPath = $currentPath;
    $this->jwtAuth = $JwtAuth;
  }

  /**
   * Add JWT access token to user login API response
   */
  public function onHttpLoginResponse(FilterResponseEvent $event) {
    // Halt if not user login request
    if ($this->currentPath->getPath() !== '/user/login') {
      return;
    }
    // Get response
    $response = $event->getResponse();
    // Ensure not error response
    if ($response->getStatusCode() !== 200) {
      return;
    }
    // Get request
    $request = $event->getRequest();
    // Just handle JSON format for now
    if ($request->query->get('_format') !== 'json') {
      return;
    }
    // Decode and add JWT token
    if ($content = $response->getContent()) {
      if ($decoded = Json::decode($content)) {
        // Add JWT access_token
        $access_token = $this->jwtAuth->generateToken();
        $decoded['access_token'] = $access_token;
        // Set new response JSON
        $response->setContent(Json::encode($decoded));
        $event->setResponse($response);
      }
    }
  }

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::RESPONSE][] = ['onHttpLoginResponse'];
    return $events;
  }

}

and the example.services.yml entry

services:
  example.login_response_listener:
    class: '\Drupal\example\Listener\ExampleLoginListener'
    arguments: ['@path.current', '@jwt.authentication.jwt']
    tags:
      - { name: event_subscriber }

In this way, we can add the JWT access_token to the /user/login?_format=json API response.


check other commerce pane validation error I am work on commerce pane, in hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order)  I call a function to do something in pane sumbit,

something like

function hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {

  do_update_something($user);
}

but when I am not fill another pane like address , my function called,
How can I prevent submit when there is error (validation in another panes) in other panes?

check errors before call your function

function hook_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
if (!(form_get_errors()){
 do_update_something($user);
}

}


How to use drupal_get_form outside of a menu I am trying to use the drupal_get_form funtion outside of a menu and am not having any luck finding examples of how this is done.

An overview of what I am trying to achieve is:
1) Pass control from a script using an href html tag passing to another script that will then read what has been passed to the new script and build a form based on the action that has been passed in. I am using the drupal_get_form function just as you would any php function.
2) I am also getting a message that says drupal_get_form is an unknown function.

This script is the initial calling script that contains an html href link to the called processing script.

function view_payment_methods() {
  try {$result = db_select('tls_connect_cashier_payment_methods', 'q')
    ->fields('q', array('id', 'payment_method', 'payment_desc', 'logically_deleted', 'system_or_user'))
    ->orderBy('payment_desc')
    ->execute();
  } catch(Exception $e) {
    watchdog_exception(
      'view_payment_methods',
      $e,
      'Select from tls_connect_cashier_payment_methods has failed.',
      null,
      'Alert'
    );

    return false;
  }
  $payment_methods = $result->fetchAll(PDO::FETCH_ASSOC);

  $col1_label           = t('Payment Method');
  $col2_label           = t('Payment Description');
  $col3_label           = t('Disabled');
  $col4_label           = t('Created By');
  $col5_label           = t('Action');
  $edit_label           = '(' . t('Edit') . ')';
  $delete_label         = '(' . t('Delete') . ')';

  $markup  = "
" . t('Payment Methods') . "
";
  $markup .= "
";
  $line    = "
";
  $line   .= "" . $col1_label . "	";
  $line   .= "" . $col2_label . "	";
  $line   .= "" . $col3_label . "	";
  $line   .= "" . $col4_label . "	";
  $line   .= "" . $col5_label . "	";
  $line   .= "
";
  $markup .= $line;
  if (isset($payment_methods[0])) {
    foreach ($payment_methods as $entry) {
      $disabled          = '';
      $created_by        = '';
      $id                = $entry['id'];
      $payment_method    = $entry['payment_method'];
      $payment_desc      = $entry['payment_desc'];
      $logically_deleted = $entry['logically_deleted'];
      $system_or_user    = $entry['system_or_user'];
      $line              = "
";
      $line             .= "" . t($payment_method) . "	";
      $line             .= "" . t($payment_desc) . "	";
      if ($disabled == 0) {
        $disabled      = 'No';
      } else {
        $disabled      = 'Yes';
      }
      $line             .= "" . t($disabled) . "	";
      if ($system_or_user == 'S') {
        $created_by    = 'System';
      } else {
        $created_by    = 'User';
      }
      $line             .= "" . t($created_by) . "	";
      $line             .= "" . $edit_label . "
                        " . $delete_label . "	";
      $markup           .= $line;
    }
  }
  $markup .= "
";

  return $markup;
}

This script is the called script accessed by way of the html href link for the edit link.

if (isset($_GET['action'])) {
  $id = $_GET['id'];
  switch ($_GET['action']) {
    case 'edit':
      $form_id = 'edit_form';
      return drupal_get_form($form_id);
      break;
    case 'delete':
      break;
  }
}

function edit_form($form, &$form_state) {
    global $id;
    die('chuck');
    $form = array();
}

As I understand it, you want to link to a page that displays a form and accepts certain parameters that will influence the form.

  2) I am also getting a message that says drupal_get_form is an unknown function.

That is because drupal_get_form() is not known when Drupal hasn't been formally loaded (bootstrapped). When you call PaymentMethodEditDelete.php directly, then Drupal doesn't know about it, and PHP doesn't know about any Drupal API functions. In order to have all Drupal functionality available, the point of entry must be the index.php in the webroot and not a custom script somewhere.

In order to achieve what I think you want, you need to define a so called menu callback. This is simply a url that is associated to a callback function. You can find more on the menu system in the docs to hook_menu().

In order to use this menu callback with drupal_get_form you would define the menu item like this:

function mymodulde_menu() {
  $items = array();
  ...
  $items['my/custum/url/to/form'] = array(
    'title' => 'My form title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_custom_form_id'),
  );
  ...
  return $items;
}

This is the bare minimum to define a page that will render as a form.

Now in order to handle arguments, you can either pass them in as ordinary $_GET parameters that you can access normally inside your form builder function.

Or you alter the newly defined menu so that it will accept additional arguments and passes them into the form builder, as arguments to drupal_get_form (see Wildcards in Paths). Also have a look at this question for more information: https://drupal.org/node/2054083.

Some more reading I can recommend:

What is the basic concept behind hooks?
http://befused.com/drupal/page-request


How to add custom images to header I would like to add some custom images into the header block of my website and the problem is that I don't know if I should modify some php file or if it is possible via admin panel. Which method is better and if it is better to modify a file, which file is it and where is it located.

Thank you in advance.

The simplest way: Add a block at admin/structure/block/add. Add the html for your images directly into Block body. Make sure the text format is Full HTML. Assign your block to Header region.

Before this, you need to upload the images on your server. You can either upload them directly to your theme folder or create an image content type with image field and use that to upload your images.


Filter by shared reference [![enter image description here][1]][1]I have a content type of "School."
I have a content type of "Event" that contains an entity reference to "School" so that events can be linked to schools.
I can create a view block that filters by the school, when the block is placed on the node of the school, using contextual filters.

The problem:
Starting with the built-in "Basic Page," I added an entity reference to "School" so that "Basic Pages" can be linked to a "School," and be subpages of the "School."
How do I filter a view of "Events" that when placed on a "Basic Page" the "Events" block view will filter based on the entity reference, "Schools," that is shared between the "Event" and "Basic Page?"  I am looking to have an "Events" subpage that lists all the events of that individual school.
I am trying to avoid having to create separate block views that use filter criteria of each individual school.  I was hoping to use contextual filters.

Thank you

You can, at least in D8 use "reverse entity references" in contextual filters and relationships, so what you propose should work.

Have a contextual reference grabbing the node id of the Basic page from the URL. A relationship from the page to the school comes next, then a reverse relationship looking for items that have a relationship to the School. You'll also add a filter on that second relationship, limiting it to Events.


How do I inject a dependency into a @FieldType plugin? I am implementing custom fields in Drupal 8 (types, widgets, formatters).

@FieldType plugins are instantiated by their respective plugin manager (\Drupal\Core\Field\FieldTypePluginManager) which does not care about dependency injection.  That is possible for both @FieldFormatter and @FieldWidget plugins if they only implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface.

What would be the alternative way to inject a dependency into a @FieldType plugin?

Notes

@FieldType plugins are actually (implicitely) instantiated by \Drupal\Core\TypedData\TypedDataManager, which does not care about dependency injection
Related drupal.org issue: Allow typed data plugins to receive injected dependencies

An example for a field formatter plugin with dependency injections. This works differently from services. First parameter injected is the container to get all services needed.

Drupal\Core\Field\Plugin\Field\FieldFormatter

class StringFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a StringFormatter instance.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Any third party settings settings.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }


Date field displayed with wrong timezone with PHP's date_create + date_format I have an Event content type with a Date field with a start and end date.

When this field is being displayed in a view, it displays properly, with the time matching the value that was entered.

On a different page, I am overriding field--field-date.tpl.php and using date_create and date_format to print out the date and time separately.

$start_date = date_create($node->field_date['und'][0]['value']); //dont hate me
$end_date = date_create($node->field_date['und'][0]['value2']);
//...
print date_format($start_date, 'g:i A') . ' - ' . date_format($end_date, 'g:i A');

As you can see, it is displaying 4:00pm instead of 12:00pm. It looks like a timezone translation is happening (or not happening) somewhere. I tried to screw around with the time zone argument for date_create but nothing actually changed the way the date displayed.

When I dump the date field out with devel, I get,

dpm($node->field_date['und'][0]['value']);
dpm($start_date);

How do I actually display the proper timezone for my date with PHP in my field--field-date.tpl.php?

Looks like your date field is configured to use either site zone or user time zone configuration.

So, while saving the node drupal expects the entered value in usertime zone or site time zone and then convert it to UTC before saving it to database.

While showing it views consider the timezone configuration and format the date as per current user viewing the date field.

The timezone you see as 'America/NewYork' in the dpm result is the timezone configuration of the user created the node.

In order to show the date with format you can use format_date, something like below.

$user_time_zone = drupal_get_user_timezone();
format_date(strtotime($node->field_date['und'][0]['value']), 'custom', 'm/d/Y h:i:sA', $timezone = $user_time_zone);

Important thing is to choose the right configuration for your field timezone settings, if the date field is irrespective to current user timezone keep the timezone configuration to UTC.


How I get the name of the taxonomy term reference of the content type I created a content type. One of the field of the content type is entity term reference. Now I want to fetch the term of the particular content type and load the nodes that contain the term.I used the following code. But does not get the answer. Any error in my concept?

$aupl_node_query = new EntityFieldQuery();
$aupl_referrence = $aupl_node_query
->entityCondition('entity_type',  'taxonomy_term')
->execute();
dpm($aupl_referrence);
$aupl_node = node_load_multiple(array(), $aupl_referrence, true);

You can refer to this article having detailed information about entity queries.

You should use ->entityCondition('entity_type',  'node')  rather than using ->entityCondition('entity_type',  'taxonomy_term')


Removing div wrapper of textfield element in webform I would like to remove div element on webform textfield.
Instead of :

<div class="form-item webform-component webform-component-textfield" id="webform-component-vous-etes--nom">
  <input type="text" id="edit-submitted-vous-etes-nom" name="submitted[vous_etes][nom]" value="" size="60" maxlength="128" class="form-text">
</div>

I would like to have this :

<input type="text" id="edit-submitted-vous-etes-nom" name="submitted[vous_etes][nom]" value="" size="60" maxlength="128" class="form-text">

You would do this by overriding theme_form_element() in your theme, eg, something along the lines of:

function YOURTHEME_form_element($variables) {

  $element=&$variables['element'];

  if ( /* this is a webform textfield */ ) {

    // create the html without the div wrapper

  } else {

    // do it the standard way

  }

  return /* the html */;

}

A look into includes/form.inc will show you the full theme_form_element() code that you could copy into your function above where necessary.


Migration of content I am able to migrate organic groups easily enough, but when I attempt to migrate the group content, I am not able to successfully migrate the "parent" group ID(s) (or group audience if you prefer). I could only find snippets of code, and never a complete example, so hopefully I'm missing something simple.

Here is my complete migration code for the group content (as per multiple sources, but for example and per the OG issue page:

  $arguments = $common_arguments + array(
    'description' => t('Migration of group nodes from Drupal 6'),
    'machine_name' => 'RanchoNodeGroupNews',
    'source_type' => 'groupnews',
    'destination_type' => 'groupnews',
  );
  Migration::registerMigration('RanchoGroupNewsMigration', $arguments['machine_name'], $arguments);

class RanchoGroupNewsMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // OG Audience field
    $this->addFieldMapping('og_group_ref', 'og_group_ref')
         ->separator(',')
         ->sourceMigration('RanchoNodeGroup');
    $this->addFieldMapping('is_public', 'is_public');
    // Set the default owner to rm.com
    $this->addFieldMapping('uid', 'uid')
         ->defaultValue(4);

    $this->addUnmigratedSources(array(
    ),'DNM', FALSE);

    $this->addUnmigratedDestinations(array(
    ),'DNM', FALSE);

  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT oga.group_nid)', 'og_group_ref');
    $query->addField('oga', 'group_nid', 'group_nid');
    $query->addField('oga', 'is_public', 'is_public');

    return $query;
  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    drush_print_r($row->og_group_ref);
    return TRUE;
  }

  public function prepare($node, stdClass $row) {
    // Set og field_mode to 'admin' so we can save this group content despite not being a member of the group.
    // See https://www.drupal.org/node/2399997
    if (!empty($node->og_group_ref[LANGUAGE_NONE])) {
      foreach($node->og_group_ref[LANGUAGE_NONE] as $delta => $value) {
        $node->og_group_ref[LANGUAGE_NONE][$delta]['field_mode'] = 'admin';
      }
    }
    drush_print_r($node->og_group_ref);
  }
}

The output I receive from drush_print_r is as follows:

drush mi RanchoNodeGroupNews --idlist=60274 --user=1
56288
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [target_id] => 56288
                    [field_mode] => admin
                )

        )

)

Processed 1 (1 created, 0 updated, 0 failed, 0 ignored) in 0.2 sec (267/min) - done with 'RanchoNodeGroupNews'

                          [completed]

Note that nid 56288 is indeed the parent group node, and is the only parent that has been migrated. I am able to edit the group content and set the parent manually. Any idea what's wrong with my code?

Seems like a bug, but needed to add a complete() function as follows:

class RanchoGroupNewsMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // OG Audience field
    $this->addFieldMapping('og_group_ref', 'og_group_ref')
         ->separator(',')
         ->sourceMigration('RanchoNodeGroup');
    $this->addFieldMapping('group_access','group_content_access');

    ...

  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT oga.group_nid)', 'og_group_ref');
    $query->addField('oga', 'group_nid', 'group_nid');
    $query->leftJoin('og_access_post','oa','oa.nid = n.nid');
    $query->addField('oa','og_public','group_content_access');

    return $query;
  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    // Seems the access setting is actually the opposite in D7, so we need to
    // toggle the boolean here.
    $row->group_content_access = !$row->group_content_access;
    return TRUE;
  }

  public function prepare($node, stdClass $row) {
    // Set og field_mode to 'admin' so we can save this group content despite not being a member of the group.
    // See https://www.drupal.org/node/2399997
    if (!empty($node->og_group_ref[LANGUAGE_NONE])) {
      foreach($node->og_group_ref[LANGUAGE_NONE] as $delta => $value) {
        $node->og_group_ref[LANGUAGE_NONE][$delta]['field_mode'] = 'admin';
      }
    }
  }

  public function complete($node, stdClass $row) {
    $values = array(
      'entity_type' => 'node',
      'entity' => $node->nid,
      'state' => OG_STATE_ACTIVE,
      'membership_type' => OG_MEMBERSHIP_TYPE_DEFAULT,
      'field_name' => 'og_group_ref',
    );
    // Update the node
    $group_id = $row->og_group_ref;
    og_group('node', $group_id, $values);
  }
}

The above works regardless the number of groups the node is assigned to.

Note because this took me quite some time to figure out: the og_access and og_public have the opposite meaning from D6 to D7.


How to link user taxonomy-term to a list with all users with that term applied? So in my testcase you see, that there are some taxonomy terms applied to this user. However when one does click on a taxonomy term there appeares an empty view. Why are not all users with that taxonomy term listed?

First of all, I assume that the views module is installed and both the views and views_ui modules are enabled.

In the views admin page (/admin/structure/views), there is a view Taxonomy term. If you click edit to see the view settings, you will see that the view is only configured to show Content (i.e. nodes of a content type).

Off hand, I am not sure how to configure the Taxonomy term view to also show Users.  Anyway, I would not take this approach.

My suggestion is to:

Step 1) In the manage display screen for the User fields (/admin/config/people/accounts/display), set the display of your term field to Hidden.

Step 2) Add a new view page display that lists users associated with a term.  You need to use a Contextual filter on the term id (TID).

Step 3) Add a new view block display to lists terms associated with a User.  You need to use a Contextual filter on the user id (UID), so that only the terms related to the user are displayed. For the term field, Rewrite the output so that it is formatted as a link to the aforementioned view page (Step 2) and passing the TID as an argument.

Step 4) Display the view block on the user page such that it appears in a region below the user fields.

This is somewhat involved, but should work.

You may also want to take a look at the module https://www.drupal.org/project/taxonomy_display. This module may open up some other options.


How to increase priority of my custom CSS? I have this View:

The empty rows have a distrib0 class that should make the background red.
For that I have a custom CSS (amap.css) with tr.distrib0 {BACKGROUND-COLOR:#FF0000;} in it.
I have this amap.libraries.yml containing

amap:
  version: 1.x
  css:
    theme:
      css/amap.css: {}
  js:
      js/amap.js: {}
  dependencies:
    - core/drupalSettings

and finally, I attach the CSS with

function amap_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'calendrier_des_distributions' && $view->current_display == 'page_1') {
    $view->element['#attached']['library'][] = 'amap/amap';
  }
}

As you can see in the screen capture, my CSS is there but after color.css which is part of the current theme.
And of course my background is not red!
What can I do (besides adding tr.distrib0 in tr.distrib0 to color.csswhich I'd prefer to avoid)?

You have added wrong CSS here. Background color will not works with tr tag because we have style of td over tr tag.
Please correct with this code

tr.distrib0 td {
 background-color:#FF0000 !important;
}


Notice: Undefined index: driver in Database::openConnection() when trying to connect to sqlite db In one of my modules I try to connect to one SQlite DB to copy from it the info into my MySQL DB, however after creating the db info and trying to add them into the Drupal context, I get the error Notice: Undefined index: driver in Database::openConnection()

here is my function:

function query_247($table, $conditions = array()){
  $module_path = drupal_get_path('module', 'cw_ticketing' );
  $databases['247cinema']['db1'] = array (
    'driver' => 'sqlite',
    'database' => $module_path.'/247cinema_part1.sqlite',
  );
  $databases['247cinema']['db2'] = array (
    'driver' => 'sqlite',
    'database' => $module_path.'/247cinema_part2.sqlite',
  );
  // die(var_dump($databases));
  Database::addConnectionInfo('247cinema', 'db1', $databases);
  Database::addConnectionInfo('247cinema', 'db2', $databases);
  try {
    db_set_active('247cinema');
    if (count($conditions)) {
      //some logic
    }else{
      $where_s = false;
    }

    //some logic

    db_set_active();
    return$records;
  } catch (Exception $e) {
    $msg = $e->getMessage();
    watchdog('error', $msg);
    db_set_active();
  }
}

Anyone has any idea ?

The documentation is a bit misguiding as it states that the database array should be identical to the way it is declared on the settings.php file. This is wrong!

After digging a little bit the core module it shows that addConnectionInfo is expecting a array that defines the database and the driver.

Here is the correct implementation:

      $module_path = drupal_get_path('module', 'cw_ticketing' );
      $db1 = array (
        'database' => $module_path.'/247cinema_part1.sqlite',
        'driver' => 'sqlite',
      );
      $db2 = array (
        'database' => $module_path.'/247cinema_part2.sqlite',
        'driver' => 'sqlite',
      );
      // die(var_dump($databases));
      Database::addConnectionInfo('247', 'db1', $db1);
      Database::addConnectionInfo('247', 'db2', $db2);


No page style appearing on Permissions page. The permissions page on my site has no styling/theme. It is the only administration page that has this problem. The page displays as if I have turned off styles. I am using Drupal 7. What could be causing this issue?

I recommend you to do the following:

delete css files under /sites/default/files/css and then checkout the administrator pages
go to /admin/appearance and select an administrator them at the bottom of the page. If its already been selected try to use another administrator theme
make sure "Use the administration theme when editing or creating content" is checked
clear your cache using drupal clear cache button under /admin/config/development/performance
Checkout Administer themes permission in the permission page /admin/people/permissions
try to open your site with another browser


Search api autocomplete - how to show search form? I use Search Api with Search api autocomplete module.

I made configuration of autocomplete module on Search Api page, but I do not see block for input.

Should I config anything else for it?

There should be a block named Search box in admin/structure/block, i think it is the search box by default of drupal.

Remember that this block uses a view that returns a JSON, you can specify which view to use entering admin/config/search/search_autocomplete


Captcha doesn't come out in my multiform webform I have a multiform webform with 3 steps. Why can't I seem to get the CAPTCHA to appear at the end of the form, even when I've already checked Add CAPTCHA administration links to forms? Am I missing anything?

I am using Drupal 7 and Captcha 7.x-1.0-alpha3.

admin forms is not the same as webforms. You need to manually add the webform to the captcha settings.

Go to admin/config/people/captcha/captcha/settings in the blank text box under "Form Protection" enter the form_id of the webform and save the configuration. Go to the webform page and you should be able to see the captcha there.

To quickly find the form_id of the webform, take the node id and append it to "webform_client_form_", for example if the node id is 3 your webform form_id will be "webform_client_form_3". If this is not your case, you can always use firebug to inspect the hidden form_id field.


Disable delete functionality on Webform submissions I need to disable/hide the delete functionality of weform submissions.

Marked as yellow on the images below.

Webform provides the following permissions, which can be controlled via the standard page at /admin/people/permissions:

Delete all webform submissions

  Allows deleting of any webform submission by any user. Generally an administrative permission.

Delete own webform submissions

Once you have those set for the required roles, the delete tab will no longer appear for those users.


How to avoid writing to database in form submit? I have a webform and I need to validate a condition before you type in the database.

Use the hook_form_alter, this is my code:

function validate_entry_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'webform_client_form_1'){
    $form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";
  }
}

/* function HOOK_FORM_SUBMIT */

function _validate_entry_webform_client_form_submit_handler($form, &$form_state){
  $option = $form['submitted']['eventos']['#value'];
  $data_total = db_query("SELECT count(data) FROM webform_submitted_data WHERE data = $option")->fetchField();

  print_r('<pre>');
  print_r($data_total);
  print_r('</pre>');
  exit();
}

I've noticed that my function to handle the submit is handled when it wrote in database.

I need a "hook" where you can get all the results before they are written to database. Validate the data and if everything is correct, follow the workflow in database insert.

Form validation is called in the the first part af your code not in the submit function. Add another parameter to your form_alter:

$form['#validate'][] = 'nameOfMyModule_functionName_validate';
$form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";

When validation passes, the submit function will be called. if not form_set_error can be called displaying a message like so:

function nameOfMyModule_functionName_validate($form, &$form_state) {
// Check for the color 'blue'.
    if ($form_state['values']['color'] == 'blue') {
    form_set_error('color', 'Sorry, your favorite color is actually yellow.');
    }
}


How to I create a backup of my content ONLY? I'm debating between using Feeds module and Backup and Migrate and I'm not sure which would be the best option here.

Here's the scenario - I've two versions of the same site - both drupal 7, both have the same content types and taxonomy structure. One is live, one is on a development server. Due to some unclear communication a bunch of content edits were added to the live site that need to be merged in to the development site where we've made major improvements with Views and several stylistic changes, so we can't just dump the database and then move it without wiping out all the new content on the live site.

So does anyone have a good idea on how to best move JUST the content tables from the database? I know it will be different from install to install, but if you could help me get an idea of what to look for I can use the backup and migrate module and just exclude every table except those which I need.

Thanks in advance.

Node export is the best option to take backup for contents. One click export, import for the particular content types.

  This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site.

  Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.

  You will need the same content types for the imports to work (unless
  using Feeds to import), and ideally relevant compatibility with
  fields, and modules.


Update module with Drush + commit with Git What's the best way to update a module and commit with git?

Currently I'd use drush pm-updatecode then inspect with git status. The problem then is there are many files that have changed, been added or been deleted. Then performing an add or rm on the right files seems a bit cumbersome.

Would it be better to first do rm on the module, commit, then drush dl, add, commit?

git add -A is the simple answer you are looking for.  It will add all of the files anywhere inside the current working directory, including any new files that were provided or removed pm-updatecode.  (Note: git add . behaves similarly to git add -A, except that it will not include removed files in the commit.)

There is one inconvenience with git add -A, though, and that is that if you have any stray files in the way, they will be added to the repository as well (obviously enough).  You can get around this problem by listing the files that should never be committed in a .gitignore file, or simply use git reset HEAD unwantedfile prior to git commit, as recommended by git status.

drush will manage this for you with the --version-control=svn option, but as you may surmise, this is only useful when you project is checked in to svn.  As of yet, no one has written --version-control=git.  This was discussed in http://drupal.org/node/797190, but closed "won't implement".  There are some other good git commands to try in that thread as well.


How can I add or remove links to nodes in a list depending on the values of some of the fields I have a lot of content migrated over from a legacy CMS.  All of the nodes have some value, but there were a lot of entries that don't need more than for their information to show up in the long lists (They don't need individual node pages).  Let's call the three fields that need checking:

abstract
related_websites
public_files

What would be the best way to set it up so that if abstract is empty, and the multiple entry allowed related_websites and public_files both have no entries, that the entry still be listed, but there be no link to the full node.

I'll need to do this all over the place, from search results to listings by date and by content type, so the easier it is to implement the better.  Would this be better done in a theme or a module?

This is probably one of those questions that might fall under opinion-based, but I'll give my answer.

The answer really depends on your needs. It comes down to the question, does stub content impact display or workflow (editing, moderating, viewing, etc.) around the content? In either case, you'll want a centralized piece of logic (e.g. mytheme_is_stub() or mymodule_is_stub() function) that determines if the content meet your stub criteria.

If it impacts just the display then you want a theme; you can use your centralized logic to determine when/where to alter rendering of content.

If it impacts the workflow (e.g. you want to prevent an author from creating stub content or alert them about stub content) then you want a module; you can use your centralized logic to determine when/where to alter workflow around the content.

From your description (altering links, search display, etc.), it sounds like your only concern is display, if that's the case then you want a theme.


How to add call a js file in custom module that are added in libraries folder in drupal 7? I am creating a custom module in drupal 7 and adding a js file in sites/all/libraries folder but its not working.Please check my code

function mymodule_library(){
$libraries['mymodule'] = array(
    'title' => 'My custom',
    'website' => 'http://www.test.com/test',
    'version' => '1.7.14',
    'js' => array(
      'sites/all/libraries/mymod/custom.js' => array(),
    ),
);
return $libraries;

}

That code just registers the library with the system. To use it, you need to add it to the page with either

drupal_add_library('mymodule', 'mymodule');

or as part of a render array:

$build['#attached']['library'][] = array('mymodule', 'mymodule');


Why can only admin user access the print version of a view? I have installed the Printer, email and PDF versions module and I have a view named XXX and the admin can access to the print version of the XXX view with the path /printpdf/XXX.
If I change the user to other user without admin permission, I get this message

Access denied
You are not authorized to access this page.

I don't know how to allow non admin users to access the print version of a view.
I set this permissions for non admin users like so:

Bypass views access control.
Access the printer-friendly page.

But such user still does not have access to the print version of a view.
Is there a way to achieve the access with non admin users?

I have a help at this moment from a friend. The solution is simple, just search the permission Access the PDF version in admin/people/permissions and set the permission to the users. The problem was that the permission page is too long and if you search for print you will never find Access the PDF version` permission


How can I hide a certain warning message showing to users? I would like to hide the following warning message from users when they submit a web form. I know when this warning message shows up and don't really need to fix it but just want to hide it from users.

warning: trim() expects parameter 1 to be string, array given in /public_html/sites/all/modules/phpmailer/includes/phpmailer.drupal.inc on line 33.

I tried Disable message module but it's only for the Drupal system error message.
Is there anyway to hide a certain warning message just like above?

You need to include ini_set( 'display_errors','0'); in your setting.php file in drupal site.

See more about error reporting
http://php.net/manual/en/function.error-reporting.php

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)

ini_set( 'display_errors','0');


Using drush to sql-sync local to remote, without remote MySQL binaries on remote I'm working with a prod and staging environment where the MySQL binaries (like mysqldump) are not installed. PHP can interact with MySQL just fine, but for reasons that are not relevant, the binaries aren't installed.

It appears that when performing an sql-sync, drush will attempt to ssh into the remote server, run the dump, then rsync the file down, then import it. Is there a way to avoid this, maybe a way of telling Drush to perform all the database operations locally? My workstation has access to the remote databases, so it is capable of performing mysql imports and dumps on the remote databases.

I understand that Drush cannot account for all edge cases like this. I wonder if anyone knows if there are workarounds for this or suggestions? I can just write my own scripts to do the syncing of databases, but would love to leverage drush.

Drush version 3 and onward (via the sql-sync command) can only copy the database via the ssh + mysql executable method that you describe above.  If you download drush 2.1 (https://drupal.org/node/614830), you will find a command drush sql-load that works as you describe.  It's a lot slower than sql-sync, so if your database is very large, you might find this technique to be too cumbersome.  If it works for you, though, it probably wouldn't be very hard to make your own external Drush commandfile to provide sql-load on a more recent version of Drush.


How do I remove the "My account" and "Logout" links? I am trying to sub-theme the Bootstrap theme. How do I  remove the My account and Logout links from the navigation bar?

Try going to Appearance settings on your sub-theme admin/appearance/settings/... and uncheck Secondary menu.

If that doesn't work, check menu settings at admin/structure/menu/settings and make sure you haven't defaulted the main menu to "User menu".


Custom content type with a gallery and its "subgalleries" (or categorized gallery) in D7 I have a content type with some custom fields, and I would like to have a gallery in it, with the images grouped into predefined "categories" - like a "subgallery".

For example, I have a "building" content type, and I would like to categorize the photos of it depending on of which part of the building (house) these photos were made or if they are simply archive photos, etc.: you can think of categories e.g. like "Inside", "Outside", "Archive", "Misc."

I made a drawing to make it clearer:

What would be the best way to solve this problem?

Thanks for any kind of ideas!
Ask if anything is unclear.

In the meantime, I found a Media Gallery issue related to the topic:
New feature: Gallery containers (other related issues: Hierarchical galleries, Categorizing galleries)

I don't know how well exactly this will fit in with your use case, but this is how I'd do it:

Create a content type called "SubGallery", add an Image field to it with unlimited cardinality.
Create the content type you want to contain the sub-galleries ("Building")
Add an Entity reference field to the "Building" type that references an unlimited number of "SubGallery" nodes.
Choose "Inline Entity Form" as the widget for that field, which will allow users to create the "SubGallery" content types within the same form as the "Building".

You can make use of the standard node title field for the name of the sub-gallery, or you might add a vocabulary called "Gallery Type", and add a field referencing that to the "SubGallery" content type. Then when your users add a new sub-gallery via the inline edit form, they can choose one of your pre-defined gallery types to associate with it.

If you do add the vocabulary and no longer need a node title for the sub-galleries,you could use Automatic Nodetitles to fill it in automatically and hide it from the users.


How to get a rendered output field from view object programatically I can get the value of the field from the view object like this:

foreach ($view['#view']->result as $row){
      $field_slide_banner = $row->_entity->get('field_slider_banner')->getValue();
    }

However, in this case I get the target_id of the referenced image file, but I need to get the full rendered output data, which depends on format that I set for this field at the view display, for example, that should be the URL of the image in my case.

In other words, I want to be able to get final output data or HTML markup programmatically for any view field from the given row of executed view object.

Use the following code.

foreach ($view->result as $row) {
  // Change the full view with your view mode.
  $render_array = $row->_entity->field_slider_banner->view('full');
  $field_slider_banner_markup = \Drupal::service('renderer')->renderRoot($render_array);
}

Alternatively, you can use the following code.

foreach ($view->result as $id => $row) {
  $my_field_value = $view->style_plugin->getFieldValue($id, 'field_name');
}


How do I add the "error" class when a form validation fails? I'm working with Drupal 7.56 and I am using the Webform module to create a custom form.

I used hook_form_alter() in a custom module to add a validation test.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='webform_client_form_1') {
    $form['#validate'][]='mymodule_form_validate';
    return $form;
  }
}

function mymodule_form_validate($form, &$form_state) {
  $aux = $form_state['values']['submitted']['aux'];
  if ($aux != '') {
    if( /* my test */ ) {
      $text = t('Please check your input');
      form_set_error('aux', $text);
    }
  }
}

How can I add the error class when my test fails?

First try removing your if test and see if you can get the form_set_error to trigger. That way you can make sure your test is correct. You should be able to call form_set_error in a validation function and it will work.

If that isn't the problem then make sure the name of your field is correct.

To answer the question about simply adding a class in form validation you can use the following:
$form_state['complete form']['aux']['#attributes']['class'][] = 'error';

It won't add to the input itself but to the field wrapper and you can style it from there. But I think figuring out why form_set_error isn't behaving how you want is your best bet. That should really be adding the error class.


View outputs Access-Control-Allow-Origin header I have created a view (via the views module) which outputs a JSON output (minus the template etc) I have loaded the page and it outputs data as required.
I now need to call this page from another domain (cross domain) - however, when I am calling the page from the other domain (through javascript) I am obtaining the common

  Failed to load https://<>: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

The Query: Where within the views module would I be able to set the 'Access-Control-Allow-Origin' value such that it would either allow all requesting sites to be served the page or only specific domains to be served the page.

Side Note: As things stand I am not able to install other modules on the primary domain where the JSON page resides, as I am restricted to what I can do on that site.

As people of have worked with cross domain access will no doubt have guessed by now I am using the Chrome browser.

Side Note 2: When I use the Chrome extension "Allow-Control-Allow-Origin: *" I am able to load the page as required because the whole access control check is by-passed, but I need the loading functionality to work without the need for such an extension.

You can use the https://www.drupal.org/project/cors module to add the allowed domains to your project.

Or you can alter the .htaccess file or change the headers of the php file like described in https://stackoverflow.com/questions/14467673/enable-cors-in-htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.php [QSA,L]
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"


Call a Javascript Function and Update my Form Element at the same time This is my ajax callback function

function myid_search_idnumber($form, $form_state)
{
    return $form['id'];
}

It updates the values in $form['id']. But Because I wanted to call a javascript function as well as update the form, I added a few codes:

function myid_search_idnumber($form, $form_state)
{
    $commands[] = ajax_command_invoke(NULL, 'myid_update_id_number');
    $page = array( '#type' => 'ajax', '#commands' => $commands, );
    ajax_deliver($page);

    return $form['id'];
}

The three lines of code added above, calls a javascript function.

$.fn.myid_update_id_number = function(){
    alert('Wew');
}

Performing those only calls the javascript function but does not update anymore my form. How will I call my javascript and at the same time update my form?

Just to ad to the above answer by Ollie.
To return form['id'] too (same as the default behavior), you can use ajax_command_replace

function myid_search_idnumber($form, $form_state){
    $commands[] = ajax_command_replace(NULL, render($form['id']));
    $commands[] = ajax_command_invoke(NULL, 'myid_update_id_number', array($form['id']));
    $page = array(
         '#type' => 'ajax',
         '#commands' => $commands,
      );
    ajax_deliver($page);
  }


Is there a way to import Drupal variables into a the twig template? I save a configuration setting using the following code.

$config = \Drupal::service('config.factory')->getEditable('report.settings');
$config->set('id', $values['id'])->save();

Is there a way to use this configuration in my twig template?

I thought about putting PHP code in the template, but it doesn't seem the PHP code added with <?php ?> is executed from the Twig template.

You can't directly use these functions in a Twig file. Instead, you can preprocess the page and store your configuration settings in a variable that is passed to the template file, and display that variable in the template file.

function mytheme_preprocess_page(&$vars) {
  $vars['new_var'] = $config->get('id');
}

You can render your variable with {{ new_var }}.


Render custom block using block.html.twig template I'm attempting to render a custom content block programmatically (created through the Custom Block Library UI) and I would like the block to render using block.html.twig as it would if I were to place it in a theme region. I have the block placed in a disabled region and I can get the block body field to render programmatically, but it is not wrapped in the usual block template and does not include the block title. I'm using the code to render a "content block" from the accepted answer here: How can I programmatically display a block?

$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;

As I understand it, I need to render the instance of the custom block that I have placed inside the disabled region, so I would expect that I have to use the machine name of that instance. I've done a lot of searching and come up with nothing. It's strange that nobody else seems to want to render the block with the title in the block.html.twig template.

BlockContent is the only entity in Drupal not having a template of its own. So you have to wrap it in a template yourself:

$block = \Drupal\block_content\Entity\BlockContent::load($bid);
if ($block) {
  $content = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
  $build = [
    '#theme' => 'block',
    '#attributes' => [],
    '#configuration' => ['label' => 'My Block', 'label_display' => 'visible'],
    '#base_plugin_id' => 'block_content',
    '#plugin_id' => 'block_content:' . $block->uuid(),
    '#derivative_plugin_id' => $block->uuid(),
    '#id' => $block->id(),
    'content' => $content,
  ];
  return $build;
}


What is "Advanced Mode" in Views 3? In this article the first instruction is

  On every site, run drush vd to turn the Views settings to the advanced mode.

What does this mean? A Google search for "Views advanced mode" yields mostly just links back to this article. What is "advanced mode"?

Advanced mode means

  Set the Views settings to more developer-oriented values.

You can check the definition of this in views module Drush folder views.drush.inc file.

  $items['views-dev'] = array(
    'callback' => 'views_development_settings',
    'drupal dependencies' => array('views'),
    'description' => 'Set the Views settings to more developer-oriented values.',
    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
    'aliases' => array('vd'),
  );

Once drush vd command is executed following variables are set.

  variable_set('views_ui_show_listing_filters', TRUE);
  variable_set('views_ui_show_master_display', TRUE);
  variable_set('views_ui_show_advanced_column', TRUE);
  variable_set('views_ui_always_live_preview', FALSE);
  variable_set('views_ui_always_live_preview_button', TRUE);
  variable_set('views_ui_show_preview_information', TRUE);
  variable_set('views_ui_show_sql_query', TRUE);
  variable_set('views_ui_show_performance_statistics', TRUE);
  variable_set('views_show_additional_queries', TRUE);
  variable_set('views_devel_output', TRUE);
  variable_set('views_devel_region', 'message');
  variable_set('views_ui_display_embed', TRUE);
  $message = dt("Setup the new views settings.");
  drush_log($message, 'success');

You can do it with out using drush command too by navigating to "admin/structure/views/settings"


How to use Ubercart product SKU as a condition in Rules? I need to display a message on the cart page if one or more specific SKUs are added to the cart.

For example, if a product with SKU # ABC123 is added to the cart, the Rule should be triggered and thus display a message... if a product with SKU # XYZ789 is added to the cart, the Rule would not be triggered and no message would be displayed.

It seems like this should be a fairly simple function, but for the life of me I cannot find a way to accomplish this. Can anyone please point me in the right direction?

Thanks!

This answer does not use Rules, but rather hard-coding inside of the cart template.

As the message should be displayed each time the user is on the /cart page, something like this might work. If page--cart.tpl.php doesn't exist, create it and add ...

$items = uc_cart_get_contents();
foreach($items as $item) {
    if($item->model == 'ABC123') {
        drupal_set_message('Item ABC123 is in the cart');
    }
}


What could cause the Wysiwyg module / CKEditor randomly disappearing and coming back? I've successfully installed and configured the Wysiwyg module with CKeditor. However, it keeps disappearing. First it disappeared when I enabled another module (cannot remember which, but thankfully it wasn't necessary so I could disable it again). I was just lucky to figure that out.

But now it disappeared again, and I don't know what happened this time. I didn't install any new modules.

Any ideas why this is happening? Is the wysiwyg module too unstable to use? If so, what's the alternative?

EDIT:

The issue keeps coming back, but I have discovered something new: if I disable a module (and optionally enable it again), apparently pretty much any module, then the wysiwyg editor appears again(!)

So it seems any change in the modules installed brings the editor back. I have only tested this in localhost, if that has anything to do with it.

go to modules and find jQuery Update module, and put it to version 1.8
That should fix the issue.


Best practice to deploy an update which depend of a new configuration In an entity type, I need to replace a field by another with a more complexe behavior. This new behavior can reproduce the old field and add new. Like this behavior have an impact on the design, I need to update all entities with this new field to keep the data of the old field before delete it.

This import is done with a hook update. My problem is, in my hook_update is executed before I import my configuration. But I can't migrate my data in my new field like it doesn't exist yet. So, my question is, what's the best practice to do that:

Should I create programmatically my new field on my entity type in a hook_update and migrate my datas in the new field before import my configuration. This possibility allow me to delete the old field with configuration and everything will be over. But, if I create my field programmatically, I can do some errors or difference between what I have in my configuration. And, additionally, I want be lazy and don't reproduce a code which exist elsewhere. It's a little problem and I see I can improve this workflow.
Can I import configurations which concern only (and only that) the new field, do my migration of datas and import the rest of my configuration as usually? This seems be the best practice but I don't know if it's possible.
An other solution?

I thought about import all configurations before do the hook_update but this solution seems the worst thing to do: I can have update of contrib modules in my release and configurations could be apply only after these updates (I never met this case, but it's could be possible). Additionally, I will keep my old field until the next deploy.

I suppose my first solution is the only I can do but, maybe I don't thought about another.

I would recommend that you create the field programatically. In your update function. You could also create multiple update functions, just create the field in one, then migrate the data then remove the old field.

If you have a lot of data, then your update function should be done as a batch, so it doesn't run in any PHP timeouts or memory limits. In that case, having the update functions separate makes it easier to implement them.

To avoid duplicating code, you could read the config from the config sync storage and create it through the config entity storage, something like this:

$config_record = \Drupal::service('config.storage.sync')->read('field.storage....');
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$entity = $storage->createFromStorageRecord($config_record);
$entity->save();

This is usually fine for custom update functions in projects because it will only be executed once. This approach is risky for core/contrib/reused modules (which usually import it from their default config) because you don't know when the update will be executed. Maybe you have to make another change to that config next week and add another update function to deal with that change, but if someone didn't execute the first yet, this initial update will already create the field based on the latest schema and then your update logic might get very confused about that.


When programmatically adding views, what is a more efficient way to add them other than include them in mymodule.views_default.inc? I have written a module that writes views programmatically, and my mymodule.views_default.inc file is enormous. Currently there are 150 individual views, and 780 will be the target.

But, even with the test group of 150 several things are happening.

1) when enabling the module via drush, php memory usage goes through the roof. It climbs into the gigs (TOP command), but it finally loads.

2) but, when I then try to view the site I get WSOD, and the top command shows apache2 climbs into the gigs for memory usage until the Apache process actually crashes.  Of course there is not enough memory to load it, and it's of course unrealistic to put php memory limit in the gigs.

What's going on here? How is the code in mymodule.views_default.inc actually handled once it's loaded? Where is it being loaded to? Is it loaded into memory for each Apache process? If I can actually get it loaded will my Apache process footprints actually shrink back down to something normal?

Can this file be divided up into individual files, and would this even help? Is it better to someway put them into the database instead of using the file at all?

In other words, how can I get almost 1000 views loaded and continue doing business as usual?

note, if you are curious, this is a census data project. I don't want to use filters or arguments as each set of data needs to to have its own individual page URL and other criteria unique to that data set.

I'm not 100% sure if it'd help performance-wise, but it is possible to separate the Views into different files. In your case, this is probably useful anyway as that's a LOT of Views.

If you create a folder in your module called "views" (or whatever you want), then you can just add the following to your implementation of hook_views_default_views.

function MYMODULE_views_default_views() {
  $files = file_scan_directory(drupal_get_path('module', 'MYMODULE'). '/views', '/.view/');
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }
  return $views;
}

DISCLAIMER/CREDIT:

This code was taken from this blog post, and this comment, so make sure you pop over there and say thank you :)


Create Context Based on Field File Type I want a means of triggering a different Context depending on the type of file used in a field on a given content type.

I have been struggling with trying to achieve this for a few days/weeks now after recently moving from D6 to D7. After trying it with Panels I've moved onto Context Module and Context Entity Field. I'm hoping I can finally get this sorted so all help appreciated thanks.

I don't know if it's my lack of D7 experience that's causing this. Basically, I'm working with one content type. It has a Multimedia asset field. I allow uploading, adding images and youtube media via url in this field. I was wanting to create a new page context if the field contains youtube video field. If it has an image then let's do another context etc. Only one of these filetypes are allowed per node.

Context Entity Field seems to only work if the Multimedia asset field has something, or not. I was wanting to use context on file type.

Is this possible or am I really missing some simple D7 point that wasn't there in D6?

Thanks

Note that I am using Media Module for this Multimedia asset field.

Can I suggest a slightly different strategy? If you have the Rules modules installed - or are willing to install it - then can use a Rules condition to apply the specific test you want. If it passes that test, you can get Rules to set a field on your node that Context can respond to.

So, for example, you could have a Term reference on your content type that has three vocabulary items 'YouTube', 'Image', 'Empty'. Rules can set this field whenever the node is saved. And Context is able to respond differently depending on the Taxonomy Term that is present.

A downside is the user gets to see the Term reference field when entering data, but since it's changed to the right value on save anyway, this may not be a big deal. You can tell the user to ignore this on the form and hide it away, e.g. in a closed fieldset. Or if you are a Display Suite user, you can easily hide using configuration.

I've tested whether Rules can pick up the media type and can confirm it does so quite cheerfully. To start the process, add a new rule and choose React on event with the type 'Before saving content'. Supposing you have a field on your content type with the machine name field_media, then you will need to use a Data comparison condition that checked [node:field-media:file:mime] to see if it is equal to video/youtube or image\png etc. You may need to do a bit of fishing to get out all the relevant mime types. You'll then need to create an appropriate action when the condition is true. You'll probably want several rules bundled together in a Rule set.

A single condition will look a bit like this:

If you've not used Rules before, it can be a bit fiddly to set up the first couple of times, but well worth it. Knowing that it can detect the condition that is of interest to you, means that this is a solution that you can make work.


Adding custom Text changes the horizontal alignment in Content type I have a content type. For two fields I am using horizontal tab item . those two fields Section_grid_image and section_grid_image_path are displayed one after another so I have used hook_form_alter and added custom CSS.

function displayor_form_alter(&$form, &$form_state, $form_id) {

//Load CSS
$form['#attached']['css'][drupal_get_path('module', 'displayor') . '/form.css'] = array();

if ($form['#id'] == 'section-node-form'){ //contenttype-node-form

   $form['field_section_grid_image']['#prefix'] = '
';
   $form['field_section_grid_image']['#suffix'] = '
';
   //where field_test is your file upload field

   $form['field_section_grid_image_path']['#prefix'] = '
 OR';
   $form['field_section_grid_image_path']['#suffix'] = '
';
   //where field_test is your file upload field
 }
}

CSS

#leftcolumn{
width: 400px;
float: left;
}

#rightcolumn{
 width: 600px;
 margin-left: 200px;
}

#innercolumn{
 width: 500px;
}

My alignment is getting like this:

I want the fields and OR to be displayed in a line.

How to do this.

EDIT: Got the answer.Below CSS did the trick.

function displayor_form_alter(&$form, &$form_state, $form_id) {

//Load CSS
$form['#attached']['css'][drupal_get_path('module', 'displayor') . '/form.css'] = array();

if ($form['#id'] == 'section-node-form'){ //contenttype-node-form

   $form['field_section_grid_image']['#prefix'] = '
';
   $form['field_section_grid_image']['#suffix'] = '
';
   //where field_test is your file upload field

   $form['field_section_grid_image_path']['#prefix'] = '
(OR)';
   $form['field_section_grid_image_path']['#suffix'] = '
';
   //where field_test is your file upload field
 }
}

CSS

#leftcolumn,
#rightcolumn,
#orseperator
 {
   float: left;
   margin-right: 77px;
   padding: 10px;
 }
 .or
  { left: 382px;
   margin-right: 25px;
   margin-top: 1px;
   position: absolute;
   top: 76px;
  }

Why dont you just do the following:

   $form['field_section_grid_image']['#suffix'] = '

 OR';

   $form['field_section_grid_image_path']['#prefix'] = '

';


How do you access custom user information added from: Configuration » People » Account settings I'm looking to create a script that pulls some of this information, but I need to know how to call it. For example one of the 'machine names' for one field is field_first_name how could I call this?

At the moment I'm using:

<?php
global $user;
print $user->name;
?>

Below is what I'm looking for, pulling the custom information instead of the username.

<?php
global $user;
print $user->feild_first_name;
?>

try $account = user_load($user -> uid) after global $user and then dsm($account) or print_r($account);,
global $user get only basic data of object I think


Adding a Taxonomy term in a node via services I am trying to submit a node via an android native app in java.  I am using services 3.3, and I am able to login, and submit to a Content type assuming all of the fields are Text fields.

But I would also like to add some taxonomy terms as fields.  The Tax term is already defined on the drupal system.  I have a term NAME: "A". tid:37.

what is the services technique to submit a Tax term?  or even some hints.

I also want to submit some images as well... another question perhaps

I'm not familiar with Services module or drupal's web service (I usually use Symfony for such Services), but I don't think there are any specific rules for such task.
Assuming there is a callback in your module which receives a data from external resource, e.g.:

function module_menu()
{
  ...

  $items['my-path/%'] = array(
    'title' => 'TITLE',
    'page callback' => 'myCallback', // this can be either `drupal_get_form` or your callback function..
    'page arguments' => array(1),
    ...
  );

  ...
}

and define that callback:

function myCallback($data /* assuming $data is an array, but It can be another type, JSON, XML... */)
{
  if(empty($data)) {
    // some dummy check
    return 'Invalid data';
  }

  $node = entity_get_controller('node');
  $node->type = 'MY_TYPE';
  // set other base fields such as author...

  $nodeWrapper = entity_metadata_wrapper('node', $node);

  $nodeWrapper->field_MYTEXTFIELD->set($data['text_field_data']);
  $nodeWrapper->field_TERMFIELD->set($data['term_field_data']);
  ....
  $nodeWrapper->save();

  ...

  // finally return response
}


How to grab the values of field collection items in a template file? I have a field collection field_plaats_en_aantal with two fields: field_plaats (text) and field_aantal (integer). I'm currently displaying this field collection in a node view as an unordered list:

I'd now like to theme the field collection a bit in order to get something like this instead:

It seems fairly easy, but I can't find a way to achieve this. At first, I tried to work with a template file views-view-field--field-plaats-en-aantal.tpl.php, but I don't know how to grab the values of the field collection items there. Is this a good way to work on? If yes, how can I get the needed values?

Afterwards, I read some things on the internet about templates for the field collection items themselves and tried using two templates field-collection-item--field-plaats.tpl.php and field-collection-item--field-aantal.tpl.php, because that seemed an easier solution to me. However, those files aren't scanned and therefore don't affect the theming of the fields. What am I doing wrong?

It turned out that I was making things too complicated: the theming can be achieved with CSS by using the default classes of the field collection. Hopefully, my code underneath can be helpful for others too.

.item-list li {
  list-style: none;
}

.field-name-field-plaats:before {
  content: "@ ";
}

.field-name-field-plaats {
  display: inline;
}

.field-items {
  display: inline-block;
}

.field-name-field-aantal:before {
  content: " (";
}

.field-name-field-aantal:after {
  content: "x)";
}

.field-name-field-aantal {
  display: inline;
}


Bootstrap framework - Sub-theme template.php not having any effect I installed bootstrap framework for drupal and copied the sub-theme into my themes directory, renamed all the files accordingly and everything works fine, however any php code that i put in my sub-theme template.php file is not having any effect.

I tried adding google fonts, css files and some other functions to template.php but nothing works, even tho the code is valid.

I wonder what am i doing wrong? Should i be editing base theme template.php file, even tho it will get updated and deleted? Or is there some other reason why my sub-themes template.php has no effect?

If you change in template.php then you have to clear the theme cache. Because the contents of the this file is cached in the database, so altering it will not be noticed by Drupal.

You can clear cache from here

Drupal 7: Administration > Configuration > Development > Performance (admin/config/development/performance)

For more information visit Clearing the theme cache


How to SUM/add the values of two fields in a View? I have two separate fields in a View:

Miles on Engine at Time of Purchase/Delivery (field_engine_hours_at_delivery)
Miles added to Engine After Purchase/Delivery (field_util_agg_engine_hours)

(1) is a standard integer field. (2) is fed by an aggregation of many other content items. My view is set to display these two values in a table, side by side.

I would like to now add those two fields to get a "Total Miles on Engine" value for the view. I tried adding a Views PHP field with the following PHP code, but the result that is returned is blank.

Value Code

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_engine_hours_at_delivery'))) + array_pop(array_pop(field_get_items($entity_type, $entity, 'field_util_agg_engine_hours')));

Output Code

  <?php $display_output = $entity_field_item['value']; ?>

I'm not very well-versed in PHP, so I'm sure I've got something amiss in that code. Can anyone clarify whether this can be done... and if it can, what I need to change in my code to make it work?

P.S., I also tried this version of the Value Code, but still did not get any result:

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, '$row->field_engine_hours_at_delivery'))) + array_pop(array_pop(field_get_items($entity_type, $entity, '$row->field_util_agg_engine_hours')));

Thanks!

There's a module for that: Views Calc allows you to SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns in Views.


How to make in CCK a field like a grid In my site I want user to add a new album of images
he have to add
 1. title
 2. description
 3. sub form that contain Image and title and set to default (radio button) and he can add   more than one sub form

and only one image will be the default site that will appear in home page (Selected from radio button)

How can I make things like that

Presuming CCK=>Drupal 6, and without writing a custom module or custom compound CCK type, you could do something like this:

Create a cck content type, let's call it album_image, and in it have the following fields:

a.  Image field
b.  text field for title
c.  text area for description
Allow your users to create/edit these content types and fields via permissions
Create a view that returns all album_images created by the logged in user
Add a node reference field to the user's profile (The Content Profile module is an easy way to do this) and restrict it to one result, and call it for discussion here default_image.
Within CCK screens for the field above, use the view you created above to populate the "returned values" for the node reference instead of just selecting a content type.
Now, when your user edits his or her profile, they can select one album_image as the one they want displayed.

Now within your user profiles you have a field called field_default_image that contains the nid of the album_image your user wants to have displayed on his or her profile, so you can then load that up to get the image and use that wherever you need, eg, within whatever preprocess functions you use within your theme to paint the profile.


How can I make a view which displays the categories of a parent category? Possible Duplicate:
  Taxonomy in Contextual filters for Views

I want to browse the categories in my catalog. This is what my vocabulary looks like:

Products

prod1

subprod1

prod2

subprod2

subsubprod2

prod3

How can I make a view which displays the categories of a parent category? When you click Products you should see prod1, prod2 and prod3. When you click prod2 you should see subprod2. When you click subsubprod2 you should see the nodes in the category.

Anyone?

Thanks!

Views comes with a default view that overrides the taxonomy pages. Enable this and then edit the view. Under "Advanced" change the depth of "Content: Has taxonomy term ID (with depth" to display the depth of your choosing. I think there may also be a setting in the Taxonomy Display module that also allows you to modify the depth without using views.


How to create a rule to send an email when someone creates content of selected type(s)? I'm trying to create a rule (using the Rules module 8.x-3.x-dev) to send an email when someone creates content that is of the type Announcement or Article, but I can't seem to get the event to trigger properly. It's sending an email for every node that is created. Can anyone help with the proper method of setting the content type? My rule is as follows:

Event: After saving new content (rules_entity_insert:node)

Condition: Node is of type

Node Value: @node.node_route_context:node

Content Type Value: Announcement, Article

I'm trying to create a rule (using the Rules module 8.x-3.x-dev) to send an email when someone creates content that is of the type Announcement or Article

To my knowledge, the current answer to this question is a no go: You can't do that yet with the most recent Drupal 8 version of the Rules module.
Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.
Plan B
While waiting for Rules to become more mature, you can use the Admin Content Notification module as a temporary alternative (which does have an official D8 release already). Some details about it (from its project page):

... can be used for receive email notification when a new content of any content type will be created on your site. Although one can use rules for the same functionality but it's not good to use rules only for notification as it is a huge module, so we can use this module for small websites.

The "...Although one can use rules for the same functionality ..." part of this clearly does not apply to the D8 version of Rules (yet).


How do I append HTML after a form title? This is the output I want:

Name!

The only way I can think of is to concatenate my HTML to the form title value

'#title' => t('Name') . '!',

This kind of works, but is ugly: the output is:

Name!

The #suffix property won't do because it adds my HTML outside of the form element's wrapping div.

Any ideas. Thanks.

You shouldn't concatenate the result of the t() function, it should rather be built up as a single string:

'#title' => t('Name <span>!</span>'),

Other than that, you're already doing this about the cleanest way possible. Other approaches would involve post-processing the form element(s) to render their title in a different way than standard. I imagine that would end up being more trouble than it's worth unless you wanted to do it globally for every element in every form in the site.


TinyMCE strips out audio tag I'm using TinyMCE and I'm using the Full HTML format which shouldn't strip any tags. I copy another web page with an html5 audio tag in it and paste it into the editor. I can see the html5 audio player there, but when I save, it is stripped out.

I tried again and this time brought up the raw html editor and directly put the audio tag into the html. When I click Update, the audio tag is stripped out.

Here is my Full HTML text format config:

You need to deselect "Verify HTML" in the configuration page for the input format using Wysiwyg. Those settings are available in admin/config/content/wysiwyg.

Once I disabled that option, I tried with the following HTML, and it worked.

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mp3">
  Your browser does not support the audio tag.
</audio>

With that option enabled, this is what I get right after entering the HTML with the HTML button.


Where are the database username and password stored? I'd like to send my Drupal installation to a colleague, but I don't want him to see the username and the password of my database. Where are these informations stored?

I've seen that the username and the password are written in sitename/sites/default/settings.php, but is it the only file with these informations? Is it sufficient if I change the username and the password in this file and then send my colleague all my Drupal files and my database?

The settings are stored in sites/default/settings.php. That is indeed the only file with that information and it is sufficient that you change the username and the password in that file.


Hooks for altering Views block output in Drupal 6 I have a View in which i mention 3 fields then i displayed as a block.

I want to want to change value of these fields.

  Which hook will i use so i can change content to fields on page load ?

  I tried  hook_view, hook_block, they don't help me.

Thanks

You could use hook_views_pre_render to alter the results of the View before Views passes the data of for rendering.