How to add Vue.js validation attributes to input elements? I've seen a tutorial about enhancing Drupal's elements using Vue.js validation component. The input markup is like this:

<input class="username form-text required" autocapitalize="none" type="text" id="edit-name" name="name" value="" size="60" maxlength="60" v-model="name" v-validate.initial="name" data-rules="required|alpha|min:3">
<input type="text" id="edit-mail" name="mail" value="" size="60" maxlength="254" class="form-text required" v-model="mail" v-validate.initial="email" data-rules="required|email">

But how do I add the Vue.js custom attributes to these input field?

I suppose you only want to add Vue specific attributes to certain form elements, not every single one of them (including admin/backend forms).

Presuming you are using Drupal 8, I'd recommend enabling Twig debugging. That will help you to identify which fields you want to alter.

Once twig debugging is enabled Drupal should expose theming details for each element. In your case you need to know about template and hook names.

The input field shown in the screenshot is using input.html.twig template file from core/themes/classy/templates/form/input.html.twig, and theme hook is input__textfield

For your specific question, I recommend adding those attributes via preprocess hooks in your theme. For example;

<?php
function YOURTHEME_preprocess_input__textfield(&$variables) {
  $element = $variables['element'];

  if ($element['#name'] === 'title') {
    $variables['attributes']['autocapitalize'] = 'none';
    $variables['attributes']['v-model'] = 'name';
    $variables['attributes']['v-validate.initial'] = 'name';
    $variables['attributes']['data-rules'] = 'required|alpha|min:3';
  }
}

My example above is NOT very specific, it only alters "textfields" with the name "title". I recommend targeting more specific form elements.


How to create link to a view I've a view with a page display on url "progetti".

On my controller I'm trying to create a link to this url but I can't find the right way. I've added \Drupal\Core\Url namespace on top of the file.

I'm creating an items list:

$url = Url::fromRoute('progetti');
$variables['items'][]['value'] = array(
  '#type' => 'link',
  '#title' => array('#value' => 'sergio'),
  '#url' => $url,
);

It doesn't work, also if I use "/progetti" as argument.

Logs say:

PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "progetti" does not exist."

As you want to create url object from a path instead of route, use the function fromUri() instead of fromRoute().

$url  = Url::fromUri('internal:/progetti');
$variables['items'][]['value'] = array(
  '#type' => 'link',
  '#title' => array('#value' => 'sergio'),
  '#url' => $url,
);

In fromUri() function you need to pass the URI of the resource including the scheme. For user input that may correspond to a Drupal route, use internal: for the scheme.


EntityMalformedException: Missing bundle property on entity of type node in modal I want to open create content type in modal, according to modal form and modal api example, I implement it, I test

the problem is here
when I test it by contact form

    ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    // 'title' => t('Contact'),
    'ajax' => TRUE,
  );
  module_load_include('inc', 'contact', 'contact.pages');
  $output = ctools_modal_form_wrapper('contact_site_form', $form_state);

every thing work correctly and  there is no problem,but when I change it to

ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    // 'title' => t('Contact'),
    'ajax' => TRUE,
  );
module_load_include('inc', 'node', 'node.pages');
$output = ctools_modal_form_wrapper('page_node_form', $form_state);

return me **
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /drupal-7.24/share/ajax/1
StatusText: Service unavailable (with message)
ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7724 of /includes/common.inc).** , where is the problem?

I create a menu, and it open a modal,I want add content in that modal

EntityMalformedException: Missing bundle property on entity of type node

This means that at some point in code when the node entity should be handled, it is unclear what type (bundle) that is. Now when you look at node_form() you see that it expects a node object as a parameter. If that's not given the node add form doesn't know what fields and properties to render because the node type can't be identified. Looking further into node_add(), which is the function normally called to create a new node of a specific type, I think you could go along the following lines (completely untested):

global $user;
ctools_include('modal');
ctools_include('ajax');
$node = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'page',
  'language' => LANGUAGE_NONE,
);
$form_state = array(
  'ajax' => TRUE,
  'build_info' => array(
    'args' => array($node),
  ),
);
module_load_include('inc', 'node', 'node.pages');
$output = ctools_modal_form_wrapper('page_node_form', $form_state);


Bootstrap search form wrapper alter I am using the 7.x-3.0 version of Bootstrap and have sub themed it. I want to change wrapped div, add 'input-group-sm' to the class bit I can't not figure out how to override it. if I add search-block-form.tpl.php to my sub theme I can access and alter that but the code I need is in bootstrap-search-form-wrapper-func.php I have copied that to my sub theme with no success. I have tried replicating the same file structure as Bootstrap 'mytheme/theme/bootstrap/bootstrap-search-form-wrapper.func.php', I have tried putting just in my templates dir.

My last attempt was trying to follow the instructions on theme registry alters: https://www.drupal.org/node/2224003 which I have as this:

function CFbootstrap_theme(&$existing, $type, $theme, $path) {
  $hooks['CFbootstrap_hook'] = array(
    'CFbootstrap_search_form_wrapper' => array(
      'render element' => 'element',
    ),
  );

  bootstrap_hook_theme_complete($existing, $theme, $path . '/theme');
  return $hooks;
}

Nothing works, what I am doing wrong? How do I override this *.func.php?

OK, I have this figured out, I think I just got confused by instructions and getting ramped up again on the ways of Drupal. Anyway just to leave a clear answer. All subthemes will be called MYTHEME. In my template.php in my subtheme I altered the form and then added hook to my new form wrapper:

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
if($form_id) {
    switch ($form_id) {
        case 'search_form':
            dpm($form);
            $form['basic']['keys']['#theme_wrappers'] = array('MYTHEME_search_form_wrapper');
            break;
    }
  }
}

function MYTHEME_theme(&$existing, $type, $theme, $path) {
  $hooks = array(
      'MYTHEME_search_form_wrapper' => array(
      'render element' => 'element',
      'file' => 'MYTHEME-search-form-wrapper.func.php',
    ),
  );

  return $hooks;
}

In this I copied the original wrapper file and made my changes, you could just copy the method and add it to your template.php anyway here's that method, referenced earlier as 'MYTHEME-search-form-wrapper.func.php':

function MYTHEME_MYTHEME_search_form_wrapper($variables) {
  $output = '
';
  $output .= $variables['element']['#children'];
  $output .= '';
  $output .= '<button type="submit" class="btn btn-default">';
  // We can be sure that the font icons exist in CDN.
  if (theme_get_setting('bootstrap_cdn')) {
    $output .= _bootstrap_icon('search');
  }
  else {
    $output .= t('Search');
  }
  $output .= '</button>';
  $output .= '';
  $output .= '
';
  return $output;
}

Key here is having the subtheme name twice in the method call. The instructions I found on this didn't give an explanation on why that needs to be. I'll try to find relevant information.


How do I POST a new node? I have referred many links including the following:

Services module. How to construct the JSON data with session info for creating node?
GitHub
- Creating a node using Services 6.3 REST

I tried several ways to POST a new node to a Drupal site, but I have failed. I have created a sample CCK for storing students data with name, age, gender, DOB, and added some list.

I have installed and configured the Services module (D7), and created a service end point at services.
As expected, GET is the easiest way to get details of a node in JSON. http://localhost/drupal/services/node simply listed all nodes.

I still can't figure out how to use the POST method.

I would like to search for the students whose name contains john. I tried localhost/drupal/services/node&node[name]=john. I used  POST Man plugin for Chrome without success. I also tried some other ways.
I tried adding a new student to the site without success.

Can anyone guide me to make the above work fine?

UPDATE :

I tried adding new nodes of type article . It worked fine. but when i am trying to add nodes of type Department CCK It is showing "s:22:"CSRF validation failed";"
Here are the screen shots

I have gone through the link https://drupal.org/node/2013781

I followed session = session_name=session_id but i still get an error.

Hope this will help you,

For Drupal 7

Tools used:

Firefox Poster add-on to do tests and debugging.
There may be other add-on as well. But for this example im using Firefox add-on.
To help editing and validating the JSON data you can use

Edit the JSON data using this link
Validate the JSON data using this link

HTTP requests

To make the HTTP requests, you need use the Firefox add-on POSTER.
Two commonly used methods for a request-response between a client and server are:

GET
POST

After the add-on is Downloaded. Open Firefox -> Tools -> Poster

Make sure to enable the Session authentication. After the Services is configured properly, before creating the node you should log-in. Once logged-in you can create the nodes.
For login use POST method, with the URL like - http://XXXXXXXX.com/demo/rulebook/rulebook_endpoint/user/login

If it is a valid user then it will return user details with session ID and Name. If not valid it will return Access denied

By using Session name and ID in the POST HEADER, we can able to create new nodes

Now after adding the HEADER, You need to make HTTP POST request and make sure  user should have permissions to create node.

If the node is created you will get the response with node link

NOTE : If you want the response in JSON then, you should always append .json at the end of the URL. eg., http://XXXXXXXX.com/test/endpoint/user.json OR http://XXXXXXXX.com/test/endpoint/node.json OR http://XXXXXXXX.com/test/endpoint/user/user_id.json OR http://XXXXXXXX.com/test/endpoint/node/node_id.json


Get nid of nodes which contains FPP I have some fieldable panel pane and I can attach this FPP in diferent nodes with panelizer functionality.

How can I get nid of nodes which contains(attach) this FPP programmatically ?

I have fpid but how can I check in which nodes use this FPP ?

I'm looking for a similar solution, I work on a site with thousands of fieldable panel panes and need to find all the nodes that contain a certain fpid. The most promising lead I've found is: Find node programmatically by field value so if you've found a better solution (maybe using views) I'd like to hear about it.


Retriving field value I have field called field_3d_model_xml_path which is a text type. I am currently retriving the value like this.

//get current node
$node = menu_get_object();
//build xml path
$xmlPath = DRUPAL_ROOT . "/" . $node->field_3d_model_xml_path['und'][0]['value'];

Is this right way to do it or there is some better way?

The safest way is to use field_get_items() like this (which will handle any languages):

$xmlPath = '';
if ($items = field_get_items('node', $node, 'field_3d_model_xml_path')) {
  $xmlPath = $items[0]['value'];
}

If you want to access it like you currently are (sometimes it is useful to do so but in your case I don't think so, this is just to be more complete), use the LANGUAGE_NONE constant for the 'und' language instead of hard coding it, like this:

$xmlPath = DRUPAL_ROOT . "/" . $node->field_3d_model_xml_path[LANGUAGE_NONE][0]['value'];


How to check if entity id exists or valid? I have created a content entity type. When I save form, I got id in routing url, like:

entityform/1

entityform/2

But if I directly access some non-existing id like entityform/999, page dies.

In watchdog, it is showing error,

  Error: Call to a member function get() on null in Drupal...

I can not call function get() on the fields of entity, if entity doesn't exists.

$content_type = $entity->get('ctype')->value;

How to apply this check, whether entity actually created or not?

You can check if the entity object isset() or is not NULL, and use get() only if the condition passes.


How to display the user email on account pages? On the user account page all feilds are displayed except for the email. I have tried to modify the user-profile.tpl, and added

print $user->mail

but it displays the logged in user and not the account being displayed. Not a big problem since the end users usually only see their own account bit frustrating for admins. I also tried

print render($user_profile['mail']);

but that displays nothing.

You can implement the following hook in the template.php of your theme:

/**
 * Process variables for user-profile.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 *
 * @see user-profile.tpl.php
 */

function YOUR_THEME_preprocess_user_profile(&$variables) {
  $account = $variables['elements']['#account'];
  //Add mail to $user_profile variable
  $variables['user_profile']['mail'] = $account->mail;
  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
}

And in your user-profile.tpl you can use:

print $user_profile['mail'];


Can I create surveys with unique URLs for each recipient? Does anybody know if there's a module that can support unique URLs for survey participants?

To clarify, what I mean is, I'd like to send out letters/ documentation to people in a particular geographic area. I'd like to encourage them to complete a survey, but for each recipient of the letter I'd like to assign a unique URL for their survey, which can then be used by me to marry them up to the data I already hold about them.

So, for example:

Person A receives a letter and is given a survey URL of www.mysite.com/ab123
Person B receives a letter and is given a survey URL of www.mysite.com/eg462
Person C receives a letter and is given a survey URL of www.mysite.com/qt368

and so on.

For a number of reasons, this method is better for my data collection purposes, rather than asking participants to include an assigned ID number or their own details.

You can use the webform API in a tiny module to access the form to add a hidden element to it. Then use the handy Drupal arg() function to determine the value of your unique URL argument. After, use the webform API function to change values before saving to the hidden field for administration usage later.

I can't guarantee this will work so hopefully some of the other Drupal Stack Exchange folks can verify this.


How to print sid value in webform? I have created a form using webform module, and alter form In D7

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

  global $user;

  if('webform_client_form_1' == $form_id) {

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

  }

}

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

.............

.............

}

I write print_r($form_state); in mymodule_check_email function.

Get all variables but sid value is empty but in database sid insert proper.

My question how to get sid value.

The sid won't be available from a validation handler; validation handlers are called before form submission, thus a valid sid for your submission doesn't exist at time of execution.

If you need to call a post-submit webform hander, the webform module provides hook_webform_submission_insert():

function mymodule_webform_submission_insert($node, $submission) {
  // The submission object contains $submission->sid, the submission id.
  print_r($submission);
}


Remove the special characters (like %20) from URL Is it possible to replace the URL encoded characters for space,?,etc. with the exact character ? Because one of the content in my site takes the following URL and it doesn't looks so nice!

  https://expatchoice.asia/eat-drink/restaurants-casual/ana-intercontinental-tokyo%E3%80%80ana%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%82%B3%E3%83%B3%E3%83%81%E3%83%8D%E3%83%B3%E3%82%BF%E3%83%AB%E3%83%9B%E3%83%86%E3%83%AB%E6%9D%B1%E4%BA%AC

Please take a look at transliteration module. Together with pathauto you could get better urls. But i don't know how well this works with chinese characters.


Editing status message contents I want to change the contents of a status message, it is being brought in via the commerce module (commerce_cart.rules.inc).

The error message I want to change is:

/**
* Rules action: displays a the default translatable Add to Cart message.
*/
function commerce_cart_rules_add_to_cart_message($product) {
  drupal_set_message(t('%title added to your cart.', array('%title' => $product->title, '!cart-url' => url('cart'))));
}

I don't want to apply a patch to commerce just to change a status message so does anyone know of any alternate solutions?

Thanks

You can just remove the default Display a translatable Add to Cart message action and add a custom message that you want to be displayed yourself.

You can do this at /admin/config/workflow/rules/reaction/manage/commerce_cart_add_to_cart_message.


How to check if a database query has results? How do I check if the following code has results?

I tried the empty function but it always returns FALSE

$query = db_select('my_table', 't');
$query->condition('code', 10)
      ->fields('t', array('cid'));
$result = $query->execute();

If I'm correct the result of the execute() call should be a DatabaseStatementInterface which has a rowCount function.


Can I call menu_rebuild() only for one module or specific hook_menu? Is there a way to call menu_rebuild so it will only update items
in selected module and / or hook_menu ?

I need it to update links ( if they are already existing ) and add new
( if they are now ).

Don't want the menu_rebuild to clear the menu_router.

I am afraid that's what the function does. From Drupal docs:

  This function will clear and populate the {menu_router} table, add entries to {menu_links} for new router items, and then remove stale items from {menu_links}. If called from update.php or install.php, it will also schedule a call to itself on the first real page load from menu_execute_active_handler(), because the maintenance page environment is different and leaves stale data in the menu tables.

I guess you could try to reimplement the function into your own custom one and modify its source according to your needs. It looks like a lot of work though. You'd probably have to reimplement more functions.

Source: https://api.drupal.org/api/drupal/includes!menu.inc/function/menu_rebuild/7


How can I add fields to a block? I'm learning Drupal 8 after working with 7 for a number of years and I'm a bit unsure how to approach this. I need to be able to add a block and have it appear on a few specific pages.

I also need to be able to add some text and a link to this block. Is there a way to add these as fields to the block that can be filled in when the block is added to the page?

It looks like I could accomplish something similar by creating a new content type with those fields and adding it as an "Entity view" but this seems like overly complicated.

Is there another way I'm not aware of?

You can create a Custom block type (admin/structure/block/block-content/types/add) and then add fields to it (admin/structure/block/block-content/manage/YOUR_BLOCK_MACHINE_NAME/fields).

You will see that you have the Manage form display and Manage display tabs too like the content types, you don't need to create a content type. In Drupal 8 you can use blocks in more than one region.

Check The Block System is Finally Useful in Drupal 8 and see the video.


Drupal and Git workflow using Acquia cloud Currently i have my central repo (origin repo) on a Bonobo Git Server.

I have followed those steps to use Acquia Cloud with a remote repository.

On my Acquia cloud repo i installed Drupal 8.

also i already cloned my origin repo (Bonobo Git Server) locally to my computer.

Now i think the best workflow is to clone the Acquia Cloud repo locally isn’t it? With the whole Drupal 8 core and all files from the Drupal 8 installation.

So after that i can add contributed modules and themes to my local repo and commit and push them to my origin repo (Bonobo Git Server) and the Acquia Cloud repo?

Is this the a correct workflow? And how do i get all the Drupal 8
files from Acquia Cloud to my local repo?
i have read also something about 'Translating your root directory with git subtree' in this article. Is this correct and what do i have to do exactly regarding my workflow
Is it advisable to use Acquia dev desktop also?

Disclaimer: I work for Acquia

This library article you linked to originates from an blog post that was written 4 years ago to answer questions about deploying from Jenkins build servers, private Github repos, etc. There's nothing specific to Acquia Cloud per se and it's rather a Git strategy you need to come up with for your development needs.

Is the Bonobo Git Server going to be the 'origin' going forward?

If yes, then simply add the Acquia Cloud as a new remote (e.g. 'ac').
Git allows you to push to different remotes without any issue.
If not, then you should make Acquia Cloud the 'origin' and Bonobo a
regular remote (probably easier).

Since Git is decentralized, you 'own' the repo at any point in time and the main reason for keeping a remote is if you have a continuous integration system you need to pass your codebase through before you deploy code to Acquia Cloud. Another good reason is if you have a preferred Git workflow (think Github pull requests for instance) you wish to continue working with. But if you simply want to mirror your Acquia Cloud repo to (for instance) back it up, then I'd argue to just keep the Acquia Cloud repo and simplify your workflow.

The idea to keep in mind is you need only one checkout of your codebase. Having several remotes allows you to handle where to push to as described in the article.


drupal_is_front_page() fails when using alias If I set the default front page to use a node with an alias, e.g. 'home', drupal_is_front_page() fails as it compares the un-aliased path ($_GET['q']) with the value of the 'site_frontpage' variable. Would it not be better to save the 'site_frontpage' variable as un-aliased path, or am I missing something?

Sorry, this is actually what happens. The variable must have been set to 'home' by something else.

drupal_is_front_page() compares the content of the "site_frontpage" variable with an un-aliased path because the content of that variable is set to an un-aliased path, on the page at admin/config/system/site-information.

In system_site_information_settings(), the form builder for that page, the content of the "site_frontpage" field is set using the following code:

'#default_value' => (variable_get('site_frontpage') != 'node' ? drupal_get_path_alias(variable_get('site_frontpage', 'node')) : ''),

In system_site_information_settings_validate(), the form validation handler for that page, the value of the "site_frontpage" field is set using the following code:

  if (empty($form_state['values']['site_frontpage'])) {
    // Set to default "node".
    form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
  }
  else {
    // Get the normal path of the front page.
    form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
  }

What is being saved in the "site_frontpage" variable is the normal path (a.k.a. the un-aliased one). It is the correct what drupal_is_front_page() does.
If there is a module that set the value of that variable to a path alias, then the code of that module should be changed, as that module is not working with the actual Drupal code.


How to add “Quote Request” button on some products? I'm using Drupal Commerce and I want a quote button on some product (node) page so that a potential buyer can enter some brief information and click to send a Quote Request for the item that they are viewing.

I have a product type called "Premium products", and I want this Quote Request button instead of price to be on some page.

On clicking the Quote Request button and asking a quote to the seller, the seller may respond to the query and tell the proposal amount for the product which user can accept or reject. Once accepted by user, the product should be added to the user's cart with the purposed price.

Have a look at the feature request "Let customers build a 'quote' cart and request a quote instead of checkout". Even though it has status "postponed", it has some interesting comments, such as the very first one, which includes this (I added the bold markup):

You probably don't need any specific module to do a majority of this. All you'd have to do is add $0.00 prices to all your products and then just don't display those prices anywhere. You don't have to show product price fields in your display nodes, and you can edit your cart Views so they don't include prices any more. The only thing you'd really have to change is the text pertaining to the shopping cart. You could do this with a module like String Overrides or just alter the various places directly with a hook in a site customizations module.
When it comes time to submit the quote, I suppose you may want a custom button on the Cart form that changes the status of the order to "Needs quote" or something - if that's true, then that's all your custom module should really be responsible for ...

Also, the comment #7 in that same issue seems worth considering, this is part of what it says (I added the bold markup):

I got this working quite easily! As Ryan said, make all product prices $0. Use String Override module and override a couple of the basic syntaxes. Edit a couple of Views where certain terms/words still creeped through. When you see syntax that needs to be changed on a view and you've already used String Override for it but it's not overriding it, just click on the right corner of the view on the gear to edit view. Then change the wording on there. I also had to remove or change some of the text that were on some views but under the "FOOTER" section (middle section of view). I had to do this a lot for the cart and checkout views.
I added another checkout rule under Store>Configuration>Checkout Settings under "Send Request"-section to email me when the person places a request.

Maybe not a complete solution / answer to your question, but at least a partial answer to think about ...


How to install Drupal without interaction via web UI? Is it possible to confgirue installation profile so it can be installed via web UI as usual but without any interaction, just the progress bar?

You can Install Drupal using Drush without interacting WEB UI.
You have to use following command

drush dl drupal-7.x --drupal-project-rename=D7
cd D7
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://YourMySQLUser:YourMySQLPassword@localhost/YourMySQLDatabase

Ofcourse You have to install Drush if not already installed and change Mysql Database details in command as per details.

Choose installation profile that you want to install

site-install standard OR site-install minimal


Kernel tests: Url toString with language option In a Kernel test I need to test the result of an url object per language. But the test doesn't consider the language settings.
Example:
public function register(ContainerBuilder $container) {
    parent::register($container);

    $language = Language::$defaultValues;
    $language['id'] = 'de';
    $language['name'] = 'German';
    $container->setParameter('language.default_values', $language);
}

protected function setUp() {
    parent::setUp();

    ConfigurableLanguage::createFromLangcode('fr')->save();
    ConfigurableLanguage::createFromLangcode('it')->save();
}

public function testUrls() {
    $languageManager = $this->container->get('language_manager');
    print_r($languageManager->getLanguages());

    $url = Url::fromRoute('<front>');
    $url->setOption('language', $languageManager->getLanguage('fr'));
    print_r($url->toString());
}

Output:
Array
(
    [de]
    [fr]
    [it]
)

# Output of toString()
/

The output of toString should be /fr instead of /
Addendum:
I discovered that the \Drupal\language\HttpKernel\PathProcessorLanguage outbound processor is missing, when UrlGenerator::processPath() is called from the Kernel test. Therefore, I registered it in the Kernel test's register method, but that doesn't solve the problem.

Solution
I could solve it by register the PathProcessorLanguage class and add the language.types and language.negotiation config.
public function register(ContainerBuilder $container) {
  parent::register($container);

  // Define the default language.
  $language = Language::$defaultValues;
  $language['id'] = 'de';
  $language['name'] = 'German';
  $container->setParameter('language.default_values', $language);

  // Register PathProcessorLanguage.
  $container->register('path_processor_language', PathProcessorLanguage::class)
    ->addTag('path_processor_outbound', ['priority' => 100])
    ->addArgument(new Reference('config.factory'))
    ->addArgument(new Reference('language_manager'))
    ->addArgument(new Reference('language_negotiator'))
    ->addArgument(new Reference('current_user'))
    ->addArgument(new Reference('language.config_subscriber'));
}

protected function setUp() {
  parent::setUp();

  // Add additional languages.
  ConfigurableLanguage::createFromLangcode('fr')->save();
  ConfigurableLanguage::createFromLangcode('it')->save();

  // Define language settings.
  $this->config('language.types')->setData([
    'configurable' => ['language_interface'],
    'negotiation' => [
      'language_interface' => [
        'enabled' => [
          LanguageNegotiationUrl::METHOD_ID => 0,
        ],
      ],
    ],
  ])->save();

  $languageKeys = array_keys($this->container->get('language_manager')->getLanguages());
  $this->config('language.negotiation')->setData([
    'url' => [
      'source' => LanguageNegotiationUrl::CONFIG_PATH_PREFIX,
      'prefixes' => array_combine($languageKeys, $languageKeys),
    ],
  ])->save();
}

Addition
If you want to use/test path alias configs too, just register the AliasPathProcessor class...
public function register(ContainerBuilder $container) {
  parent::register($container);

  // ...

  $container->register('path_alias.path_processor', AliasPathProcessor::class)
      ->addTag('path_processor_outbound', ['priority' => 300])
      ->addArgument(new Reference('path_alias.manager'));

  //...
}

... and add the path alias entry for the specific language.
protected function setUp() {
  parent::setUp();

  // ...

  $pathAlias = PathAlias::create([
      'path' => '/foo',
      'alias' => '/bar',
      'langcode' => 'it',
    ]);
    $pathAlias->save();

  // ...
}


Is it possible to use stringoverride on ONLY one page? I want to modify ubercarts "Add to cart" text button but only on ONE page that I've customized. I haven't been able to figure out how to call the button via php so I don't know if that's possible. I figured I could use string override but that would change the text across all pages and for that I can just change the option in ubercart.

I'm betting you're looking for hook_form_alter() ... I'm pretty sure its just a form buttom on the page and you can change its #valueproperty as-needed with that hook. Its up to you to figure out how to target just that form, on just that page ... I don't think you need stringoverride for this.

You would want to test this out of course :)


Entity reference view display is not displaying fields as expected I have a number of registered users on my drupal 8 website who some of them are "active" and the others are "blocked".

I want to add a select list field inside the article content type displaying only user with the status= active (Easy job!)

Note: I have added a field to the user page (field_full_name) and I want to display the users using their
"Full Name" and not their "Usernames". (Still an easy Job!)

So I did the below:

Create a new view to show "users"
Create an "entity reference" display for the view.
Delete the "username" field created by default
Add the Full name field to the view (field_full_name)
Add the filter field "User: User status (= Yes)"
Inside the Settings of the "Entity Reference" View, check the "User: Full Name" as the search field.
Save the view.
Add the view as a user reference field to the article content type by selecting the Reference method: Views: Filter
by a entity reference view and for the View used to select the entities: Select the created view above.

Now, when you add a new article /node/add/article, if you try to select a user from the dropdown select list,
you will notice that all users are displayed using their usernames and not their Full Names.

In other words, I like to have something like this in the select list:

Full Name 1.
Full Name 2.
Full Name 3.
Full Name 4.

but actually I am receiving this:

Username 1.
Username 2.
Username 3.
Username 4.

Also I noticed the same behaviour when I tried to create an "entity reference" view displaying all the groups that the current
logged in user is a member of, by doing the below steps:

Create a new view and set the view to show: "Group content" of type: "All".
Add relationship: "The group containing the entity".
Add relationship: "Relates to the user entity that the group content represents".
Add a contextual filter: "User ID" and when the filter value is not available select: "User ID from logged in user"
Delete any available field created by default.
Add the field: "Title" (to show the title of the group)
Create an "entity reference" display for the view.
Inside the Settings of the "Entity Reference" View, check the "Group: Title" as the search field.

Now, add this view as an "entity reference" field to any content type for example "Article" and when you will add a new article
/node/add/article, if you try to select a Group from the dropdown select list, you will notice also that all
Groups are displayed using the username of the current logged in user and not by their Group titles.

In other words, lets say the current looged in username "Admin1" is a member of 3 groups titled:
(Group Title 1, Group Title 2 and Group Title 3)

you will see that the entity reference select list field is displaying:

Admin1
Admin1
Admin1

Instead of:

Group Title 1
Group Title 2
Group Title 3

What am i doing wrong ?!

Is there something wrong with the "entity reference view" display ?!

any help ?

It is worth mentioning that if you just duplicate the "Entity reference" display to a "page" display and you visit that
page, you will indeed see a list of users displayed using their Full Name or list of Groups displayed using
their group titles

Thank you in advance,

You could use the realname module (which now has a D8 release). Or, you could alter the user name as displayed in Drupal:

function HOOK_user_format_name_alter(&$name, $account) {
  // Load the full user account.
  $account = \Drupal\user\Entity\User::load($account->id());
  // Get the full name from field_name.
  $full_name = $account->get('field_name')->value;
  // If there's a value, set it as the new $name.
  if (!empty($full_name)) {
    $name = $full_name;
  }
}


How do I create a content type that has another content type embedded inside of it? I'm building a content type for a journal-type product. In each journal there are a number journal articles that vary from journal to journal, which have their own unique fields (like author, date, subject, synopsis, etc). Right now I've set it up so you fill out all of the contents for the articles and then you pull them into the journal via entity reference.

Ideally though, it would be great if I could just streamline all of this into the same "create content" form. For example, when I click "create new journal", I want to get all the fields for my journal plus the ability to dynamically add journal articles and all of their fields.  It could be in a different tab or something, it just needs to be in the same create journal content type form.

Use References dialog. "This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog"


What is the proper syntax to call the theme function for a node, passing an argument? I'm writing a Drupal 7 application that has many content types. Each of these content types has a custom template for display. For instance, I have node--event.tpl.php, node--person.tpl.php, node--feedback.tpl.php, and so on.

I'd like to be able to manually call a theme function on a node that should have an overriding template. i.e. something like the following:

<?php print theme('node', array('node' => $node)); ?>

The reason for this is that I've written a module called Content Inclusion which allows pieces of content to be manually included within one another. I'm trying to have this line of code in my node.tpl.php file to automatically display the included node along with the parent node.

I appreciate any and all suggestions, but I would be more interested in learning about ways to make this work - this module has some very specific requirements that existing modules were not able to address. Thanks.

You should use the node_view function for that, which attaches fields to the node and creates a build array, which when rendered will use the node theme function that you try to use directly.


How can I automatically restore my site from a backup using the command line for testing purposes? I am on Mac OS X using MAMP PRO as my local development environment.  I want to quickly reset my site to a known state in order to run some tests I have prepared in Selenium.

I have the Backup and Migrate module installed which makes it easy to restore from the command line via drush, but if I restore using Backup and Migrate it appears to only overwrite the existing data and leaves other data in place, which I don't want-- I want to erase all of this other data as well so that I can be sure that the database is in exactly the same state as the backup file.

Currently, I log in to PHPmyadmin, drop all of the tables in the database, and then re-import from the backup.  This seems somewhat inefficient to me; is there a way to automate this from the command line?

I use /applications/mamp/library/bin/mysqldump -uUSERNAME -pPASSWORD DATABASE >backup.sql to back my database up and then /applications/mamp/library/bin/mysql -uUSERNAME -pPASSWORD DATABASE <backup.sql to restore it.


How to add content type to front page I created a content type Carousel.
I created a region Huge.

On the front page, I want the content type to be placed in the region Huge.

Current process:

Create content
Specify publish to front page.

Even though I specify this:

render($page['carousel']).

All of the content is being loaded in:

render($page['content']).

What is the drupal way of doing this on the front page?

The use case is for marketing to create new Carousel content type >> publish to front page >> the HUGE region is updated with new content.

This should be different than regular blog's posts that appear on the front page.

Thanks for any help!
noah

You can use Views module to create a block and place that block in your custom region

Here is the step by step process to create a slide show with slide show module
And  placing block in the region can be done here
admin/structure/block

To create custom block and template

/**
  * Implements hook_theme().
 */
function YOUR_MODULE_theme() {

$theme = array();

$theme = array(
    'my_custom theme' => array(
        'variables' => array('items' => array()),
        'template' => 'my-custom-theme'
    ),
return $theme;
}
/**
* Implements hook_block_info().
*/
function YOUR_MODULE_block_info() {
   $blocks = array();
   $blocks['slideshow'] = array(
   'info' => t('Block Name'),
);
return $blocks;
}
/**
 * Implements hook_block_view().
*/
function YOUR_MODULE_block_view($delta = '') {
   $block = array();
  switch ($delta) {
        case 'slideshow':
        $block['subject'] = '';
        $block['content'] = _YOUR_MODULE_slideshow_callback();
        break;
     }
   return $block;
 }
function  _YOUR_MODULE_slideshow_callback() {
  $result = "Your query to fetch content";
   foreach($result as $row){
       $items[] = $row;
       }
   $output = $output .= theme('my_custom theme', array('items' => $items));;
    return $output;
 }

and write html code for your slide show in my-custom-theme.tpl.php file


Is it possible to show taxonomy terms in a views filter sorted alphabetically? I have some content that is classified using a two-level taxonomy:
Accommodation -> B&B
Accommodation -> Hotels
Accommodation -> Self Catering
Things to Do -> Arts & Crafts
Things to Do -> Family attractions
Eating out -> Cafes
Eating out -> Restaurants

In some situations, I need to display all these categories together in views as a taxonomy filter.

When I do that, they are displayed grouped by the parent term, so they look weirdly random.  Is it possible to break them out from their parent term and show them in the filter sorted alphabetically, or alternatively, show the parent term as well as the child term, so that it's clear why the terms are sorted like that?

I am on Drupal 7, Views 3.11.

Upgrade taxonomy and views to the latest version and select the following options.

And when the filters terms are being listed, they will be listed in alphabetic order.

You can confirm that there is hierarchy in terms and they are not alphabtic in order.


How to map different entity types as layers with OpenLayers? My implementation requires the mapping of multiple entity types, which is difficult to achieve in vanilla Gmap with Views.

In the documentation, OpenLayers states that layers can produced from views of OpenLayers data type. Is it really as simple as specifying a few layer views and adding them to a map?

If so, and multiple views can be served as data sources to OpenLayers, what does one have to do to convert a Location/Gmap set up to OpenLayers?

So, OpenLayers requires Geofield as a spatial data format, which is better than the Location Module for spatial formats. There's no simple solution to convert the data, so you spatial content will have be updates with Address or Geofield formatted data. I used Views CSV export and Feeds to dump and spit back the data to the right fields. From there, I followed the tutorial here Multiple Layer Maps with OpenLayers creating multiple data overlay views to a build a map based on layers of different views. This let me overlay my users over my other spatial nodes.


Views Filter: Has referencing entities I'm using the Views and Entity reference modules in Drupal 7. I'm trying to do the following:
Make a view to list nodes of type A (teasers)
Expose filters to filter this list

I have other nodes (type B) that reference A nodes. I would like to add an exposed filter in the form of "Has referring nodes" (of type B implicitly).

My problem is that the only way I am able to do it is by using operators like "greater than" and I don't find a "has" operator. I can implement it as "greater than 0" and it works but it looks really ugly because the user has a text field to put the 0. I would like to have a checkbox that toggles on/off a filter that works like "greater than a fixed value" or an actual "has" filter.

I think the question it is Views related but Ive mentioned the Entity relation just in case its important for the problem.

Thanks for your help.

PD: I have just thought that a "is referred" filter will also work, so thats a third possible solution I'm looking for.

If you are willing to have an extra field, consider using Corresponding Entity Reference.

  It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.

So basically, if properly configured, it will give you "is referred by" field you mentioned in your last paragraph.

For Drupal 6, use Corresponding node references module.


Override quicktabs tab titles I have a quicktabs instance that shows lists of content by year (2012, 2011, 2010 and so on). Each tab is a views generated block that pulls content by date using relative values (current year, current year-1, etc.). How can I override the title of each of the tabs so that I don´t have to hardcode year values as tabs titles? Thanks in advance.

I finally got this to work by adding on my template.php:

function YOURTHEME_quicktabs_alter($quicktabs) {
if ($quicktabs->machine_name == 'YOUR_QTABS_NAME') {
  $currYear = date('Y');
  for ($i = 0; $i <= 3 ; $i++ ) {
    $yr = ($currYear-$i);
    $quicktabs->tabs[$i]['title'] = t($yr);
  }
}

}
}


How to format a date submission value of a webform? I need to format a birthday submission value to the short format (01.01.2015) defined under admin/config/regional/date-time on a webform.

This Token is working but it uses the long format (Fr, 01/01/2015):

[submission:values:bday]

I tried the following token variations :

[submission:values:bday:short]
[submission:values:bday:custom:short]
[submission:values:bday:custom:d.m.Y]
[submission:values:bday:date:short]

But none of them submits my desired output. Any Ideas?

I finally found a answer myself.
Instead of changing the date format tokens you can set the date format globally for webforms under admin/config/content/webform.


Is it possible to hide certain content type options? I have a module which creates a new content type attached to a Feed. For this content type having options such as "Comment settings" or "Revision information" makes no sense. Is there a way to hide those?

I assume your logged in as admin (user 1), so you'll always see them, but for other users it depends on the permissions they have and you can also use http://drupal.org/project/override_node_options to toggle this for each role


How to attach image from a list of predefined images? Anyone had this? I have a custom content type and I want to give an option to attach an image from a list of predefined images (in my case - a list of product series logotypes). The admin interface would be a simple dropdown of logotype labels:

- None -
Series 1
Series 2
Series 3

How would I then process the selection and convert it into a real image?
What would be the best practice here?

Regards,
Artur

These are general guidelines as I made something like this but for D6.
I would create a logotype variable in template_preprocess_node and then loop on you dropdown variable. For each value selected I would add an <img src='path/to/logo1.png' alt='Logo 1' /> to your logotypes variables.
Then just display the variable in you node template.


How to include a custom menu in page.tpl I want to code a custom menu straight into page.tpl.php. The default theme uses

<?php if ($main_menu): ?>
  <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->
<?php endif; ?>

In Drupal 7 I've created a new menu called 'Footer menu'. How do I code that into my theme in the same way as the $main_menu is coded  in the default theme?

Try this

<?php
 $menu = menu_navigation_links('menu-your-custom-menu-name');
 print theme('links__menu_your_custom_menu_name', array('links' => $menu));
?>

You can also add to template.php

function THEME_preprocess_page(&$vars) {

$menu = menu_navigation_links('menu-your-custom-menu-name');

$vars['custom_menu'] = theme('links__menu_your_custom_menu_name', array('links' => $menu));

}

the variable $custom_menu is available in the page tpl


How to add a rule condition from select-list in a webform This an export of my rule

{ "rules_webform_to_simplenews" : {
    "LABEL" : "Webform to simplenews",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules", "simplenews_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "webform-client-form-113",
          "selected_webform" : { "value" : {
              "webform-client-form-27" : "webform-client-form-27",
              "webform-client-form-113" : "webform-client-form-113"
            }
          }
        }
      }
    ],
    "DO" : [
      { "simplenews_rules_action_subscribe" : { "mail" : "[data:e_mail-value]", "tid" : "211", "confirmation" : "2" } }
    ]
  }
}

When a webform is submitted, the e-mailadres is added to the newsletter-subscriptions.
But there should be an extra condition that the submitter agrees the subscribing by checking a select-option on the webform.

when i use the data-selector data:newsletter-value or data:newsletter-key for parmeter, it is refused.

You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:newsletter-value-raw] (assuming newsletter is the form component containing your select-option) and with a data type which equals the data type of your Webform component. In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).
Use the Conditional Rules module to perform a data comparison. In this case to check the value of your select-option. If so, and only then, perform your Rules Action to add the email address as a subscriber.

PS: Instead of using the Conditional Rules module, you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


Translate hard-coded strings with source language other than english I building a custom module for a multi-language Drupal 7 site where the default language is not english. Now I want to translate the module. Since my source strings are not in english I cannot use t().

The i18n module provides a i18n_string() function which would seem to do the job but I can't find my strings under admin/config/regional/translate/translate? I even implemented hook_i18n_string_info() to define my own textgroup, which shows up, but the strings don't!

What am I missing? Or is there a better way to translate strings that are in an other language than english?

We also have a lot of sites with a primary language which is not english.

After several different approaches we opted to write all user exposed string in our modules in english and translate them with the t() function.

We then use a crawler like wget to crawl the whole site (to get all strings into the translation database).

We enable the module Translation template extractor (https://www.drupal.org/project/potx)  and export all strings from our module with this module in our languages.

The resulting language-files are edited and translations are added.

This file is then put in a "translations" subfolder in our module file with a *.po extension.

Uninstall and reinstall the module to activate the translations for your languages.

It may sound like a lot of work, because it is, but this is the only method that actually worked for us.


Taxonomy drag and drop for only 2 levels I've created a vocabulary, I can add terms but I want to "configure" this taxonomy to add terms with only 2 levels.

I'm talking about the default table that show my vocabulary terms (drag and drop system). How can I make it set only a term and sub-terms (disable sub-sub-...-subterms)?

I've tested the select module but as long as I can add multiple hierarchic terms, the select module add them as well, so it's not the solution

Thank you all

The theme function theme_taxonomy_overview_terms() drives the taxonomy overview table you're describing. The Drupal API function drupal_add_tabledrag() has an 8th parameter $limit that specifies the maximum depth of hierarchy. If it's set to 1, it will do what you describe.

In your theme, you can override theme_taxonomy_overview_terms() so the $limit is to 1. In order to do this.

Copy theme_taxonomy_overview_terms() to your theme's template.php.
Rename the function to MYTHEME_taxonomy_overview_terms in your template.php.
Alter the line drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE); so that the 8th parameter is 1 (i.e. change it to drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE, 1); )
Flush your theme cache to pickup the updated taxonomy overview page.


Flag module not joining flagging with EntityFieldQuery? I'm using EntityFieldQuery to pull nodes based on a flag created with the Flag module (3.2):

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    ->range(0, 25)
    ->addTag('flagging_flag_names')
    ->addMetaData('flag_name_value', 'my_flag_name');

I'm not seeing the flagging table being joined to the query (from the error being thrown):

Unknown column 'flagging.fid' in 'on clause':
SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, 'node' AS entity_type FROM node node INNER JOIN flag f ON flagging.fid = f.fid WHERE (node.status = 1) AND (node.type = 'article') AND (f.name = 'my_flag_name') LIMIT 25 OFFSET 0

Below is the flag_query_flagging_flag_names_alter from the flag module file:

function flag_query_flagging_flag_names_alter(QueryAlterableInterface $query) {
  // Get value and operator for bundle condition from meta data.
  $value = $query->getMetaData('flag_name_value');
  $operator = $query->getMetaData('flag_name_operator');
  // Join [flag] and [flagging] tables by [fid] and
  // apply bundle condition on [flag].[name] field.
  $query->join('flag', 'f', 'flagging.fid = f.fid');
  $query->condition('f.name', $value, $operator);
}

What am I missing in the query build to join the flagging table?

The flagging table is not available when querying for nodes using an EntityFieldQuery, that's why the flagging.fid column is missing in this query.

In order to get hold of flaged items, the flagging-entities need to be queried instead:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'flagging')
  ->entityCondition('bundle', 'name_of_some_flag');

Then use entity_load('flagging', ...) and obtain the nid from the entity_id-property of the flagging entities.

However keep in mind that it is impossible to sort / filter on properties of the target object (nodes in this case) because EntityFieldQuery does not support JOINs in Drupal 7.

I suggest to build a view instead of trying to battle the EFQ in this particular case.


How can I center a logo image in an Omega theme? I'm using Omega (a subtheme obviously) and am having trouble centering my logo image. I tried adding a .logo-img CSS class to my global.css file but it isn't doing anything. I added the following, but results are weird:

margin-left: auto;
margin-right: auto;
border: 4px solid;

I added the border to see the image field because when I save these settings, the image stays on the left, but the border extends all the way to the right.

So those settings end up in the logo image resulting like this: http://i.imgur.com/1r8Bccc.jpg?1 (sorry I can't post images)

If I comment out the margin lines in the css file, the image stays the same.

I honestly don't know how to fix this. Is there a way to do this within my theme's settings? I can't find anything online or in the documentation.

By default the Omega theme CSS floats the image within branding left. You'll have to set it to float none.


How can I get the taxonomy title from its machine name? (drupal 7) I am trying to get the taxonomy name which I already got its machine name.
The content type "manage field" looks like following image:

Right now, I already got the value "field_application_type." How can I get the lable "application type"(in the red circle) for this machine name(in the blue circle)?

The correct way to obtain a Label of a taxonomy vocabulary would be something like this:

$vocabulary = taxonomy_vocabulary_machine_name_load('machine_name');
echo check_plain($vocabulary->name);

However, looking at your screenshot, I guess you actually want to have the field Label of the taxonomy reference field.

In that case your question is a duplicate of How do I get a field label by the field name?


How to make user IDs start on 5000? On our Drupal 7 social network site, we want the user ID (user number) to start from 5000.
What is the easiest way to do it?

One could modify the auto increment field of the users table in the database. Similar to https://stackoverflow.com/questions/970597/change-auto-increment-starting-number.

ALTER TABLE users AUTO_INCREMENT = 5000;


How do I grab multiple commits from a different release branch? I am currently a maintain a module on Drupal.org. I had high hopes of working on a 8.x release, however I ran out of time and made extra commits in the 7.x-2.x branch.  Now my git repository looks like something below:

  7.x-2.x     x - x - x - x - x - x - x
                       \
  8.x-1.x               x

How do bring 8.x-1.x up to speed with the 7.x-2.x.  What commands do I need to run.  I thought I would ask the question here as Drupal.org is a little bit unique in how it organizes its repositories.

A normal merge should work fine. It shouldn't remove the merged branch. If it does, you can always recreate the branch.

If you want to take just some of the commits, use "git cherry-pick".


Flash HTML markup in views = No output I want to display a Flash file from a view. I have a content type with a file field that I use to create a node and submit a Flash file (.swf).

Then I use a view to create a block showing the content of these content type nodes. I get the Flash files URL and use the code below to print it - but, no Flash is printed!

Why doesnt this work? It's HTML, isn't it? And Views should support it?

<embed id="[title]" width="190" height="285" wmode="transparent" loop="true" scale="noscale" allowscriptaccess="sameDomain" quality="high" bgcolor="#FFFFFF" name="[title]" src="[field_ad_flash]" type="application/x-shockwave-flash">

This is how I resolved this issue:

I set up my view to only print the URL of the flash file.
THen I created a views template for that specific field.
In that template file i added the HTML above and printed the output - which is the flash files path - as src.
Done!


How to use tokens in data selectors in Rules and how to get autocomplete to work? In Drupal 7, the Rules module was quite simple to use. You create a rule, define it's action and done. In Drupal 8 version of Rules however, i.e the alfa1 version (which is what I'm using), I see some weird behavior.

I am not able to use tokens in data selectors (also autocomplete won't work).

What I want to accomplish:
I have two roles: admin and non-admin.

When a user assigned with the role as admin log in, he should be redirected to his dashboard (url: /admin/dashboard)
When a user assigned with the role of non-admin, he should be redirected to his particular page (url: /non-admin/dashboard)

There are 2 Rules Conditions related to User Roles:

one is under "Others" tab (= User Role).
one is under "User" tab (= User has role(s)).

Both are shown in the image below:

When I choose the 2nd one, I always get an php error (issue already posted on Rules on that).

When I choose the 1st one, no matter what I pass in the Rules Condition, it always returns true and performs the Rules Action.

Am I missing something?

Note: This is not an accurate answer of this problem, as by this time, the Rules module is still in development. This is what I did to solve my problem:

Download PHP Module, as it is removed from Drupal core and is a contrib module now. In Rules, create a new condition known as "PHP execute" and write a php segment which checks user role.

This is probably the easiest way around this problem and will work fine if you are trying to fiddle around. But for production site, I won't recommend this.


duplicate entry for username I am creating a user account programmatically with the following code.

$fields = array(
  'name' => $first_name,
  'mail' => $mail,
  'pass' => $password,
  'status' => 1,
  'init' => $mail,
);

$account = user_save('', $fields);

When I am trying with same name again, it throws an error, but by default it updates the name.

How do I update the name if already exist?

Something very simple like this, using user_load_by_name(), would be an option:

$original_username = $username = 'something';
$count = 1;
while (user_load_by_name($username)) {
  $username = $original_username . $count++;
}

$fields = array(
  'name' => $username,
  ...

That will keep on trying 'something', 'something1', 'something2', 'something3', etc. until it finds a unique name.


How to find the entity specific named id? How do I map entity type to the entity specific named id, like this:

node => nid
taxonomy_term => tid
comment => cid

so that I can turn code like

 $entity->nid

into something like

$entity->{$label}

and correctly handle non-node entities.

This should do it (definitely works for all core entities, I don't have any custom entities to play with on my sandbox site I'm afraid):

$type = 'taxonomy_term';

// Get the entity type info
$info = entity_get_info($type);

// Grab the id key
$key = $info['entity keys']['id'];

// $key contains 'tid'

I'm pretty positive this will work across any entity type though, according to hook_entity_info() the id property of entity keys is required:

  Every entity object passed to the Field API must have this property and its value must be numeric.


How do I add a view with a module when installing a module? In Drupal 8, I want a view to be created when a module is installed.

I have already used the Features module to export the view, so I have the yml file that creates the view. I can't find what to include in order for this view to be created on installation of my module.

How can I achieve this?

If you have the YAML file, you can put this in: /modules/your_module/config/install.

Then the View will be imported, when the module is installed (but there will be no updates, if you change the YAML file, it will only be imported once).

Btw. to export the YAML file you don't need Features, you can do this with core (admin/config/development/configuration/single/export).

So you can remove the line uuid: from the YAML file, this is only valid for re-importing the YAML to the same or a cloned site.


Move title below image in Views grid format with CSS I'm trying to customize a View that I've created showing all of one published content type. The grid is set to have 3 columns. I also have it set as a Rendered Entity with view mode "Teaser" so that it displays the image and content.

Using CSS I've been able to modify the header size, hide the words in the teaser while leaving the image, and modifying the size of the teaser image.

I'd like to be able to display the title underneath the image rather than on top, as is the default. There is no setting in the Views module to achieve this that I can find, so I'm doing some modifications using CSS. I'm having some trouble figuring out which divs to use to do so (there seem to be quite a lot that don't move around so easily). The divs are currently positioned like so:

I did find that assigning display: table-header-group and display: table-footer-group to the images (l-slat__media) and header text (l-slat__header) respectively worked, after assigning display: table to article. But they were tiny and about 25% of the original size. Not really sure why this is happening.

Any input as to what I might be able to do to put the header text below the teaser image would be appreciated.

You could simply edit the "Teaser" view mode and place the title below the image using Display Suite Here are the instructions:

Download Display Suite and enable the "Display Suite" and "Display Suite UI" modules.
Go to admin/structure/types/manage/article/display/teaser where "article" is your content type.
In the "Layout for article in teaser" fieldset, select the "One column" layout and click Save.

You will now see a lot more fields, provided by the Display Suite module. One of those fields is the title field.

Now drag the title field up to the top, below the Image field, just like you requested. From what I understand from your question, you could remove the Body field as well.

All done! No custom theming required.


Twig templates not inheriting I have a parent theme with templates defined in a directory called templates. Within that folder, I have directories like base (page, html, block etc twig templates), views, and menu folder.

My subtheme, which is based on the parent, will not load these templates even though base_theme is set in the .info.yml file.

What am I missing? If I copy the templates into the subtheme, they begin to work.

Annnnd after asking I read my question and realized my answer. The key base_theme is not one word, it's two.


Colorbox + jCarousel + slideshow + compact mode? I'm looking for a good solution (preferably as one integrated module) that would allow to display images in a multi-value image field in any kind of a lightbox, have a compact mode so that only the first image is shown, display a carousel beneath, and provide slideshow.

I've tried: Colorbox, Field Slideshow, jCarousel, Shadowbox.

Colorbox was nicely integrated with Field Slideshow and provided a pager, but it had a strange bug which causes certain images on the main page beneath to be cloned upon every click within the Colorbox layer. Shadows wins over it even though is paid. Colorbox does not have a compact mode - if I set explicitly number of images to show to 1, all remaining images become unavailable and the slideshow is automatically disabled, otherwise, all of them appear on the node.

A while ago I gave also a try to Lightbox2, but I gave up on it, being unsuccessful at enabling its compact mode.

You basically want to output the images inside an HTML list, using, say views, and then install a jQuery plugin to do the slideshow for you.

You can use an existing module, however we often find it's easier to just install the jQuery plugin, and initialise your slideshow yourself.

Assuming your view outputs an HTML list, which is pretty easy to get set up, the rest isn't so much a Drupal question as it is a case of following the instructions for the exact slideshow plugin you're using.

We quite like http://jquery.malsup.com/cycle/ which has all the usual options, good documentation, and works well in a lot of different ways.


file or image migrate from drupal 6 to drupal 7 using Migrate D2D module? I am using migrate_d2d module to migrate my Drupal 6 website to Drupal 7, I succeed to transfer every thing except for images.

I read the new documentation sever times and I managed to migrate the files into the file_managed but I cant link them with the nodes any hints or examples will be greatly appreciated

In your migrate register function define the files table migration.

/**
 * Migrate files table
 */
// The description and the migration machine name are also required arguments,
// which will be unique for each migration you register.
$file_arguments = $common_arguments + array(
  'description' => t('Migration of files from Drupal 6'),
  'machine_name' => 'Files',
  'source_dir' => '/var/www/drupal6/files/xxxx/',
);

// We just use the migrate_d2d D6 migration class as-is.
Migration::registerMigration('DrupalFile6Migration', $file_arguments['machine_name'],
$file_arguments);

Then in your node migration class set the files migration as the source.

// Map the image field to the new image field, base this on the Files migration
// to map the files to the imported files table.
$this->addFieldMapping('field_image', 'field_image')
  ->sourceMigration('Files');
$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');

Hope that helps


Adding multiple links to the same table cell I am struggling to add multiple links to the same table cell, my current code looks like:

use Drupal\Core\Link;

$row[] = [
  'data' => Link::createFromRoute(...),
  'class' => 'middle',
];
$row[] = [
  'data' => Link::createFromRoute(...),
  'class' => 'middle',
];
$rows[] = ['data' => $row, 'no_striping' => TRUE];

return [
  '#theme' => 'table',
  '#header' => [..],
  '#rows' => $rows,
];

I've cut down the code to the relevant parts each element of the $row variable is a new cell and each element of the $rows variable is a new row. I need to use the data attribute as I have additional attributes on the cell.

At present this works perfectly fine, but my links are rendered in separate cells and I would like them rendered in the same cell. If I just to concatenate the 2 Link::createFromRoute I get the following error:

Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string

I've tried using the toString() and the toRenderable() functions and neither work as I want. Surely it can't be that hard?

I think you can do it as Clive alluded to with render array:

  $link_1 = Link::createFromRoute('Link 1', 'route_1')->toString();
  $link_2 = Link::createFromRoute('Link 2', 'route_2')->toString();
  $link_concat = ['#markup' => $link_1 . ' - ' . $link_2];

  $header = [ ... ];
  $row = [];
  $row[] = [
    'data' => \Drupal::service('renderer')->render($link_concat),
    'class' => 'middle',
  ];
return [
  '#theme' => 'table',
  '#header' => [..],
  '#rows' => $row,
];

This is just one method of doing it, there are a lot of ways you could potentially work this scenario. This way just puts the two links with a dash in between. But hopefully this will help guide you towards a solution.


A gallery display formatter for Media I'm using Media, version 7.X, and I'm looking for a module that creates a display widget as a gallery for a "file" field.

I'v tried Media Gallery but I can't use "dev" versions.

Any suggestion?

Create Block using views module and show in sidebar.


drupal_add_js(), script not executed I try to include a simple script (below) and cant get it to work.

(function ($) {
  Drupal.behaviors.myModuleBehavior = function (context) {
    alert('say something pretty please');
  }
})(jQuery);

The script is added within a hook_form_alter function

drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module_form.js', 'file');

Up to here, no issues. I see the script is added to the long line of js:extends with the correct path. Thus I would expect to receive an alert... but nothing happens.

As I've run out of things to check for and consulted docs, google and this site, only to find that the code should work, is anyone able to point out what might be wrong here?

I believe the = function (context) bit needs to include the attach:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      alert('say something pretty please');
    }
  };
})(jQuery);


dissecting the og module - where is the content type form submit handler for function og_ui_form_node_type_form_alter? drupal version: 7

Hi, I'm trying to add settings to a content type form and I'm using organic groups as a guide. I see the form elements for OG being added in the og_ui.module at line 316 in this function og_ui_form_node_type_form_alter but I don't see where these form elements are being submitted, handled, saved, processed... I would've expected it to add another submit handler to the form but it doesn't seem to be the case. Anyone have any experience with this?

This happens automatically.

Adding a variable to that form means that it is automatically saved with variable_set() with a _node_type suffix. Similar to admin forms.

Here is another example: userpoints_nc_visits_form_node_type_form_alter().

As you can see, the form element is for example named userpoints_nc_visits_points and the default value is fetched with userpoints_nc_visits_points_type (inside the get setting api function).


How to count the number of posts by a author? I have created a view with table settings. I would like to display the name of the author and the total number of posts that he has created. I have used relations to get the author name but I don't see any fields related to count the number of posts.

Any suggestions?

If you are using D7 I think you will have to enable aggregation for you view, and then set the group by for you field (Content:nid for example) to Count.


drush status only showing drush info, not drupal info I have drush installed globally on my VPS (thanks to a previously answered question on here :D), logging in as root all works fine, but using a different user (let's call it drushuser) if I run:

drush @mysite st

I just get the drush version etc, not the drupal info.
I assume this is down to the 'root' path in my alias:

'root' => '/home/accountname/public_html',

so logged in as root on the VPS that works - but what should I change it to for drushuser? I'm guessing drush is currently looking in /home/drushuser/home/accountname/public_html and not finding drupal (since it doesn't exist there) so just giving the drush info instead?

I've tried '../accountname/public_html' which didn't work.

If the drushuser account doesn't have read permission to the directory, it won't be able to run and bootstrap Drupal to get information, so it falls back to displaying the status it can which is Drush status.

If drushuser isn't the same as accountname above, it's very unlikely that drushuser will have access to the home directory of accountname. The root user can read files in every directory, so that is probably why it works as root.

You should be able to run drush as accountname or if you can put the public_html files into a shared location and make sure that the permissions are set so that both users share a group that has read access.


How to positioning a field before another specific field with hook_form_alter() I'm modifying a form by adding another text input, and I need to add this input right before a field. How do i do it? this is my code and it's working correctly:

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

    $form['input_latitude'] = array(
      '#type' => 'textfield',
      '#title' => t('Search address'),
      '#default_value' => '',
      '#prefix' => '
Mappa qui
',
    );

}

I just need to position this before $form['field_latitude'].

Set the weight property of your required lower than other.

$form['field_latitude']['#weight'] = 0;
$form['input_latitude']['#weight'] = -10;

or
function provintegra_form_alter(&$form, &$form_state, $form_id) {

$form['input_latitude'] = array(
  '#type' => 'textfield',
  '#title' => t('Search address'),
  '#default_value' => '',
  '#prefix' => '
Mappa qui
',
  '#weight' => -10,
);

}


How do I overwrite the text value? I want to overwrite the $link['text'] value in theme('rate_button', $link['text'], $link['href'], 'rate-btn'), a theme function defined from the Rate module, under a specific content type in template.php. Is there a way to get that? How can I do that?

function rate_preprocess_rate_widget(&$variables) {
  extract($variables);

  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', $link['text'], $link['href'], 'rate-btn');
    $buttons[] = $button;
  }
  $variables['buttons'] = $buttons;

  $info = array();
  if ($mode == RATE_CLOSED) {
    $info[] = t('Voting is closed.');
  }
  if ($mode != RATE_COMPACT && $mode != RATE_COMPACT_DISABLED) {
    if ($results['user_vote']) {
      $info[] = t('You voted \'@option\'.', array('@option' => t($results['user_vote'])));
    }
  }
  $variables['info'] = implode(' ', $info);
}

This is the code of theme_rate_button().

function theme_rate_button($text, $href, $class = NULL) {
  static $id = 0;
  $id++;

  $classes = 'rate-button';
  if ($class) {
    $classes .= ' ' . $class;
  }
  if (empty($href)) {
    // Widget is disabled or closed.
    return
      '' .
      check_plain($text) .
      '';
  }
  else {
    return
      '' .
      check_plain($text) .
      '';
  }
}

The reason I am asking is that I have installed the rate module, and created the emotion vote (only one), which is used in two content types ("story", and "company"). In the "story" content type, the vote button should show two buttons labelled "best" and "bad," but in the "company" content type I want to set the buttons to "up" and "down."

The local variable $links used in rate_preprocess_rate_widget() contain the data for two buttons, of which I want to change the label basing on the content type of the node where those buttons appear.

You will need to implement mytheme_preprocess_rate_widget() and write your own version.

Notice how $variables['buttons'] is set halfway down the function in the original question. Since preprocess functions for a particular theme ALL get run, you can't (that I know of) stop the rate module running its preprocess function, but by re-assigning $variables['buttons'] in your own mytheme_preprocess_rate_widget() function, you will be able to control the output there. I would suggest something like:

function mymodule_preprocess_rate_widget(&$vars) {
  extract($vars);

  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', 'my custom text here', $link['href'], 'rate-btn');
    $buttons[] = $button;
  }
  $vars['buttons'] = $buttons;
}


How to display comments of current node in a view I would like to display comments of the current node in a view. The reason for doing so is that I want the comments to be neatly displayed in a table and views seems to be an easiest way to do so than messing with theme template etc. (I am new to drupal)

I have created a comment view and selected comment: nid as a filter selector. How do I provide the "current NID" as the argument for the filter? I have tried Comment:nid is equal to "current" but this does not work.

Any suggestion?

You need a contextual filter.  In your view, remove comment:nid from the Filter Criteria.

Next, on the far right, under "Advanced", add a "Contextual Filters" and select comment: nid there.

In the configuration options, under WHEN THE FILTER IS NOT AVAILABLE, select "Provide Default Value".  From the Type dropdown, select "Content ID from URL".

Click Apply, save your view, and add the block as normal.


How to submit webform programmaticaly? I need to submit data to a webform.

I receive data from POST submission from mobile application ("webservices").

So I try something like :

$form_data = array();
$form_data['values']['firstname'] = $user->field_civilite['und'][0]['tid'];
$form_data['values']['lastname'] = $user->field_prenom['und'][0]['value'];
$form_data['values']['mail'] = $user->field_nom['und'][0]['value'];

webform_client_form_submit(226, $form_data);

But this is don't do anything.

Someone have any idea to do that?

webform can be programatically save, as shown in below example,

  $node = node_load($nid); //nid is the node id of your webform
  global $user;

 //the values to save
  $data = array(
    1 => array('value' => array($first_value)),
    2 => array('value' => array($second_value)),
  );

  $submission = (object) array(
    'nid' => $nid,
    'uid' => $user->uid,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'data' => $data,
  );

  module_load_include('inc', 'webform', 'includes/webform.submissions');
  webform_submission_insert($node, $submission);
  webform_submission_send_mail($node, $submission);


Ubercart Roles: Expire to another role I use Ubercart Roles to manage access to parts of a member site, but I want to be able to keep track of users who's role has expired.

We have generic authenticated users, who are able to make purchases, but are unable to access member pages, and we have a 'member' role, that expires at the end of the year. At role expiration, I would like to have the 'member' role removed and an 'expired' role added. If they renew their membership from 'expired', I would like their role to go back to 'member'.

Is there a module that will help me with this?

Using Ubercart Roles, there is an event defined to trigger on sending the user a notification that their role has expired. You can use that event to trigger a rule, or you can define a role expiration event if you wish to tie it to a discrete event rather than the sending of an email. There is a proposed patch for Role Expire which creates a Rules event upon role expiration that you might use as a model.

Once you have created your rule, it is a simple action to assign a role (Add user role action) to the expiration:user.


Move drupal site from web to local host I have a site that's already on the host.
So what I want to do is to put in on my PC , and so I could edit it.
I have already installed WAMP and download a backup with the site from the host, and downloaded the DB from the host also.

What I have to do next?

Put your project in WAMP's www folder.
Start wamp and make sure both aparche and mySQL is up and running
Go to phpmyadmin http://localhost/phpmyadmin
Create a new database and import your database backup
Go to wamp/www/[your project folder]/sites/default and edit settings.php file.
Set database connection and $baseurl in settings.php file.
Go to http://localhost/[your project folder]


Complete backup solution I'm trying to backup my Drupal website (not only database) as complete as possible, because It's in the desired state. The backup should cover actual versions of all modules, themes, database tables, settings, just everything.
Now my method is to zip everything under /var/www/ folder and backup the database with Backup migrate module.
The restore process is

delete everything in /var/www
drop database and create it again and set permissions on it
unzip my backup to /var/www
restore with Backup migrate module

Will this method work? Do you know smarter method to make a complete Drupal web backup?

Will this work?
Yes
Is there a smarter method?
Drush + drush make
Drush is a command line tool that you can use for various things, one of them is to create a site. With a drush make file, you can save all of the modules you use (including version and even patches applied to them if needed). Once create you could recreate all of the modules by doing something like this:
drush make --no-core --contrib-destination=[path to the contrib folder like sites/all] [path to the make file]

You can read more about drush and drush make which has documentation about usage.
Also backup and migrate will or can add a drop syntax, so that it automatically drops tables when restoring the database. So using it, you wont need to wipe out your database completely. If need be, you can truncate it so you wont have to setup permissions again.


Is it even possible to export webform form snippets? Say I've built a small contact-form with the famous module Webform and I want to paste it in node.tpl.php (or node.twig.yml in Drupal 8) and then customize it's code manually and more easily. Can I export a ready to work HTML-PHP code from the Drupal UI somehow?

The answer is no. This is not the way Drupal theming and form building works. One of the main reasons would be that default Drupal hooks and theme functions will not work consistently if you can get a snapshot of a template, export it and change to your liking.

Let's take an example:

You create a webform with several fields.
Through this fictive module, you get the output which you can use in template files.
You use the code where you want.

The following will not work:

hook_form_alter() implementations. Fields added through dynamic conditions will not be there as well as custom CSS/JS.
Theming overrides will not work as well; say that your theme changes the way textarea elements are rendered. By exporting the form, you get the snapshot; if there is any dynamic condition, it won't work because the system cannot alter the markup anymore.

Solving the above problems would end up in a real mess, and I think this is just a tip of the iceberg.


Using twig, how to show a message on the frontend if a field is empty? Using twig, I would like to show a message on the frontend if a field is empty. My question refers to a date field, but I think this question could apply to other field types.
In my event content type I have smart_date field with unlimited cardinality. I do not want to make this a required field, but if the field is empty I want to show a message to visitors. Something like 'No dates are currently scheduled'.
I have created a template file called field--smartdate.html.twig and into this I have pasted the content of field.html.twig my base theme (Bootstrap). Copied below.
  {%
    set classes = [
      'field',
      'field--name-' ~ field_name|clean_class,
      'field--type-' ~ field_type|clean_class,
      'field--label-' ~ label_display,
    ]
  %}
  {%
    set title_classes = [
      'field--label',
      label_display == 'visually_hidden' ? 'sr-only',
    ]
  %}

  {% if label_hidden %}
    {% if multiple %}

        {% for item in items %}

{{ item.content }}

        {% endfor %}

    {% else %}
      {% for item in items %}

{{ item.content }}

      {% endfor %}
    {% endif %}
  {% else %}

{{ label }}

      {% if multiple %}

      {% endif %}
      {% for item in items %}

{{ item.content }}

      {% endfor %}
      {% if multiple %}

      {% endif %}

  {% endif %}

I have read Checking for empty fields in Twig templates is complicated And, yes it does seem complicated and I am still unsure what to do.
I have also tried the Empty Fields module but I am hoping this can be done via the theme.
So what changes must I make to the code to display a message if the field is empty?

The fact that you are in the field template is proof for a non-empty field. So you need code outside of the field template to show a message. This can be PHP like the module you've linked or TWIG in a different template.
For example:
node.html.twig
{% if node.field_example.isempty %}

Field is empty

{% endif %}


Stop footer from reloading I have a background audio module running on a site I am building. (I know WHY? but the client wanted it).  Anyway I need to know if it is possible to stop the footer from reloading every time they click to another page on the site because the song starts over.

Pre-HTML5 way

Sorry no, it is not easy nor stable. Footer is a part of HTML structure, and HTML is send with each request. You would need to remake a lot of Drupal to make it's navigation AJAX based to leave footer in place and reload just changes. I did it, once.

First problem is - if you change anything before #, browser will reload, it's mandatory. So you would need to send HTTP 204 No Content and hope user's browser really understands it. Then, JavaScript would need to detect answer like that, generate proper AJAX query. Or you could use js to insert # into every link and then send AJAX.

Either way, in PHP you would need to be able to serve stripped version of HTML structure. I did it by appending ?ajax=true and in theme stripping everything before and after my #main-container and sending only it's content. Of course if you use "# way", you cannot just paste content. You need to treat links inside.

Long story short, it was complicated, dirty, and worked like a magic. But worked all right.

HTML 5 way

Use <audio> tag like this:

<audio autoplay loop>
  <source src="ambient.mp3">
</audio>

And let the browser care.


What module is used to create the table of contents in Drupal documentation? I want to create a table of contents for sections of my site like Drupal.org has for their documentation. For example on this page, there is the "Table of Contents" block on the right hand side. What module is used to do this?

That block is the "Book navigation" block implemented by the Book module in book_block_view(), and defined in book_block_info().

The copyright block that appears right after the "Book navigation" block is implemented in drupalorg_handbook.module, which is a custom module used to run Drupal.org, and its sub-domains.


How to generate a downloadable CSV file from a View table? Is there any way to generate a downloadable CSV file from a View table?
If not, how can I generate a CSV file in Drupal 7?

You can create/export CSV files from Views in Drupal 7 with the Views Data Export module.  The module is currently in Beta.


Omega 4: manually installing a subtheme Just learning Omega 3 and 4 is out so I'm switching to try it out, but.. how does one install a subtheme manually? My drush is whacked and I already running multiple installs so I just want to do it manually.

However, copying the "default" folder to the sites/all/themes/ folder... there is no info file... so I duped the one in Omega, changed the name and it shows in the Appearance menu. However, the name isn't correct and I've gone through the few files to see what to change to my themes name but there was only one file.

So, I enabled one, it enables, but then when I click "Settings" next to that theme, I get the WSOD.

Seems not to be the same process as in D6 or even Omega 3. Anyone installed a subtheme of Omega 4 yet manually?

go the omega theme folder omega\starterkits select : default or extended folder and copy in site/all/themes .
change folder name default or extended to your subtheme name for example "alex".

go to your theme folder finde the extended.starterkit.inc or default.starterkit.inc and change to your theme name in my case is: alex.info

open alex.info and change name and description of your subtheme.


list links to nodes in another node with Views I'm currently struggling with the following scenario:

There are two different Content Types:

Offer
Event

What I want to achieve is this:

There are 6 offers and each of those offers have several events that are nodes as well, in those event nodes there's a field for the date when the event takes place.
For example: one of the offers is a photography workshop and I want a section in this node where the dates of the events (as a link to the event node) are listed.

I was thinking about creating a taxonomy with all the offers, whenever a event is created you have to select one of the tags.
In a second step I thought Views would be a good way to create this list of all the event dates to a specific offer by showing Content of type Event but I don't know where to go from there because I can't specifiy that it should only show the events with a specific tag.

EDIT

Alright I think I'm a bit closer to the solution, but I'd still need some assistance from you guys.

What I did:
Besides Views, I installed EVA.
Created a View that is neither a Page nor a Block with the following settings:

Fields
– Filter Criteria
–– Content: Type (=Event)

Added an Entity Content with the following settings:

Entity content settings
– Entity type: Node
– Bundles: Offer

Not sure where to go from there though. Can I add some kind of Contextual Filters or Relationships between the Offer and the Events?

Assuming the offer node holds a reference to the event node, this can easily be done without any custom modules.

Create a view with content type = offer.
Create a relationship to the event using 'A bridge to the Content entity that is referenced via', not 'A bridge to the Content entity that is referencing Content via'.
Add the date field into the field and use the relationship.

So for example, if it's a table view and you have one offer and two events, you should have two rows. offer 1 and event 1 date, and offer 1 and event 2 date. If you want them combined into offer 1 and event 1 date + event 2 date, then you can combine them using views distinct filter.


Wrapping multiple cck fields into a single div tag for theming? I have a content type that uses many cck fields, and I would like to theme the content type by grouping certain fields in "blocks" (not Drupal blocks but div blocks), preferably div tags, so that the fields aren't just displayed one after the other. I can edit the css of individual fields, but if I want a field to be in a div on the top right hand corner of my node types page, and then another group of fields to be along side it, and then another group of fields to fall underneath all of the other fields, that css could get messy and interfere with my themes main css. I'm not sure what to put in my template file, since all the fields just fall under "content."

I'm using Drupal 6, and a little new with php, but can do basic "print" and "if" conditions. Any help would be greatly appreciated! Thanks in advance!

In your node templates, you have access to the $content variable, which includes all of your fields mushed together as CCK et al wants them, but you also have the $node object which includes all the raw information about your node.

So, first thing to do is to put a

<php drupal_set_message('
' . print_r($node, TRUE) . '
'); ?>

at the beginning of your node-TYPE.tpl.php file to see what you have to work with fieldwise.  There you will see lots of information, but basically, it is broken down into stuff like

 field_name[0]['value'] = // raw information stored in the database
 field_name[0]['safe'] =  // the above info in a safe format
 field_name[0]['view'] =  // the above info passed passed through the widget

So.  If you want to put some of the fields in one
 and some in another you can do something like

   <?php print $node->field_name[0]['view']; ?>
   <?php print $node->another_one[0]['view']; ?>

   <?php print $node->yet_another[0]['view']; ?>
   <?php print $node->one_more[0]['view']; ?>

Now, of course, you probably don't want to create everything yourself, so you then add

 <?php print $content; ?>

but lo and behold, you get the fields you printed manually in there as well.  To get rid of that duplication, go into your content edit screens and in the Display Page (admin/content/node-type/NODETYPE/display) just exclude them from $content in your teaser and/or full node display) and they should be displayed just once now in your custom
s.

When all is working, take out that drupal_set_message() so you don't totally confuse your users :)


Permissions/access caching per node and per user UPDATE: Narrowing this a bit. I need to, for either (a) all nodes of a given type or (b) all nodes on a specified list of node id's or (c) all users on a list of iser id's, clear the cached permissions because, due to changes not necessarily made on a given node, a user's access permission may have changed.

I have built and published a module (Access by Reference) that grants update access to nodes based on edit permissions on nodes referenced in the target node.

I am concerned that the module will not work as intended if permissions cache interferes with recognizing changes made elsewhere (eg, rights to the referenced node are changed)

What I would like to do is clear permissions caches relating to particular nodes and/or particular users or roles.  I've been studying the Cache Contexts for several days but the light bulb has not yet lit.  I'd appreciate some guidance.

Access results can store cache metadata like cache tags and cache contexts. As a shortcut AccessResult has two specific methods to apply the correct cache metadata. Different membership in roles or a modified role results in a different set of permissions, use cachePerPermissions() to add a cache context for the hashed permissions. The second method is for the cache context of the current user cachePerUser().

If you get field data from a node or user, add addCacheableDependency($node) or addCacheableDependency($user).

See this example from the node module:

core/modules/node/node.module, line 938

function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node
    ->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account
        ->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()
          ->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account
          ->hasPermission('edit own ' . $type . ' content', $account) && $account
          ->id() == $node
          ->getOwnerId())
          ->cachePerPermissions()
          ->cachePerUser()
          ->addCacheableDependency($node);
      }