Leaving first-level tab selected when clicking on a subtab I have a menu like the following defined in mymodule.links.menu.yml:

mymodule.page_memos:
  title: 'List of memos'
  description: 'View list of memos'
  route_name: view.document_list.page_1
  route_parameters: { doctype: 'memo'  }
  menu_name: main
  weight: 100

mymodule.page_letters:
  title: 'List of letters'
  description: 'View list of letters'
  route_name: view.document_list.page_1
  route_parameters: { doctype: 'letter'  }
  menu_name: main
  weight: 200

mymodule.page_notes:
  title: 'List of notes'
  description: 'View list of notes'
  route_name: view.document_list.page_1
  route_parameters: { doctype: 'note'  }
  menu_name: main
  weight: 300

and then a list of tasks defined in mymodule.links.task.yml:

mymodule.document_list:
  title: 'List of documents'
  description: "View full list of documents"
  route_name: view.document_list.page_1
  base_route: view.document_list.page_1
  weight: 10

mymodule.create_doc_by_type:
  title: 'New document'
  description: 'Insert new document'
  route_name: mymodule.create_doc_by_type
  base_route: view.document_list.page_1
  weight: 20

Everything work as expected, with three tabs in the main menu and two tabs in the task (they will soon become more). There is only a small visual glitch: when I click on tabs in the main menu, the last one clicked is correctly marked as active; when I click on tabs on the task menu, only the first one is ever marked as active. I am sure this has to be something really minor, but I really don't know how to search for a solution.

I came back to study this problem further. If I am not mistaken, the active trail is not set from the local task to its parent menu link, even if the first local task is correctly set to the corresponding menu voice. I looked at a few modules and custom solution, and in the end I simply changed a bit my URLs and installed the module menu_trail_by_path, and I got the desired behaviour.


Adding a CDN feature for a new installation: now or later? If you are setting up a Drupal 6 website from scratch, is it important to install a CDN module (or similar service) immediately? Or will adding such a feature be easy to do later on--even with multiple image files or static files already being used on the site domain?

Easy to add later. We usually do it right at the end. =)

To expand, it's easy anyway, but the CDN module makes it even easier:
http://drupal.org/project/cdn

As described on the project page, CDNs work by taking files from your normal Drupal 'files' directory, either on demand or on creation (original pull or file conveyor) and in either case this can be done at the end - you can build your whole site, upload lots of files without it - it will all sort itself out when you hook things up.

The CDN module rewrites file links so you don't have to think about that either. And if you miss any, they'll still be there on your local server, everything will still work, and you can spot them in server logs and work out why they're still being served from local.

So yeh, it's cool. No need to worry about it right away.


Using triggers to add new user to a mailing list I would like the Mailman Integration module to add any new user to a mailing list. I enabled Triggers and created an action in PHP. I then assigned the action to execute when a new user is created. I can not figure out how to get the $user object for this new user though. I can get the object of myself, the logged in user using global $user, but how do I get the new user?

$user = [newly added user];
$mail = $user->mail;
$name = $user->name;
$uid = $user->uid;
$list_name = 'list';
mailman_integration_subscribe($list_name, $mail);
mailman_integration_set_user_option($list_name, $mail, 'fullname', $name);
mailman_integration_insert_users($list_name, $mail, 0, $uid);

I am not sure about how you've configured your environment but have you looked into this module? It appears to extend the rules a little bit.

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


Cant create a taxonamy menu block Steps i followed

Created a vocabulary (V) and added 5 taxonomy terms to it.
Created a new menu (M).
In edit vocabulary (created before), selected Menu M as Menu location from Taxonomy menu
settings.
Hit Save button.

Getting this error

The Taxonomy Menu rebuild process encountered an error.

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=688&op=do StatusText: OK ResponseText:

I don't think this can be answered here. It seems to be a call to Drupals Batch API that fails. But why can't be answered without some debugging and is not in the scope of your question.

Basically you are doing it right. You can try the otherway round and add menu items to you desired menu and than let them point to taxonomy/term/123. This should give you the same result.


maintenance-page--offline template not working I am following this tutorial. https://www.drupal.org/node/195435.
I have created maintenance page and its working with admin configuration site under maintenance setting. I want to create dboffline mode maintenance page. so for that, i have created another tpl "maintenance-page--offline" in same directory where "maintenance-page.tpl.php" has created. Path is like sites/all/theme/mytheme/templates/.

previously it was working but currently its showing me Additional uncaught exception thrown while handling exception. error. Its not overriding maintenance-page--offline when i am disconnecting DB, by entering wrong password in settings.php file.

This is caused when class_exists() is being called from within alpha_get_theme() and autoloading fails. I have a patch that fixes this by wrapping those calls in a try/catch block. I'm not quite sure what should be done in the case of an error though, so I have just done nothing.

See theme Omega issue => https://www.drupal.org/node/1722586

It is working for me, I had the same problem.


Search keys get variable is in subsequent search pages and so search not returning any more results I have a small form that posts the search page. The resultant link is like this:

http://www.example.com/search/node?keys=test

Then subsequent searches don't work, because the form includes the keys variable in the form definition:

<form action="/search/node?keys=test" ...

This means that subsequent searches don't work. How do I fix this?

Another detail - If I type the search page directly into the address bar, i.e. www.example.com/search/node, I get "Your search returned no results" - suggesting it is doing a search just when accessing the page directly. I think this may be related to the issue, but I can't work out why it is occurring.

You don't need to POST to /search/node as all its parameters are retrieve from query parameters. As such, you can make your basic form use the GET method with your keys input field. For example:

<form action="/search/node" method="get">
  <input title="Enter the terms you wish to search for." name="keys" value="" size="15" maxlength="128">
  <input type="submit"value="Search">
</form>

As for the "Your search returned no results" on loading /search/node, that's the default behavior.


Division by zero in theme_image_style_preview after moving to production server Warning: Division by zero in theme_image_style_preview() (line 804 of
  /var/www/html/modules/image/image.admin.inc).

  Warning: array_intersect_key(): Argument #1 is not an array in
  theme_image_style_preview() (line 806 of
  /var/www/html/modules/image/image.admin.inc).

I am receiving the above errors when I view several of the "stock" image styles on my site. I just moved my site from a development server to a production server, and the error does not occur on the development server version. I checked the directory permissions on the production server, and they appear to be consistent with the development server's permissions.

One really strange thing occurs when I view the source on the "preview image" in the admin back-end of one of those styles that has the issue. When I do, it shows the following path being called (which is, of course, not a valid path):

http://mysite.com/sites/default/files/styles/large/public/modules/image/sample.png?cache_bypass=1399676683

The "sites/default/files/styles/large/public/" part seems to be part of the issue, but I am not sure how that got there. All of my custom image styles work fine.

Thanks!

Apparently it is not safe to chmod files to 777.

A preferred way is to chmod files to 644, directories to 755 and set the ownership to the webserver, so the webserver can write files.

Here's a script for Ubuntu:

# Change directory permissions to 755.
find sites/default/files -type d -exec chmod 755 {} +
# Change folder permissions to 644.
find sites/default/files -type f -exec chmod 644 {} +
# Set ownership to webserver.
chown -R www-data:www-data sites/default/files

Learn more on - Recommended directory permissions.


Create and use a custom Account Email Template I am trying to create a new Email Template for the Account object using hook_form_alter. Here is how I create the template:
function my_module_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
    // Adds the Course Link email template to the Account Settings form
    $form['email_course_link'] = [
        '#type' => 'details',
        '#title' => t('Course link'),
        '#description' => t('Edit the course link e-mail messages sent to mobile app users.'),
        '#group' => 'email',
    ];
    $form['email_course_link']['user_mail_course_link_subject'] = [
        '#type' => 'textfield',
        '#title' => t('Subject'),
        '#maxlength' => 180,
    ];
    $form['email_course_link']['user_mail_course_link_body'] = [
        '#type' => 'textarea',
        '#title' => t('Body'),
        '#rows' => 15,
    ];
}

This adds the email template to my Account Settings form, but I am having two issues:

When I go to edit the template and hit save configurations, nothing gets saved. The subject and body edits I made are wiped out and they no longer exist.

When I go to use the template via _user_mail_notify('email_course_link', $user) I get NULL as the response and there are zero errors to be found and I never get the email...

What else am I missing here?

Specifically, your code is modifying the AccountSettingsForm, which is part of the core Drupal "user" module.
If you look at the source code for that form, you will see that like all forms in Drupal, it has both a buildForm() method and a submitForm() method. The problem with your code is that you've added form elements to the form array created by default in buildForm(), but you HAVEN'T added any code to process those new form elements and save the entered data, which is normally done in submitForm(). If you create new form elements in an existing form, you are responsible for processing the input and saving the entered values. Your custom module is the only thing that knows about those new elements, and your custom module is responsible for storing that data.
Let's look at one of the other elements defined in AccountSettingsForm, for example the email_admin_created details element which contains a user_mail_register_admin_created_subject and a user_mail_register_admin_created_body. It looks like you copied this code and changed the names for your own purpose, which is a good way to approach this. But if you search AccountSettingsForm, you will see that those form elements are also processed and saved in submitForm(), and you haven't added any new equivalent code for your new form elements.
The key then is to write your own function to execute on form submit, and in that function you need to save the values entered into your custom form elements. The way to tell Drupal about your custom submit function is to add the following at the end of your hook_form_alter():
$form['actions']['submit']['#submit'][] = 'my_module_email_course_link_submit';

Then add your function to my_module.module:
/**
 * Submit callback to  process and save email_course_link form elements.
 */
function my_module_email_course_link_submit(array $form, FormStateInterface $form_state) {
  $entered_body_value = $form_state->getValue('user_mail_course_link_body');
  $entered_subject_value = $form_state->getValue('user_mail_course_link_subject');

  // Save $entered_body_value and $entered_subject_value somewhere.
  // For example, in a database table created by your module, or
  // in a config object created by your module.
  // Where and how you save it is up to you.
}

You will also have to add use Drupal\Core\Form\FormStateInterface; at the top of my_module.module.
When you look at AccountSettingsForm you will see the user module saves form elements in the user.settings and user.mail configs. DON'T use those configs to store your custom data - define your own custom config if you want to store your own custom data in a configuration object.


SQL left join query using Drupal DB Layer The following (my)?sql query performs a left joins of node table with url_alias table by matching a node with its url alias, and returns rows with the node's title, date created, type, and url-alias:

SELECT n.title, n.created, n.type, ua.alias
FROM node AS n LEFT JOIN url_alias AS ua
ON ua.source = CONCAT('node/', n.nid);

I would like to use the drupal DB Interface to accomplish the same thing. Ideally, I would like to write:

$query = db_select( 'node', 'n' )
  ->fields( 'n', Array('created', 'title', 'type' );
$query->leftJoin( 'url_alias', 'ua', 'ua.source = CONCAT("node/", n.nid)');
$query->addField('ua', 'alias');
$results = $query->execute();

which fails with a PDO exception: "node/" is not a valid column (which is true, but I didn't mean it to be a column, hence the CONCAT):

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node/' in 'on clause': SELECT n.title AS title, n.type AS type, n.created AS created, ua.alias AS alias FROM {node} n LEFT OUTER JOIN {url_alias} ua ON ua.source = CONCAT("node/", n.nid); Array ( ) in _long_and_obscure_named_function() (line 680192318389 of narp.module (it's a large file; I went nuts).)

Rather than feeding the left join query raw into a db_query, is there some way that I can implement the query with db_select and ::leftJoin, etc?

Any help would be much appreciated. (I should add that I am running Drupal 7.x).

I've seen this before, I can't remember why it's this way but you can fix it by swapping out which types of quote you use.

Changing your code to this will fix the problem:

$query = db_select( 'node', 'n' )
  ->fields( 'n', array('created', 'title', 'type'));

// Change wrapping quotes to "" and internal to '' for 3rd arg here
$query->leftJoin( 'url_alias', 'ua', "ua.source = CONCAT('node/', n.nid)");

$query->addField('ua', 'alias');
$results = $query->execute();

It's either a Drupal or PDO issue, as either type of quote works fine when executing directly against the MySQL server.


How is this themed when using views I have a single page template...there are 5 sections, each powered by a view bound to a single content type.

The first section has a dark blue background, the second green, third red, etc...

each section renders it's "rows" differently...first section might have the header as  and the body wrapped as . Ther second might have alternating left and right aligned images.

This visual layout that is so common today is quite difficult to accomplish (if not impossible?) using default drupal template suggestions.

What I have basically had to do is iterate $view->result inside views-view--block.tpl.php and render each section individually this way to achieve the desired effect...

Is there a different/alternative way of themeing views to match the markup provided by someone else?

Not sure if this question is appropriate here (borderline I am sure) however I am not sure where else to ask or look.

Alex

In static markup normally one has row level classes, element level classes and wrapper classes. By looking into those classes add exactly the same classes into your views interface, or override default template and add your markup and then render your block in appropriate region


How to transfer webform submission ID to client side I need to transfer the submission ID to the client side after a webform is submitted. The problem is that after submission the Confirmation page is showed. And how can I attach the current sid to a page? I know how to do it on a node (se below) with Drupal behaviors on a client side JS-script.

Anyone? Or maybe the sid can be transfered to the client side another way?

function mymodule_webform_submission_insert($node, $submission) {
 // $node will give you the node id of your webform
 // $submission will give you the id of your data which you inserted in web form
 $sid = $submission->sid ? $submission->sid : FALSE;
 if($sid){
   $currentSid = array('mymodule' => array('sid' => $sid));
   $node->content['#attached']['js'][] = array(
     'data' => $currentSid,
     'type' => 'setting',
   );
 }
}

You could start by putting the submission id into $_SESSION and add it to Drupal's js settings

drupal_add_js(array('mymodule' => array('webform_id' => $_SESSION['webform_id'])), 'setting');

Then access it on the client side

webform_id = Drupal.settings.mymodule.webform_id


Changing the default imagefield formatter for a node field I am trying to change the default formatter for an imagefield node form field so that it will default to the thumbnail image and not the icon. I have already tried a form alter and that isn't doing a damn bit of good. I have already flushed all the cache. So I was wondering if anyone else knew how to do this.

I am running Drupal 6 by the way. The field in question is using imagecache presets.

Go into the admin for the content type in question and look at the display fields, eg, admin/content/node-type/THISCONTENTTYPE/display and change up the field you want.  You can select any imagecache preset you have defined on your system along with a number of other options.


How to update a node after loadByProperties? I search for a node with field value client id and I need to update values. How do I do that in drupal 8?
I search with the following code

$profileNode = \Drupal::entityTypeManager()
          ->getStorage('node')
          ->loadByProperties(['field_user_id' => $id]);

I get an array in response to this which corresponds to this. How do I update the node value with this?

Assuming you response array will contain one node as suggested by the variable name $profileNode

here is a suggestion to make it :

$profileNode = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(['field_user_id' => $id]);
// Get the node object.
$profileNodeObject = reset($profileNode);
if ($profileNodeObject) {
  // Make the changes we want : per example set the author to user 4.
  $profileNodeObject->setOwnerId(4);
  // Save the changes.
  $profileNodeObject->save();
}


How render first node in views result in different view mode? Currently, I handle it by using context. before calling views_embed_view, I set a variable in context and in node.tpl.php at first result I unset this variable...

is there any better way to handle it?

You could use the Display Suite in combination with Views. This allows you for example to choose a different view mode for each row or alternating view modes or whatever you want.


Display node as a popup window I am new to Drupal. I have a form which adds details of user to my table. I want to display that node in a popup window. How would I do this?

There are a lot of solutions for this kind of stuff. I would do it in the theme layer to have something really light. You can also use the variety of popup modules for this. One simple way to do this, use the Lightbox2 module, checkout this documentation page: http://drupal.org/node/252260


Webform Submission Using Rest API POST method I just created the webform and added fields.

I need to create a Webform Submission Using Rest API POST method. I just installed Rest & Rest UI modules for this.

But when I try to test my API using API tester its showing the error like this :

{"message":"Could not determine entity type bundle: \u0022webform_id\u0022 field is missing."}

But I have already determined the webform_id and here is my configuration

POST URL : http://example.com/entity/webform_submission?_format=json

Headers :

Content-Type : application/json

POST Data :

{
  "type": {
      "webform_id": "my_form"
    },
"your_mobile":[{"value":"123456789"}],
"your_name":[{"value":"Test"}],
"your_email":[{"value":"test@gmail.com"}]
}

Drupal Version : 8.6.4
Webform Module version : 8.x-5.1

Can anyone let me know Why its not working?

Looking at the examples on the Webform REST project page, you should be using something like…

{
  "webform_id": "my_webform",
  "checkboxes_field": [
    "Option 3",
    "Option 5"
   ],
   "integer_field": 3,
   "radio_field": "Mail",
   "email": "myemail@mydomain.com.au"
}


How can I support product prices which have a precision greater than the currency's minor unit in Drupal Commerce? Any idea how to support prices which have more decimal places than a currency supports in Drupal Commerce?

Use case is that I'm trying to build a website which has some very small parts, whose unit price can have factions of cents ie a small bearing which has a unit price of $0.05742.

Typical users would order 1000s at a time and price is rounded to nearest cent at payment time.

But a commerce_price (in USD) only supports 'whole' cents (to reflect the minor unit format). Entering 0.05472 in the price field causes rounding to 0.05 and this rounded value is also the value written out to the db.

Any suggestions?

Thanks

Commerce allows to define the amount of decimals per currency in hook_commerce_currency_info, defaulting to 2. So you could implement hook_commerce_currency_info_alter and change that for USD.

However, due to the way prices are stored (with decimals set to 2, $5.00 is stored as 500), this will affect all existing prices, so when you change it e.g to 4 decimals, then $5.00 will now just be $0.05.

So, maybe you could instead set up a virtual currency with the same name and as many decimals as you want and then let Commerce automatically handle the conversion to USD during payment.


how drupal decide execution order of same hook in different modules? if there is two modules A and B and both have same user_login hook. so when i log in. out of A_user_login() and B_user_login() function which one called first.and how drupal decide
execution order of these two function

Hooks are called in order of

Weight, which is defined per module in the database as {system.weight}.  Lower weights come earlier in the calling process.
Alphabetical, by module name.

By default, modules get assigned a weight of 0, so nearly all hooks in the system run in alphabetical order.  Some modules will adjust this in their install hooks so they run earlier or later in the module_invoke_all function.

See also: Adjusting module weight: what are the risks and things to look out for?


How to display node in view and allow users add comment? Is it possible to display a node in a view and allow users to add comments to the node?

I have not been able to find a way to do this.

Yes, you can show node in view and also allow users to add comment. See example below:

Create a view normally.
Under Format section, change Show settings to Content
Select the view mode as Full Content and enable Display
Comments. (Check screenshot below)
Click on Apply


Adding an auto-complete field to a custom module form I am trying to add two auto-complete fields to a form I am using to generate two types of reports. What I have going on is that we have interfaced the CometChat chat system with Drupal using a custom module and now the customer wants reports for it. We realized that the best way for the user to narrow the result set is to let them use an auto-complete field for chatrooms by name and instant messages by individual.

Since I will be querying non-Drupal tables in the DB to do so I cannot just use a CCK field and the autocomplete widgets module (unless you know a trick on how to do that). I have never done an auto-complete field before in my life.

I know that I need to create the menu hook page callback, but I am not entirely sure how the JS and pingback should work to best do something like this. Does anyone know how to get started?

I am going over the code for the autocomplete widgets module to learn from it right now. But I would love any help with this.

Thanks!

There's a full example for Drupal 6 here: Textfield that uses autocomplete. The code will probably be useful to people on this site as well so I'll post i here:

The following is based on a module with the name: 'cities'

In your form function:

$form['city'] = array(
  '#type' => 'textfield',
  '#title' => 'City',
  '#maxlength' => 128,
  '#autocomplete_path' => 'cities/autocomplete',
);

In your module file:

function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' => 'Autocomplete for cities',
    'page callback' => '_cities_autocomplete',
    'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
    'type' => MENU_CALLBACK
  );
  return $items;
}

Also in your module file:

function _cities_autocomplete($string) {
  $matches = array();
  //search table `cities` for cities that begin with the letters the user enters in the form
  $result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%')", $string, 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->city] = check_plain($data->city);
  }
  // return for JS
  print drupal_to_js($matches);
  exit();
}


Why is this query failing? I'm using CONCAT in a join. It works well in PHPMyAdmin, but the equivalent Drupal query doesn't work.

$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT( td.name,  "%\" ) AND td.vid = sbc.vid');

This query causes the following error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  '%\' in 'on clause'

However, the following query works fine.

$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT( td.name,  \'%\' ) AND td.vid = sbc.vid');

The only difference between the two queries is the string quotes: In the first one I used double quotes to wrap %; in the second one I used single quotes.

PHPMyAdmin gives me the result whether the % is wrapped with single quotes, or double quotes. (Actually, it should.)

I think there is something I'm missing. I'm just curious to know what it is.

I tried executing a query similar to the one you are showing using an desktop application to connect to the MySQL server running on my computer, and I got the following error:

  You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%\") AND td.vid = n.vid' at line 1

Drupal reported the following error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '%\' in 'on clause': SELECT n.* FROM {node} n INNER JOIN {taxonomy_term_data} td ON n.title LIKE CONCAT( td.name, "%\" ) AND td.vid = n.vid;

The PDO driver seems throwing the wrong exception.

The error is caused from the fact you are escaping the second quote, and there isn't any other quote character, except the one ending the join condition.

If I recall correctly, you should not use the double quotes inside SQL strings. Rewrite the query as following, and it works.

$query->join('taxonomy_term_data', 'td', "sbc.tname LIKE CONCAT(td.name,  '%') AND td.vid = sbc.vid");

I also tried escaping the % character with another %, as suggested by @Clive, but the following still raised the same exception.

$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT(td.name,  "%%\") AND td.vid = sbc.vid');

The following worked too, but the result doesn't change, compared to the first query I wrote.

$query->join('taxonomy_term_data', 'td', "sbc.tname LIKE CONCAT(td.name,  '%%') AND td.vid = sbc.vid");


Node's Preview when using Views module to render Node I have been using Views module to render Node's Full content (using unformatted list of fields!). Seems that was not such a good idea.

Now when I preview the Node, I see the Teaser and Full content Entity view modes (instead a View with fields). So the actual problem is these teasers and Full content are not themed the way my View is.

Is there any workaroud except rebuilding the whole thing in Display Suite module?

THX!

The solution was to rebuild the whole thing in Display Suite module. Views (when using Unformatted List of Fields) cannot render teaser and Full content in node's preview!


How to sort translation under Translate tab? I need to sort these translated language names alphabetically. I want to sort these irrespective of these languages weight and hierarchy. How can I do that?

Have you checked on "admin/config/regional/language"?
There you can sort languages and the order is reflected throughout the system (e.g.: the language switcher block)


Hide the price when stock is 0 Is there a way to hide the price on display of a product when the stock goes to zero?

This explains how I did something similar. You'll just need to adjust your selectors to hide the price as well as the add to cart button...

Step 1 – Create New “Product Status” Field

Go to  Administration > Store settings > Product settings > Variation types and select “Manage Fields” for the variation type you want to modify (I just use the default “Product” variation type for my site). Add a new field called “Product Status” of the type “List (text).” For “Allowed values list,” I entered the following because it occurred to me the client might want similar display-but-don’t-sell functionality for upcoming releases…

soldout|SOLD OUT
comingsoon|COMING SOON
Of course you can just include the sold out line if you prefer. The string before the pipe is the machine name and the part after the pipe is what will display. Save your changes. Now go to “Manage Display” for the product variation type and add the new field for any display types you use for your products. I just use the default and teaser display types on my site. Remember to adjust the label settings (I’m guessing you want “hidden”) and to order the field so it displays relative to other fields as you desire. Save your display changes.

Step 2 – Set Products to Product Status = SOLD OUT

Go to Products > Manage Products and edit your sold out products, setting the new status field to SOLD OUT as appropriate. Note: this is the only step the client will need to do in the future whenever he runs out of a certain product…

Screen Shot 2013-09-24 at 4.59.24 PMSave your changes.

OK – we’ve created a mechanism for indicating when something is sold out, but this doesn’t prevent site visitors from adding sold out items to their carts. Probably nobody would try to put these items in their cart, but you never know. I certainly don’t want my client to have to hassle with issuing PayPal refunds, so I’m going to make sure these products can’t be added to the cart. It seems to me the easiest way to do this is to use jQuery to remove the add-to-cart button for sold out products.

Step 3 – jQuery to Remove Add-to-Cart Button From Sold Out Product Displays

The following jQuery script simply looks for the class that wraps my Product Status (“field-name-field-product-status”): if it finds the class, it removes the Add-to-Cart form for that product. This works because Drupal’s default behavior is to not render the field and its wrapper classes if there is no data to display. In other words, only products I set to “Sold Out” (or “COMING SOON”) will have this field and class. I reiterate this technique because there are two possible display pages for products on my site (full and a teaser view), and each has a different DOM that needs to be traversed differently. You will almost certainly need to adjust my selectors for your particular needs (browser developer tools, firebug or just viewing the page source will guide you)…

/*Script for Gench product pages - removes add-to-cart button/form if product is sold out*/
/*wrap everything in a safety  "no-conflict" function so dollar sign works*/
(function($){
/*wait until page is fully loaded before firing script*/
$(document).ready(function(){
        /*remove add-to-cart button if product has status of sold out - for product display page*/
        $(".field-name-field-product-status").closest("td.views-field").find("form.commerce-add-to-cart").remove();
        /*remove add-to-cart button if product has status of sold out - for product teasers page*/
        $(".field-name-field-product-status").closest("div.content").find("form.commerce-add-to-cart").remove();
    });
})(jQuery);
Because I was already using javascript on my product pages, I just added the above script to the existing script, so I don’t have to do anything additional to call the new script. If you write this as a stand-alone .js file in your sites/all/themes/themename directory, you’ll need to reference the script which can be done globally in your theme’s .info file, or for select content, in your theme’s template.php file. For example…

function genchstyle_preprocess_page(&$variables, $user) {

  if(arg(0) === 'productdisplay' || 'store') {
    drupal_add_js(path_to_theme().'/js/soldout.js');
    $variables['scripts'] = drupal_get_js();
    $scripts = drupal_get_js();
  }
}

Here is what a product looks like when it is in stock (full display)…

And this is what it looks like when it is no longer in stock…

Again, you probably want to go with an actual inventory control module/approach for bigger/busier sites, but this kluge works pretty well for my purposes (and doesn’t preclude adding the Commerce Stock module later should the need arise).

Cheers


unset form error for specific field I have a a kind of conditional field for a sign up form where the user can optionally sign up with a mobile number or an email address.

I'm trying out a custom form validate eg.

  function signup_validate($form, FormStateInterface $form_state) {
    $mobile = $form_state->getValue('field_mobile');
    $email = $form_state->getValue('field_email_address');

    if ($email[0]['value'] != '' || $mobile[0]['value'] != '') {
      $form_state->clearErrors();
    }
  }

Now clearErrors();  obviously clears all errors for the form even if other fields are invalid, I want to know how to clear the error only for field_mobile or field_email_address

While I agree with the accepted answer, one way to accomplish your goal is to:

Assign the form errors to a variable, such as $form_errors
Clear all form errors from $form_state
Remove the particular form error from $form_errors
Loop through the remaining $form_errors, re-setting them to $form_state.

So to clear the field_mobile error you would use the following code:

// Temporarily store all form errors.
$form_errors = $form_state->getErrors();

// Clear the form errors.
$form_state->clearErrors();

// Remove the field_mobile form error.
unset($form_errors['field_mobile']);

// Now loop through and re-apply the remaining form error messages.
foreach ($form_errors as $name => $error_message) {
  $form_state->setErrorByName($name, $error_message);
}


Poll with multilingual choices in Drupal 7 I've installed the poll module in Drupal 7 and I want to have a multilingual poll, so that the choices could be in differents languages and sum the votes of the choices. I've found these posts:

Multi language Poll output

Poll in two languages

The problem is that I'm not able to develop the solution because I don't know where I have to apply the patch since i18n module in drupal 7 doesn't include the i18n_poll subfolder.

Thanks in advance

@chabea you are right in asking the question, the answers given in the links above do not explain how to apply the patch on D7. Here is what you need to do:

Under the i18n module created a i18n_poll folder.
Copy the patch to the above folder.
Run the command patch < 1173130_i18n_poll_module_5.patch. This creats two files i18n_poll.info and i18n_poll.module which are all you need to get the poll aggregate module in D7. (I'm assuming you are using *nix operating system and have already enabled the core poll module) You can checkout how to apply a patch in Drupal.
Then go to the poll content type edit page Structure > Content Types > Poll > Edit. In the publishing options - multilingual support section check the Enable, with translation option.

Now go to the poll content type create page Content > Add Content > Poll and create a new poll.
On the newly create poll page there is a Translate link.

The translation page provides a list of language that the poll can be translated to so click on the language of your choice to start translation.

The translation workflow is quite consistent to other modules/content types. Hope this helps.


What does "Prefetch views unpack data" in APDQC module do? There is an option in the APDQC (Asynchronous Prefetch Database Query Cache)  https://www.drupal.org/project/apdqc module for:

Prefetch views unpack data

It's unclear what this does. Should this be turned on or left off as default?

Really depends on your workload. In some cases having all of the views data prefetched is faster, in other cases it's slower. If you have 50+ views then it's best to leave it off, if you have just a couple views, turning it on is faster.

Side note: I created the patch for creating this cache in views, now I wish it was prefixed by the view name so prefetch would be easier.


Date value to different date format I have a date field. In my template I want to display the date in two different ways. I know in display I can set the format used for a date. To print the date in my template I am doing.

<?php print $node->field_date[0]['view'] ?>

To print as a different format I tried

<?php print format_date($node->field_date[0]['timestamp'],"custom","H:i")?>

However this does not seem to be showing the correct time...

We tend to use:

print format_date(strtotime($node->field_date[0]['value']), 'custom', 'H:i');

Perhaps that would work in your situation?


Views rewrite output for image url add divs So in views , I had created a block display with this fields:

image field : imagecache URL (exclude from display)
image field :    imagecache for resized image (exclude from display)
image field :    data (description) (exclude from display)
global field : rewrite the output with

            [field_galerie_image_vdl_fid_1]

Stripped out all wrapper elements like  , and using a field template with:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?> chocolat-parent" data-chocolat-title="set title">
    <?php print $row; ?>

<?php endforeach; ?>

but in result I get:

           http://caucadis.vmdev/sites/all/media/imagecache/galleryformatter_slide/galerie_images_vdl/2016/22/people-q-c-640-480-4_0.jpg

So what do I missed ?

thanks

Found out, to have unique items for my display


Required regions for a theme Are there a set of required regions for a theme that they must have?

I thought I read this in the documentation at one point, but I can't find it again.

The required regions:

regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom

More on this can be found at http://drupal.org/update/themes/6/7#closure


Using a Service to expose better getter methods for a Node instance Currently we use a Service that takes an NodeInterface object as an argument and then gives back a value, i.e:

  public function iFullyBooked(NodeInterface $node) {
    $fully_booked_field = $node->get('field_fully_booked')->first();
    $value = $fully_booked_field->getValue();

    return $value['value'] === "1";
  }

This works, is testable, but is this a good approach to take? We don't want to put all these preprocess things in a hook, since that function would be ridiculous long and not very nice to work with.

Would this be considered bad practise, and if so, is there a better way?

Having a service for frequently used things like this makes sense.

That said, your code can be simplified a lot.

$node->get('field_fully_booked')->value == 1;

Does exactly the same. If you want to check something, then do a hasField('field_fully_booked') to avoid an error if that field doesn't exist.

This relies on magic methods, see https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

And yes, I did not use a type safe check on purpose. There are cases where type safety makes sense, but entity field values are not type safe, it actually makes your code more error-prone, for example if you'd change the value with API and did a = 1, then your method would return FALSE.


Migrate track last imported time Which property should I set to save the last imported time in the migration map (SQL)?

I've seen that adding:

source:
  track_changes: true

https://www.drupal.org/docs/8/api/migrate-api/migrate-source

The hash is been calculated but no idea how to set the calculation of the time.

Thanks!

You have to set setTrackLastImported to TRUE.

What I've done is create a new source plugin that extends the source plugin that I was using and set to true the last imported property.

/**
 * Source plugin that extends "url" source plugin and saves the last imported
 * date.
 *
 * @MigrateSource(
 *   id = "url_last_import"
 * )
 */
class UrlLastImport extends Url {

public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    $migration->setTrackLastImported(TRUE);
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }
}

I don't know if it's the best solution, but it works.


Checking Available Update data - AJAX error I'm having problems with a local site that I imported to Acquia Dev desktop from one of my live sites.  Everytime I try to Check for Available Update data, I get an Ajax error

  Error Checking Update Data Please Continue to error page An AJAX HTTP
  request terminated abnormally. Debugging information follows. Path:
  /batch?id=676&op=do StatusText: ResponseText: ReadyState: 4

Clicking the error page link, drupal returns me to the available updates page with a message

  An error occurred trying to get available update data.

Any ideas?

Thanks
Sharon

It turns out the problem was with Cron, It was not running due to some custom php code.  Remove the code and everything seems fine now.


Is there a way to set a session variable but not save them in the sessions table? I wanted to save a huge array in a $_SESSION variable. If I understand it correctly, Drupal saves the entire $_SESSION into the sessions table. But when the $_SESSION variable gets to around 3mb, MySQL throws an error.

I don't want to increase max_allowed_packet size, and I don't really need Drupal to save the array variable in the sessions table.

So, is there a way to set a $_SESSION variable that can be excluded from being saved into the sessions table?

You should probably look first at either not storing this data but instead deferring its calculation, or at alternative storage methods, eg perhaps cache_set() and cache_get(). You could easily run into the same DB limitations there of course.

You probably don't need to store this data to the session at all, and as you've discovered it can be problematic to do so.

I've seen developers use  $_SESSION as a global variable to pass data around, and as temporary per-visitor storage. This is possible, but there are limitations and likely better ways - for which you might need to zoom out to the actual problem at hand. (Do you need to store a rendered collection of kitten profiles, or just a list of kitten IDs then render later?)

If you do actually need to store such large datasets to the session, you'd probably have to replace the default session management in Drupal or reconfigure your DB (which you've said you'd rather not do). In that case perhaps modules like Session Proxy or perhaps Memcache would help ... But try not to go there :)


How do I register a user? I am using Drupal 7.17 and the Services module 7.3.2.

I set the Services module as in the following screenshots.

I followed the documentation on http://drupal.org/node/1447020.

With FireFox HttpRequester, I tried to register a new user.

I got a 500 error.

Do you have any idea?

apparently , there is a field of that name ... and some node / entity which is trying to get saved automatically. Could you have Profile2 installed ?
Did you try the report on admin/reports/fields ?
If you dont find it there, try the database - finde the table that uses the column ie this way :

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'field_published_value'
AND TABLE_SCHEMA = 'yourdb'

i tried on a "default install" and didnt see it :)


How to use curly braces in schema default value? I have a long varchar field that I'm using to save serialised data with drupal_write_record. I'd like to set the default value of the column to "a:0:{}" (which is serialize(array())).

However, when Drupal runs database updates, they are run through the update_sql() function which includes the default value in the query. This means that the '{' and '}' are interpreted as prefixing table names and removed, leaving the actual value of "a:0:" in the database, which is not what I want.

Is there a way to use curly braces in a field spec's "default" value?

In your schema, for the field you want to serialize, you can add the key serialize => TRUE and use the drupal_write_record() function to write the field in the database. After, you have just to send a simple array()(without serialize()) and Drupal will do it by himself.

You can have more information in the documentation.


How do I set the sender name? When emails are sent from my dev drupal site to new users the sender is listed as the first part of the site's email address ("info" from "info@mydomainname.com.au" (screenshot below)). Ideally I would like it to be the site's name. How can I control this? Thank you.

drupal_mail() supports a display name in the From: field, but it's up to the whatever module you're using to send mail. If you'd like to force the name, you can use the MIMEMail module.

Once installed, under the Configuration > System > Mimemail administration menu, you can set the default Name/Email that will be sent.


How to send an email to select set of users for moderation states? We are using the following modules below for content moderation. Currently have we have 5 people with the Content Approver role and all of them are sent an email when a state transition occurs. There is a need to send email alerts of moderation transitions for certain content types that need approval to just 2 out of the 5 Approvers.

How to send an email to select set of users when changing moderation state?

Expected Results:

When a content editor marks a page ready for Review, they are allowed to manually select one or more users to send an email alert to regardless of Role.

Enabled Modules:

Workbench v8.x-1.0
Workbench Email v8.x-1.0-alpha7

you can maybe use rules module

alternatively create a custom module and you can inspire from this, that is used with core content moderation module:

use  \Drupal\user\Entity\User;

/**
 *
 *
 * Envoie de mail en fonction des transitions le modération de contenu.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 */
function my_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() !== 'content_moderation_state') {
    return;
  }

  $article_id = $entity->get('content_entity_id')->getString();
  $article = \Drupal\node\Entity\Node::load($article_id);
  if ($article->bundle() !== 'article') {
    return;
  }

  global $base_url;

  $article_title = $article->get('title')->getString();
  $article_url = $base_url . "/node/" . $article->get('nid')->getString();

  $author_name = $article->getOwner()->get('field_cn_ldap')->getString();
  $author_email = $article->getOwner()->getEmail();
  $current_user_uid = \Drupal::currentUser()->id();
  $current_user_name = \Drupal\user\Entity\User::load($current_user_uid)
    ->get('field_cn_ldap')
    ->getString();
  $is_author = ($current_user_name == $author_name);

  $uids = \Drupal::entityQuery('user')
    ->condition('status', 1)
    ->condition('roles', 'redacteur_en_chef')
    ->execute();
  ;
  $users = User::loadMultiple($uids);

  $emails_redacteur_en_chef = [];
  foreach ($users as $user) {
    $emails_redacteur_en_chef[] = $user->getEmail();
  }
  $emails_redacteur_en_chef = implode(',', $emails_redacteur_en_chef);

  $moderation_state = $entity->get('moderation_state')->getString();
  $moderation_state_original = '';
  if ($entity->original) {
    $moderation_state_original = $entity->original->get('moderation_state')
      ->getString();
  }
  $is_transition_change = ($moderation_state !== $moderation_state_original);

  include 'includes/notification/messages.php';
  include 'includes/notification/titles.php';
  $send_to = $author_email;
  $params['node_title'] = $title_mod;
  $params['message'] = $message_same_state;
  $send = FALSE;

  switch ($moderation_state) {
    case 'draft':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      break;

    case 'relecture':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      elseif ($is_transition_change) {
        $send_to = "joe@google.fr";
        $params['node_title'] = $title_prop;
        $params['message'] = $message_prop;
        $send = TRUE;
      }
      break;

    case 'relecture1':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      elseif ($is_transition_change) {
        $send_to = "whatever@yahoo.com";
        $params['node_title'] = $title_relec1;
        $params['message'] = $message_relec1;
        $send = TRUE;
      }
      break;

    case 'relecture2':
      $send_to = $emails_redacteur_en_chef;
      $params['node_title'] = $title_relec2;
      $params['message'] = $message_relec2;
      $send = TRUE;
      break;

    case 'published':
      if (!$is_transition_change) {
        $send_to .= ',';
        $send_to .= $emails_redacteur_en_chef;
        $send = TRUE;
      }
      else {

        $send_to = "all@hotmail.com";
        $params['node_title'] = $title_pub;
        $params['message'] = $message_pub;
        $send = TRUE;
      }
      break;

    case 'maj':
      $send_to = "whatever@wahtever.com";
      $params['node_title'] = $title_maj;
      $params['message'] = $message_maj;
      $send = TRUE;
      break;

    default:
      break;
  }

  if ($send) {
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = "amu_dud_rules";
    $key = 'state_changed_action';
    $to = $send_to;

    $langcode = \Drupal::currentUser()->getPreferredLangcode();

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

    if ($result['result'] !== TRUE) {
      drupal_set_message(t('There was a problem sending notifications.'), 'error');
    }
    else {
      drupal_set_message(t("A notification has been sent to $to"));
    }
  }
}

/**
 * Implements hook_mail().
 */
function my_module_mail($key, &$message, $params) {
  $options = [
    'langcode' => $message['langcode'],
  ];
  switch ($key) {
    case 'state_changed_action':
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $from = 'from@from.com';

      $message['from'] = $from;
      $message['headers']['From'] = $from;
      $message['headers']['Sender'] = $from;
      $message['headers']['Return-Path'] = $from;
      $message['subject'] = t('@title', ['@title' => $params['node_title']], $options);
      $message['body'][] = $params['message'];
      break;
  }
}


Avoiding PHP timeout when geocoding many addresses - preferred method? I have a script that's taking in a ton of address data from a CSV, converting it to JSON, and along the way it hits the Google Maps API to get the latitude and longitude of each address. It then writes the whole thing to a .json file that is used by another widget. This works well for small numbers of addresses but some of the files I'm importing have hundreds of addresses. I have considered several ways around this:

Queues: The problem with this one seems to be that I would have to save an object for each address and I don't want to completely fill up my database with address objects. I would then also have to somehow detect the completion of the queue and retrieve all those objects from the database to generate my complete json file. I worry about whether the server will deal with this well.
Some other Google Maps API: Am I even using the correct Google Maps API for this? Is there one that can get a bunch of coordinates for a bunch of addresses in one HTTP request? I couldn't find one but that doesn't mean it's not existing.
Feeds API (or some other core or contrib API for getting tons of data): It occurs to me that my hand-rolled solution might be circumventing some more Drupal-correct way to accomplish this task. Does Drupal offer something for making big batches of HTTP requests that I'm just missing?

So, basically my question is: what's the most Drupalish way to make and process a large number of HTTP requests from a module?

It seems to me that your only option is to go with a PHP CLI script implementation. You can learn more here: http://www.php-cli.com/

In PHP in general, whenever you have a long running task, it's best to go with PHP CLI as it doesn't impose a timeout limit and have larger memory limits by default. Note here that PHP CLI and the PHP used to server web pages have different settings that you can manage separately.

Once you have a PHP CLI script in place, setup a standard Linux CRON task to hit that script say every hour or every day.

In the context of Drupal, you might want to check this post: Do I need a cron task for processing a queue? and also check the Elysia CRON module https://www.drupal.org/project/elysia_cron as they might be helpful but I think in your case you're better of with a standard PHP CLI script.

Also, keep in mind that you can call Drush commands from a PHP CLI script very easily. I have a script that runs updates and CRON automatically on all Drupal instances running on web server and it's a huge advantage. You can also look into implementing your custom Drush commands.

Good luck.


How to filter paragraphs by the field name on parent using entityQuery? I have a paragraph type my_paragraph which is attached to a node type my_content_type on multiple fields like field_a, field_b, field_c, field_d. I want to load only those attached to some specific fields, let's say field_a and field_c. I am using entityQuery, but open to other suggestions.
The entity/field structure is like:
my_content_type: Node
|_ field_a: Paragraph (type: my_paragraph)
|_ field_b: Paragraph (type: my_paragraph)
|_ field_c: Paragraph (type: my_paragraph)
|_ field_d: Paragraph (type: my_paragraph)

My code which loads all paragraphs of type:
\Drupal::entityQuery('paragraph')
  ->condition('type', 'my_paragraph')
  // Here I want to filter by the field name on the parent entity
  ->condition('PARENT_FIELD', ['field_a', 'field_c'], 'IN')
  // Some more conditions out of context
  ->condition('out_of_context_field', $out_of_context_value)
  ->execute();

Is there any entity query condition I can use here?

Specifically with Paragraphs there are three extra fields directly on Paragraph level, which are accessible with EntityQuery: parent_id, parent_type (entity type like "node", not bundle name like "page"), parent_field_name
You can use those three with EQ like a normal field, e.g.
->condition('parent_field_name', ['field_a', 'field_c'], 'IN')

Notice that those three fields are only available for Paragraphs, it will not work with any other entity type.


Bootstrap subtheme - theme_menu_link(array $variables) not reacting I'm using the Bootstrap theme and I've successfuly created a bootstrap subtheme that I named bootstrapdreve

I've already overidded successfully two templates, but now I'm facing a problem I'm stuck for hours on.

I wanted to overide the bootstrap_menu_link theming function located in bootstrap/theme/menu/.
So I copied it into my

bootstrapdreve/template.php

and renamed it

function bootstrapdreve_menu_link(array $variables)

Before bringing my adaptations I set a dsm('test'); on first line:

function bootstrapdreve_menu_link(array $variables) {
  dsm('test');
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Prevent dropdown functions from being added to management menu so it
    // does not affect the navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = drupal_render($element['#below']);
    }
    elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
      // Add our own wrapper.
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '
' . drupal_render($element['#below']) . '
';
      // Generate as standard dropdown.
      $element['#title'] .= ' ';
      $element['#attributes']['class'][] = 'dropdown';
      $element['#localized_options']['html'] = TRUE;

      // Set dropdown trigger element to # to prevent inadvertant page loading
      // when a submenu link is clicked.
      $element['#localized_options']['attributes']['data-target'] = '#';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    }
  }
  // On primary navigation menu, class 'active' is not set on active menu item.
  // @see https://drupal.org/node/1896674
  if (($element['#href'] == $_GET['q'] || ($element['#href'] == '<front>' && drupal_is_front_page())) && (empty($element['#localized_options']['language']))) {
    $element['#attributes']['class'][] = 'active';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

... and nothing's displayed

I've followed the idea given by this subtheme preprocess functions inheritance post by creating this structure:

bootstrapdreve/theme/menu/menu-link.func.php

and by setting also a dsm('test'); at first line of code...

Still no message... and thus as I interpret it no execution of this function...

I don't understand why. Could you please help me find why this theming function overiding doesn't work ?

Rem.: There's no problem with the dsm(), I've tried to put one at top of bootstrapdreve/template.php and it works fine...

Rem. 2: I've offcourse cleared the cache at every modification I made

I maintain a Bootstrap subtheme that I use for most of my projects and I override theme_menu_link() in my subtheme using the same method with no problem:

/**
 * Overrides bootstrap_menu_link().
 *
 * Resets theme_menu_link() to the default that ships with Drupal. Bootstrap
 * attempts to make every menu with children into a dropdown menu. Remove this
 * function if you want drop down links.
 */
function bootstrap_ignitor_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

You must have a problem somewhere else.


Modify/Alter Password Policy Constraints Text I'm looking for the easiest possible way to modify or alter the password policy constraints error text. The following is the default the users see.

The password does not include enough variation to be secure.
•   Password must contain characters of at least 3 different types (lowercase, uppercase, digit or punctuation).
•   Password must contain at least one digit.
•   Password must be at least 8 characters in length.
•   Password must contain at least one lowercase character.
•   Password must contain at least one punctuation (not whitespace or an alphanumeric) character.
•   Password must contain at least one uppercase character.

I would like to modify this text to display to users like so:

Password must:
    • Be at least 8 characters
    • Have at least one lowercase letter
    • Have at least one number
    • etc etc.

Would this be possible using a form alter or other methods?

Short answer:

Of course there is a module for that.

Actually, more than one:

https://www.cmsdrupal.com/blog/how-implement-custom-password-policy-drupal
https://dev.acquia.com/blog/password-policies-and-drupal/03/04/2017/17856

Longer answer:

Since you don't just want to change the policy (you want to change the form markup too) you might also need to use hook_form_user_login_block_alter(&$form, &$form_state, $form_id).


Programmatically place image field as default value in form plugin I have a content type that has an image field that allows you to upload up to 4 photos. I'm creating a form for users to use that will allow them to edit existing items of this content type. The form fields need to be filled with the existing node field values by default. Retrieving fields such as textfields and supplying the default value works just fine, like so:

class EquipmentEditForm extends ConfigFormBase {
    private $imageNum = 4;

    protected function getEditableConfigNames() {
        return array(
            'equipment.form',
        );
    }
    public function buildForm(array $form, FormStateInterface $form_state) {
        $equipment_id = 10306;
        $node = NODE::load($equipment_id);

        $contact        = $node->get('field_contact')->value;
        $description    = $node->get('field_description')->value;

        $form = [
            'container'    => [
                '#type'       => 'container',
                '#attributes' => [
                    'class'      => ['equipment-entry'],
                ],
                'contact'      => [
                    '#type'       => 'textfield',
                    '#title'      => t('Contact Person'),
                    '#attributes' => [
                        'name'       => 'contact',
                    ],
                    '#default_value' => $contact,
                ],
                'description'    => [
                    '#type'       => 'textfield',
                    '#title'      => t('Description'),
                    '#attributes' => [
                        'name'       => 'description',
                    ],
                    '#default_value' => $description,
                ],
           ],
        ];
    }
}

This generates the form and populated the fields from the node just fine. However I'm not sure how to populate the image field.
I've attempted the following with no luck.

    if ($node->get('field_equipment_photo')->entity != null) {
        $photos = $node->get('field_equipment_photo');
    }
    for ($i = 1; $i <= $this->imageNum; $i += 1) {

        $title = ($i == 1)?'Image '.$i:'Image '.$i.' (extra)';

        $form['image'.$i] = [
            '#type'            => 'managed_file',
            '#upload_location' => 'public://images/',
            '#title'           => t($title),
            '#name'            => 'image'.$i,
            '#default_value'   => $photos[$i],
        ];
    }

It just provides an error

  Recoverable fatal error: Object of class
  Drupal\Core\TypedData\Plugin\DataType\IntegerData could not be
  converted to string in
  Drupal\Core\Entity\ContentEntityStorageBase->buildCacheId() (line 659
  of core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php).

I know I'm retrieving the images because if I perform a statement like this:

die(print_r($photos[1]->entity));

I do get a list of the information contained in the 2 uploaded image. Including the filename.

How would I programmatically retrieve the values of an image field array of a node and place them into the default values of a form field?

UPDATE: I'm able to discover the fid using

die(print_r($photos[0]->entity->fid->value));

but using $photos[0]->entity->fid->value as the default value leads to this error

  Warning: Invalid argument supplied for foreach() in
  Drupal\file\Element\ManagedFile::valueCallback()

Turns out I needed to get the fid of the images and place them into an array. First I started by retrieving the images like I did before

    if ($node->get('field_equipment_photo')->entity != null) {
        $photos = $node->get('field_equipment_photo');
    }

Then I grabbed the fid and placed them into the default value like so

if ($photos[$i]->entity->fid->value != null) {
                $form['image'.$i]['#default_value'] = array($photos[$i]->entity->fid->value);
            }

For some reason even though the fid is just one value it still needs to be wrapped in an array when being used as the default value.


How can I use the core link field widget with title and URL in a custom form? I want to add a link field to my custom form.

Below is the code that I have been trying to use but no success. So can anyone let me know how to use core link field in a custom form in Drupal8?

The below code works for Drupal7 but not for Drupal8. I have also tried using #type => 'link' in the below code.

$form['cta'] = [
  '#type' => 'link_field',
  '#field_name' => 'link_field',
  '#field_parents' => array(),
  '#delta' => 0,
];
return $form;

I think you have to create two seperate form fields to do this in Drupal 8.

You can use textfield for the title and url for the URL field, like this:

$form['cta_title'] = [
  '#type' => 'textfield',
  '#title' => t('CTA Title'),
];

$form['cta_url'] = [
  '#type' => 'url',
  '#title' => t('CTA Url'),
];

return $form;

Another solution is to pull the widget out from an entity display. There is a guide how to do that here, https://www.webomelette.com/how-render-entity-field-widgets-inside-custom-form-drupal-8.

Basically you load the entity display,

$entity = $this->entityTypeManager->getStorage('node')->create(['type' => 'article']);
$form_display = $this->entityTypeManager->getStorage('entity_form_display')->load('node.article.custom_form_display');

And then you pull out the widgets and add them to your form,

foreach ($form_display->getComponents() as $name => $component) {
  $widget = $form_display->getRenderer($name);
  if (!$widget) {
    continue;
  }

  $items = $entity->get($name);
  $items->filterEmptyItems();
  $form[$name] = $widget->form($items, $form, $form_state);
  $form[$name]['#access'] = $items->access('edit');
}


How to prevent a field from wrapping in Views? I have a price field that gets squished and displays on multilines instead of a single line. The only way to solve this is to apply some css wrap magic?

With css you could set a specific width or use white-space:nowrap. I don't know how to do it other than with css or javascript


How can I overwrite a hook from a theme I have a custom sub-theme of the Seven theme. The Seven theme makes some node alteration via seven_form_node_form_alter(). I would like to have seven_form_node_form_alter() not run at all or I would like to overwrite it.  How can I accomplish this?

I tried hook_module_implements_alter() but there was no implementation of Seven in there. (I'm wondering if that only works with modules.)
Another thought was hook_theme_registry_alter() but I couldn't see anything there about form alters.

hook_module_implements_alter() allows just to alter the hooks implemented by modules, and hook_theme_registry_alter() alters only the theme functions, not hooks.

If you look at the code of drupal_alter(), the function that invokes all the alter hooks, you will see the following code, which deals with alter hooks implemented by themes.

// Allow the theme to alter variables after the theme system has been
// initialized.
global $theme, $base_theme_info;
if (isset($theme)) {
  $theme_keys = array();
  foreach ($base_theme_info as $base) {
    $theme_keys[] = $base->name;
  }
  $theme_keys[] = $theme;
  foreach ($theme_keys as $theme_key) {
    $function = $theme_key . '_' . $hook;
    if (function_exists($function)) {
      $functions[$cid][] = $function;
    }
    if (isset($extra_types)) {
      foreach ($extra_types as $extra_type) {
        $function = $theme_key . '_' . $extra_type . '_alter';
        if (function_exists($function)) {
          $functions[$cid][] = $function;
        }
      }
    }
  }
}

The alter hooks implemented by the base themes run first; if you have a sub-theme, and that is the current theme, its alter hook will run last. The only thing I see you could do is (in the implementation of the same hook done from your theme) to remove the changes introduced by seven_form_node_form_alter() that you don't want in your theme.


Showing only one of the Field Collection fields through Views I created a Field Collection field for a content type. This FC has two fields inside: an image field where I can upload unlimited number of image; and the other one is the title field to be used as a caption for these images.

Now the problem arises when I try to view this content type through Views where I can not modify each FC field but the whole FC. For example, if I had a content type with an image and a title field in Views I could manipulate the image field controlling the image style, the linking if the image links to the file or nothing etc. But since I use FC I can not access the image field settings anymore through Views.

The reason I want to manipulate the FC image field is that I want to use Colorbox inside my image gallery. But first I want to link all these images shown through Views to the node of each image gallery and then I want it to be seen with Colorbox.

Note: I tried to use in the FC settings Output this field as a link but it links only from the title field of FC not from the image field and, as I explained above, I can't manipulate the image field to make it have these settings.

Can someone help me out with this problem?
Thank you!

Did you try to ad a new view with "Show: Field Collection Item" and then, you need different relationships and contextual filters. My Field collection Item is called Gallery and Caption

I've got the following relationships (right column of the views):

"Field collection item: entity with the Gallery and Caption" (this
one connects the field collection item with my contenttype gallery)
"(Field_gallery_and_caption) File Usage: File"  "Field collection
item: Gallery Image:fid"

And following Contextual Filters (also right column of the views):

(field_gallery_and_caption) Content: Nid
Field collection item: Gallery Image:fid

I'm not sure about the order of adjustment, you have to try a little bit. But through relationships and contextual filters, you can get new fields for the views. And while configuring the fields (left column of views), there appears a dropdown called "Relationship", try different settings here, it changes the result.

Not the most detailed help but try to change the settings and you gonna get a result...


Are there specific cache tags which get reset on user login? Scenario

I'd like to invalidate a set of caches based on user id upon user login. I'd like to avoid creating new tags, and limit new code as much as possible. Presumably the way to do this is with cache tags.

The specific use case is to cache a user-specific web service response, per user, for the duration of a user session.

Are there any existing cache tags (or something to similar effect) which are invalidated upon successful user login, so that I don't have to implement hook_user_login() to manually invalidate the cache?

No, there aren't any cache tags invalidated upon login. And even if there were, they wouldn't be tied to your cache. Instead, you should act on hook_user_login(), and expire the cache yourself.

Cache invalidation isn't really something you would piggy back onto something non-relevant. Rather, you set up elements with cache tags/contexts etc, and then if necessary you add your own cache invalidation on relevant events.


Installation on OpenSuse Leap I get following two warnings:

  Due to the settings for ServerTokens in httpd.conf, it is impossible to accurately determine the version of Apache running on this server. The reported value is Apache, to run Drupal without mod_rewrite, a minimum version of 2.2.16 is needed.

  PHP OPcode caching can improve your site's performance considerably. It is highly recommended to have OPcache installed on your server.

It would be nice if someone could help me with some pointers about how to solve this problem.

The first error message is saying that, basing on headers returned from Apache, Drupal is not able to determine which Apache version the server is using. If you have access to the httpd.conf file, you can set ServerTokens to at least ServerTokens Min, so Drupal will be able to check which Apache version the server is using.
If you know your server is using at least Apache 2.2.16, you can go forward and proceed with the installation. What you are getting is just a warning for you to check the Apache version, since Drupal cannot find out that.

The other message is telling you that it should preferable to install the OPcache extensions, which means you need to have access to the php.ini file, and being able to install extensions on your server.
If you aren't able to do that, don't do anything. That is not an error message, but a warning message telling you it is preferable to have OPcache enabled to make Drupal faster, but Drupal 8 works also without it.


File (Field) Paths upload/remove not recognized This behavior started after upgrading our Drupal 7.43 system to 7.56. In the process we also upgraded the Views module to 7.x-3.18 and the File (Field) Path module is at 7.x-1.0.

In the content type field management the File field configuration is using this setting for File Name:

[file:ffp-name-only-original].[file:ffp-extension-original]

As an example the file name sellsheet.pdf is displayed on the content page.

In the files/pdf directory the files and revisions are:

  sellsheet.pdf
  sellsheet_0.pdf
  sellsheet_1.pdf
  sellsheet_3.pdf
  sellsheet_4.pdf
  sellsheet_5.pdf

This file is attached to a view using Rewrite results code of:

Sell Sheet

Which generates a link to sellsheet_5.pdf

When I delete this content on the content page I would expect the link on the view to disappear. It does not, it changes the link to the file sellsheet_2.pdf which did not exist before but does now because when looking the directory the files are:

  sellsheet.pdf
  sellsheet_0.pdf
  sellsheet_1.pdf
  sellsheet_2.pdf
  sellsheet_3.pdf
  sellsheet_4.pdf

This because sellsheet_5.pdf has been renamed to sellsheet_2.pdf.

So the view still provides a link even though it should not.

When I upload a new file in the content edit page the directory of files becomes:

  sellsheet.pdf
  sellsheet_0.pdf
  sellsheet_1.pdf
  sellsheet_3.pdf
  sellsheet_4.pdf
  sellsheet_5.pdf
  sellsheet_6.pdf

The new file was uploaded and named sellsheet_5.pdf and sellsheet_2.pdf was renamed to sellsheet_6.pdf.

So when you click on the link on the content editing page it opens sellsheet_5.pdf, but the view link goes to sellsheet_6.pdf.

I'm not sure what is going on but suspect it may have something to do with Drupal not being able to update the database.

There are no errors in watchdog, Apache or MySQL logs.

Has/is anyone else experienced this? I'm assuming it's a File (Field) Path issue.

I have finally discovered the issue. Even though the node shows a status of published there is actually a draft. Up until the upgrade users were able to publish the content they created using Workbench Moderation. Now after saving an edit to the node the status never changes to draft and will not allow the user to publish the content. The only way the content can be published is by an administrator setting the Moderation status at the bottom of the page and then saving the record.

I have not been able to find a way to correct this issue yet. I will post a separate question that has a clearer description of the issue now that I have one.


Starts with a larger ubercart order number Ubercart order number start at 1. How can I set the order number to start with a larger number, e.g. 100001?

Run this query against your database:

ALTER TABLE uc_orders AUTO_INCREMENT = 100001;

The next record added will use 100001 as the ID.

Or for Postgres (Thanks @Mołot for the heads up):

SELECT setval('SEQUENCE_ID', 100001, FALSE);

You'll need to replace SEQUENCE_ID with the appropriate sequence id for the uc_orders table.

For sequence-enabled databases that lack setval (like Oracle, at least in some versions), you can:

ALTER SEQUENCE schema.sequence_id INCREMENT BY 1000;
SELECT schema.sequence_id.NEXTVAL FROM dual;
ALTER SEQUENCE schema.sequence_id INCREMENT BY 1;


Importing Published status from xml using Xpath parser I have an xml page that I want to import. Although I'm able to successfully import the Title and Body, Im unable to import the published status and promoted-to-front-page settings for the page.
Here is what my xml code looks like:

<nodes>
<node>
<Title>This is the Title
</Title>
<Body>
This is the Body
</Body>
<Order>1</Order>
<Path>
/clips/this-is-the-path
</Path>
<Post-date>Tuesday, February 17, 2015 - 09:33</Post-date>
<Promoted-to-front-page>No</Promoted-to-front-page>
<Published>Yes</Published>
</node>
</nodes>

Here are what my Xpath settings look like:

Could anyone suggest what I'm doing wrong here?

I suggest installing feeds tamper (https://www.drupal.org/project/feeds_tamper) with this module you can easily convert the yes to a 1 and no to a 0 before saving to the database. This should solve your issue.


Add a class to images in drupal I have more than thousand images on my site. adding a class to each image manually is very time consuming process is there any way to add the class "adaptive-image" to all images already uploaded automatically.

Few ways to do this:

JavaScript. Not the best one, but fastest:

$('img').addClass('adaptive-image');

For styling field images, see the response by Manoj Bisht.
For styling images added through WYSIWYG you will have to write a custom text filter and add classes. Depending on the WYSIWYG editor you use, you might be able to create a plugin / set configuration so that all images inserted automatically get certain CSS class.
Ultimately, you can just adjust the CSS of .adaptive-image, or clone the styles and apply them for all img tags.
Example source:

.adaptive-image {
  /* Whatever. */
}

Change to, or add this:

img {
  /* Copy styles from .adaptive-image. */
}


CKEditor Inline Styles Getting Removed on save I am trying to edit the font size for CKEditor, however whenever I save these changes, the inline styles are removed.

Now I saw that it may be due to a custom Javascript configuration issue, and so I've put this in the Advanced Options dropdown:

config.allowedContent = true;

Even after putting this on both full and filtered, I've had absolutely no luck getting my inline styles to stay correct. What am I doing wrong? Is this a CKEditor problem, or a Drupal problem?

Nevermind, this is only happening on filtered. So I'm pretty sure it's just a Drupal setting in how filtered is configured. I'll post the solution soon.

You write:

  Nevermind, this is only happening on filtered.

Sure!  The Filtered HTML text format is supposed to do that.

For CKEditor, you need to configure the WYSIWYG filter module to retain inline styles (Unless you allow users to use the Full HTML text format. This is not recommended as it is insecure. The Full HTML text format lets unfiltered user input pass into rendered content.)

I am written up a short cookbook about configuring CKEditor for Drupal, including how you configure the CKEditor ACF and the the WYSIWYG filter text filter to give your users the power of the CKEditor without jeopardizing security.

Here's a link to my CKEditor cookbook.


How I create table View of webform submissions I want to view webform submissions in table view. I created a view of webform submissions but it shows a link for the data submitted. I dont want to use link, I want only simple table view.

You can create your own tables of Webform submissions with Views...

Make a new view of type 'Webform submissions'
Add a page, set the path and set the Style to 'Table'.
Add the fields you want, sort and filter as needed.

If you want submissions filtered by the node (Webform) they were submitted against,  you should add a relationship for 'Webform submissions: Node' so you can pass the Node ID to the view -- remember to include the argument placeholder in your path for the nid (e.g. submissions/%)

(Of course, this provides a tabular view of Webform submissions with the fields you choose as outlined in your question -- the existing view of submissions will still be on the tab for that Webform node... Changing that is a different question.)


Getting error after install drupal8? I have installed drupal 8 .

During installation i am getting the below error

Drupal requires you to enable the PHP extensions in the following list (see the system requirements page for more information):

fileinfo

Which i have solved by uncommenting "extension=php_fileinfo.dll" in php.ini file.

But after successfully installation i am getting connection reset issue like url is not found.

I know d8 is not stable version.

Still some users working/posting issue.

How they able to work on it?

Please suggest is there any alternative link to download d8.

Thank you.

Still some users working/posting issue. How they able to work on it?

They have set up a working web server, installed Drupal core files and a database, and configured a vhost for it. Once you've got your web server working you'll be able to work on it too. That should be your focus; check your web server error logs and fix everything that it says is wrong.

  is there any alternative link to download d8.

There might be, but why would you want to get it from somewhere other than the official Drupal repository? You wouldn't be able to trust that it was up-to-date or that integrity had been maintained with the official release (without manually checking, obviously, but that seems pointless).


Drupal 8 - Pathauto taxonomy terms in content paths I currently have a pattern set up for my site's basic pages. It pulls in some generic fields associated with the content type, and no problems there.

Got a new requirement to associate some data from a taxonomy term into the URL path. The content type already had an entity reference field to pull in the taxonomy terms, so the user could associate any number of those terms with the content.

My issue is that I can only use the Taxonomy Term's Name field in the Pathauto pattern configuration. I see no way to bring in another field associated with that Taxonomy term. So, for example, the vocabulary Company has a field called field_short_name that I would like to include in the Basic Page's URL.

Example data of what I have:

Company taxonomy term

Title: ACME Limited Corporation
Short Name: ACME

Basic Page content:

Title: John Doe
Entity Reference: ACME Limited Corporation

Path Auto:

/[node:field_company]/[node:title]

This currently gives me www.example.com/ACME-Limited-Corporation/John-Doe where I really want it to give me www.example.com/ACME/John-Doe.

I hope I'm explaining this in a way that makes sense.

If you have a taxonomy vocabulary named company

And you have a taxonomy entity reference on your basic page machine-named field_company

Then the pattern you want in pathauto is:

[node:field_company:entity:field_short_name]/[node:title]

This says, "find the value of field_company on the current node, get it's referenced entity, find the value of field_short_name / the node title"


Exposed filter or facet for a vocabulary listing select list I have to create a form with a fulltext search field and a dropdown listing every terms of a certain vocabulary. On submission the form is redirecting the user with the value of both the fields as parameters in path.
I don't know which should be better to use between a facet or a simple list listing every terms of the needed vocabulary?

Facets are usually used for a lot more complex examples with many properties to narrow down your search by.

Both facets and the usual Views with Exposed filters form create paths that hold search parameters entered by users.

The simplest case would probably be to add the textual filter for the Body field, and the Filter for the Taxonomy reference field, and Expose them (so that the users can choose values for them and narrow down the search results). You can use Exposed form settings to change the way the form fields display, drop-downs sometimes aren't the most usable options.

You can use Better Exposed Filters module if you need more options for the exposed form display.


Large files on Pantheon I run the website for a small nonprofit, and we're looking at Pantheon.  I've imported my code and DB and gotten things basically working, but I have a question about serving large files.  We're a choir and we have a couple hundred MP3s (recordings of rehearsals, so people can practice) that we need to serve.  It's not high traffic at all - probably only a couple dozen downloads per week - but the files can be as big as 100M each.

A CDN would be overkill - all downloaders are local, not spread around the globe.  And it's really not much traffic.

How should I host them?  Just check them in to Git?  They're not currently in sites/default/files, but I could put them there and use symlinks from their current location if that would help.

I wouldn't check them into Git, just create an Audio content type and have a file/audio field. I would just check Pantheon to see what the file upload limit is.


Alternative views on content type How do you allow a content type to publish an option that changes views options of that page?

I have created 2 views slideshows block with different settings - I want the user to choose how to view the images on any page of a certain content type BUT DONT WANT TO SAVE THE PAGES TWICE - the images must be shown programmatically depending on which view option is chosen.

I saw this tutorial on rendering views via a tpl.php file...

I do not know how to create and where to place this tpl.php file -- Could this be implemented as a module instead?
What do you place in the $args function - are there any useful examples?

Add a new field to your content type:

Name: Pick a view
Type: boolean
Widget: [doesn't matter]

Then add this code to your block or node or page tpl.php file.

<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$field_value = $wrapper->field_pick_a_view->value();

if ($field_value == 1) {
  print views_embed_view('my_view', 'block_1');
  } else {
  print views_embed_view('my_view', 'block_2');
  }
}

?>

replace view_name with your view name
replace block_1 or block_2 with your machine name

So if your field is check-marked, it prints view 1. If it's not checked-marked, it prints view 2.


Content type or web form(creating own form using hooks) Which one is best way of collecting input from user? I am new to Drupal and learning is in progress. I know about content types and creating webforms using hooks. Now I want to collect data from user and store it to db and view it later (easily I can do with a content type) but I need to apply some jQuery events. i.e. if user choose a country then in another drop down I want to show the states of that particular country and I want to change input style.

Which suits best for above problem and why not another one more suitable?

If you dont want to make your hands dirty playing with code then better use webform module as per your drupal version.
Webform module  in drupal gives you everything, you dont need to make further queries to manage the input data, its just a use of normal CMS. Better try with that, an in addition you can export data as well.
I hope this helps you.
Thanks


Geshi does not detect libraries on Drupal 7 I have installed the Geshi Filter and Field modules, but Drupal does not detect the GeShi Libraries.

I got the Geshi Libraries from sourceforge. To be sure, I put it in:
/sites/all/libraries/ ,  /sites/all/modules/libraries/ and /sites/all/modules/geshifilter/
I am using 7.x-1.x-dev

Yet, it cannot find the libraries. How can I get it to work? Please do not suggest syntaxhighlighter. I have tried it and I would prefer a server side solution.

From the Status Report

The files should be copied, for example, in "sites/all/libraries/geshi" or "$config/libraries/geshi," where "$config" is the directory containing the settings.php file used for the Drupal site.
In the first case, the class.geshi.php file is put in "sites/all/libraries/geshi/class.geshi.php," and the "geshi" directory that is in the downloaded archive is put in "sites/all/libraries/geshi/geshi."

As for where the Libraries API module looks for the directory containing the library files, the documentation comment for libraries_get_libraries() reports the following text:

  Returns an array of library directories from the all-sites directory (i.e. sites/all/libraries/), the profiles directory, and site-specific directory (i.e. sites/somesite/libraries/).

The site-specific directory is the one that I reported as "$config/libraries/geshi."
The module doesn't look in "sites/all/modules/libraries."


remove divs and spans from view output In my page.tpl.php I'm doing this to display one of my view:

print views_embed_view('teaserview', 'default');

That gives me the following html output:

Edit view

But the only thing that I really need is

Is there a possibility to modify the views_embed_view call so that I get only the needed data?

There would be the possibility to modify all the views .tpl.php files but I hope there's an easier way to do this.

I also read about the semantic views module but I didn't understand how to configure my view with it so that i get only the needed markup as output. it didn't seem to have any effect.

If you go into the view thru the Views UI, and look at the fields, you can configure/remove the wrapper html from the field by selecting none for the wrapper of the field, and that should take a lot, if not all, of the html away that you don't want.  Also, if you go into the views admin screen and go to tools, you can check the "Do not show hover links over views" which should remove the first edit portion of all of your views when looked at via an admin type account as well.

If the above doesn't take away all the html you want, you can either modify the templates as you mentioned above, or use something like this instead of views_embed_view:

$view = views_get_view('teaserview');
$display_id = 'default';
$view->set_display($display_id);
$view->execute();

which will execute but not display the view ... but will create a $view->result which is an array of row objects basically, so you could then go in there and print out whatever you wanted.

To find out what is in there, throw in a

drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>');

and you'll see what you can work with.

PS
Once you have this working, I would put it in a preprocess hook and assign this output to a variable instead of putting any/all of this code in your page.tpl, too...

PPS
I also am assuming you know that the Theme Developer module is throwing a lot of html in there as well (all those thmr='s as such).


Search api, postprocess processor: how re-run the query? The documentation of the search api module says, about postprocess processor:

Postprocess query
This is probably the rarest phase for processors to
use, postprocessing the query after it has run to manipulate the
search results in some way. A prominent example would be the
"Highlight" processor, which highlights the search keywords in the
returned results. But this phase could also be used, for example, to
re-run the query completely with some changes in case no results were
found the first time.

However, it doesn't explain how to re-run the query completely.
I've to implement exactly in the case described: I've a search api view, with a fulltext search exposed filter and some facets.
If the query returns no results, I need to re-run it with some changes on the conditions provided by one of the facet filters (the content type), before actually rendering the result page.
This must be done programmatically and not by user interaction.
I've checked the ProcessorInterface but the only relative method seems to be the function postprocessSearchResults(ResultSetInterface $results);.
Highligh, the only processor implementing a postprocess_query stage doesn't do anything similar at what I need to do.
Any idea how I could re-run the query? I'm on a D9 site. Alternative solutions to the problem would be useful too, I'm trying this way as the documentation gives the idea it is a possible solution.

I managed to do something, despite not being optimal: in the postprocessSearchResults when necessary I send a RedirectResponse with new search params thus "reloading" the page and "re-running the search.
  /**
 *
 * @SearchApiProcessor(
 *   id = "my_processor",
 *   label = @Translation("A label"),
 *   description = @Translation("A description"),
 *
 *   stages = {
 *     "postprocess_query" = 0,
 *   }
 * )
 */
class MyProcessor extends ProcessorPluginBase {

  //Skipped constructor and boilerplate code

  /**
   * {@inheritdoc}
   */
  public function postprocessSearchResults(ResultSetInterface $results) {
    if ($results->getResultCount()) {
      return;
    }

    $query = $results->getQuery();

    if ($query->getProcessingLevel() != QueryInterface::PROCESSING_FULL) {
      return;
    }

    $request = $this->requestStack->getMasterRequest();
    $request_query = $request->query;
    $sdm_empty_result_automatic_search = $request_query->has($this->requestQueryTag) ? $request_query->get($this->requestQueryTag) : FALSE;

    /*
     * Necessary to identify between user search and ones run by this class.
     * E.g. if the user is on "article", and does a new search, it must stay
     * on "articles" if there is any result.
     * However if there are no results, the class must redirect to the fist
     * content type and so on until all are searched
     *
     */
    $next_type_value = NULL;
    $condition_type_value = $this->sdmSearchQueryHelper->queryGetConditionValue($query);
    switch ($condition_type_value) {
      case 'prodotto':
        $next_type_value = 'scheda_espositore';
        $sdm_empty_result_automatic_search = TRUE;
        break;
      case 'scheda_espositore':
        $next_type_value = $sdm_empty_result_automatic_search ? 'article' : 'prodotto';
        break;
      case 'article':
        $next_type_value = $sdm_empty_result_automatic_search ? NULL : 'prodotto';
        break;
    }

    if (empty($next_type_value)) {
      return;
    }

    $query_params = [
      'search_api_fulltext' => $query->getOriginalKeys(),
      'sort_by' => 'title',
      'f' => ['content_type:' . $next_type_value],
    ];

    if ($sdm_empty_result_automatic_search) {
      $query_params[$this->requestQueryTag] = $this->requestQueryTag;
    }

    $response = new RedirectResponse(Url::fromRoute('<current>', [], ['query' => $query_params])
      ->toString());
    $response->send();

     /**
     * todo
     * can't use the following logic but had to do all the previous because I have overriden the default url_processor,
     * so there is always a "default" content type if none is selected.
      * So unfortunately I can't run a generic query to search for all the results.
      * For a "standard" search implementation the following one could be a good starting point
     */
    /*
    $original_query = $query->getOriginalQuery();
    $original_query->addTag($this->queryTag);
    $this->sdmSearchQueryHelper->addConditionToQuery($original_query, 'facet:type', ['type' => 'scheda_espositore']);
    $results = $original_query->execute();

    $items = $results->getResultItems();
    $iterator = $results->getIterator();
    */

  }


How to create multi select list programmatically How to create a multi select list in a custom module, populate values from taxonomy term and access the selected values when the form is submitted.

I have to code below for multi select list. I want to know how to access the multiple selected values from multi select list when the form is submitted.

function rice_graph_form($form, &$form_state) {
  $form['country'] = array(
  '#title' => t('Country'),
  '#type' => 'select',
  '#multiple' => true,
  //'#description' => 'Select a Country.',
  '#options' => rice_graph_get_terms('country')
  );
  if(isset($form_state['values'])) {
    $multivalues = $form_state['values']['country'];
  }
}

In your submit handler add something like this:

$selected_countries = array_filter($form_state['values']['country']);

$selected_countries will contain the array keys of all the selected items in your Country select list. You need the array_filter to get rid of unselected items, which also come through to the submit handler but with a value of 0.