Drupal 8 translating paragraphs programmatically - drupal

Paragraphs are supposed to be translated on on the level of their component fields, not on the paragraph_field level. So how do you programmatically translate paragraphs?
To be more explicit, my paragraph field is not translatable, but the component fields are. So how can I load a node, loop through the paragraph items, and add translations to the fields?
Does anyone have an example?
Thanks.

following https://www.flocondetoile.fr/blog/translate-programmatically-drupal-8 node translation:
This is an abstraction of my actual code, and I haven't actually tested it:
$node = node_load(12);
if ($node->hasTranslation('de')) {
$transl_node = $node->getTranslation('de');
foreach ($transl_node->field_paragraph => $paragraph) {
$entity_array = $paragraph->toArray();
$translated_fields = [];
$translated_fields['field_body'] = array(
'value' => 'translated value',
'format' => 'full'
);
$translated_fields['field_section_title'] = 'translated section title';
$translated_entity_array = array_merge($entity_array, $translated_fields);
if (!$paragraph->hasTranslation('de')) {
$paragraph->addTranslation('de', $translated_entity_array);
$paragraph->save();
}
}
$transl_node->save();
}

Related

How to programmatically query the translated content of a block in drupal9

I created a block, the default language is English and the translation language is Chinese. Now I query the content of this block in my code:
$block = \Drupal::entityTypeManager()->getStorage('block_content')
->loadByProperties([
'info' => $info,
'langcode' => 'zh-hant'
]);
But what I got is still in English, what am I doing wrong?
You have to load the block_content entities without langcode condition, then get the translation in the language you need by getTranslation():
$blocks = \Drupal::entityTypeManager()->getStorage('block_content')
->loadByProperties([
'info' => $info
]);
$translated_blocks = array_map(function ($block) {
return $block->getTranslation('zh-hant');
}, $blocks);
// do somthing with $translated_blocks

Programmatically adding columns in VIEWS

In drupal 7 view, I have created a custom module and add dynamic columns using below method.
function my_module_views_pre_view(&$view, &$display_id, &$args) {
if ($view->name == 'my_view') {
$countries = my_module_vocab_terms('countries');
foreach ($countries as $country){
$view->add_item($view->current_display, 'field', 'views', 'nothing', array(
'label' => $country->name,
'alter' => array('text' => $country->tid),
'element_class' => 'my-field',
'element_default_classes' => 0,
), $country->tid);
}
}
}
}
But the text value repeated in each rows like this.
Please suggest how to pass value for each row.
Thanks
If anyone is still interested how to alter values to such fields.
You can do so by rendering the fields and altering the data in one of the hooks where the results are already fetched eg. the hook_views_post_execute, hook_views_pre_render, hook_views_post_render depending on your needs.
/**
* Implements hook_views_post_execute().
*/
function my_module_views_post_execute(view &$view) {
$view->style_plugin->render_fields($view->result);
$view_fields = &$view->style_plugin->rendered_fields;
foreach ($view_fields as &$field) {
$field['my_field'] = "some value";
}
unset($field);
}

Drupal change multi select to checkboxes on views exposed form not working

I needed to have all taxonomy vocabularies available to filter on, without adding all of the taxonomies one at a time.
I did this using the Content: Has taxonomy terms (Multiple) Filter - which renders out as a multiple select list.
I needed to change the select list to checkboxes, but BEF didnt allow me to do that for this type of field, so i did the following...
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'views_exposed_form') {
$options = $form['filter']['#options'];
unset($form['filter']);
foreach($options as $vocab => $terms) {
foreach ($terms as $key => $value) {
$newkey = $options[$vocab][$key]->option;
$termoptions[$vocab][key($newkey)] = $newkey[key($newkey)];
}
$form[$vocab] = array(
'#type' => 'checkboxes',
'#options' => $termoptions[$vocab],
'#title' => $vocab,
'#multiple' => TRUE,
);
}
}
}
The exposed form looks good, but it doesnt work.
I think its because the name of the query is wrong. As i have split up the heirarchy into separate fields, the url used to look like
mysite.com/category?filter[]=123
Now it looks like...
mysite.com/category?Brand[123]=123
So theres how far ive got, any ideas how i can make this exposed form work?
I had a poke around at changing the submit handler views_exposed_form_submit but i dont know what i would need to change.
i am updating my ans once again for more clear view
step one expose filter
settings for this
click on settings text then
then gor for bef
and the result is
hope it make sense now

Change field using theme_preprocess_field()

gunwinner is my theme name and i want to change a field on particular content type.
I have tried this code,
function gunwinner_preprocess_field(&$variables) {
$element = $variables['element'];
if($element['#field_name'] == 'field_deal_url') {
$values = $element['#items'][0]['value'];
$deal_link = l(t("Go to Store"), "$values", array('attributes' => array('class' => 'store-link')));
$element['#items'][0]['value'] = "Store";
return;
}
}
which returns me the array with the link title "Go to Store" but it doesn't reflect on the page for the particular field.
Can anyone help me out for this?
You're making a copy of $variables['element'] and manipulating that, so the changes aren't being persisted into the original variable.
Just change the first line of your function to
$element = &$variables['element'];

Add CSS attributes to Symfony form labels?

I try to add some css attributes to labels in my custom sfForm but I can't achieve it.
In my custom class myForm extends sfForm, I create all textfields dynamically:
public function configure()
{
$widgetFixtures = array();
foreach ($fixtures as $fixture) {
$widgetFixtures[$fixture->getId()] = new sfWidgetFormInputText(
array('label' => $fixture->getTeamNameDom()),
// I would like to add something like: array('class' => $fixture->getCSS()),
array('value' => $fixture->getScore1(), 'readonly' => 'readonly')
);
}
$this->setWidgets($widgetFixtures);
}
I tried to format the rendering with setFormFormatterName but without success.
Note: I can't use renderLabel($value, $attributes = array()) in the template because I get the CSS class from the DB (as you may have seen, I have to use: $fixture->getCSS()).
Could someone shed my light?
Many thanks.
Here is how I solved it.
I took both suggestions from johnwards and richsage and put them together :
"This sort of stuff should be handled in the view/action."
"Access to the options/attributes passed to the Widget itself."
First, I add the CSS class to the input itself (even if I will not use it).
In my custom class myForm extends sfForm,
foreach ($fixtures as $fixture) {
$widgetFixtures[$fixture->getId()] = new sfWidgetFormInputText(
array('label' => $fixture->getTeamNameDom()),
array('value' => $fixture->getScore1(),
'readonly' => 'readonly',
'class' => $fixture->getCSS())
);
}
Then, in the template, instead of using echo $form;, I add the CSS class to the label as shown below:
foreach ($form as $widgetId => $widget) {
...
$labelClass = $widget->getWidget()->getAttribute('class');
echo '<td>'.$widget->renderLabel(null, array('class' => $labelClass)).'</td>';
...
}
Maybe it is not the best way to solve this issue but it works.
Thanks all for your feedback!
What you're trying to do seems possible but your greyed out syntax seems a little off. Try this:
$widgetFixtures[$fixture->getId()] = new sfWidgetFormInputText(
array('label' => $fixture->getTeamNameDom()),
array('class' => $fixture->getCSS()),
array('value' => $fixture->getScore1(), 'readonly' => 'readonly')
);
... or check "The sfWidgetForm Base Class" section here: http://www.symfony-project.org/forms/1_4/en/A-Widgets
The class attribute needs to be passed in as an array in the second parameter for all form widgets.
$this->setWidget('foo', new sfWidgetFormInputText(array(),array('class','fooclass'));
You could try overriding the widget class if you want to add CSS to labels - specifically the methods that render the label. You could then do something like
$foo = new myWidgetFormInputText(array("myCSSClass" => $fixture->getCSS()));
and then override your renderLabel() method or similar in your widget. Your widget will have access to the options you pass in - in the above example myCSSClass is the option key. You can then apply this class value to your widget's label.
It's much easier than that. Just apply CSS to the label for tag...
label[for=payment_cardNumber]
{
margin-top: 20px;
color: red;
}

Resources