I have multiple values image field in Drupal 8 and I would like to prepare values in Controller for output in the twig template.
It's simple (well, if we can call the ridiculously complicated "lets-do-everything-in-OOP-eventhough-its-useless" Drupal 8 way simple) for single value fields:
$nids = \Drupal::entityQuery('node')->condition('type', 'zbornik_a_foto')->execute();
$nodes = Node::loadMultiple($nids);
$data = array();
foreach ($nodes as $node) {
$data[] = array(
'rocnik' => $node->get('field_rok')->getValue(),
'miesto' => $node->get('field_miesto_konania')->getValue(),
'fotografie' => $node->get('field_zbornik')->getValue(),
'foto' => $node->get('field_fotografie')->getValue(),
);
}
return array(
'#theme' => 'riadky_zazili',
'#data' => $data,
'#title' => 'Zažili sme',
);
However, the field_fotografie value is multiple values field and I would like to get all image's URIs in the $data array. Does anybody know how? Ideally less than 10 lines of useless OOP jibber-jabber. Thanks.
Try like this way, it might be useful for you.
$data = array();
foreach($nodes as $node) {
$photo = array();
foreach($node->get('field_image')->getValue() as $file){
$fid = $file['target_id']; // get file fid;
$photo[] = \Drupal\file\Entity\File::load($fid)->getFileUri();
}
$data[] = array(
'rocnik' => $node->get('field_rok')->getValue(),
'miesto' => $node->get('field_miesto_konania')->getValue(),
'fotografie' => $node->get('field_zbornik')->getValue(),
'foto' => $photo,
);
}
$nids = \Drupal::entityQuery('node')->condition('type', 'zbornik_a_foto')->execute();
$nodes = Node::loadMultiple($nids);
$data = array();
foreach ($nodes as $node) {
$fotoValues = $node->get('field_fotografie')->getValue();
$myvalues = array();
foreach($fotoValues as $val){
$myvalues[] = $val["value"];
}
$data[] = array(
'rocnik' => $node->get('field_rok')->getValue(),
'miesto' => $node->get('field_miesto_konania')->getValue(),
'fotografie' => $node->get('field_zbornik')->getValue(),
'foto' => $myvalues,
);
}
return array(
'#theme' => 'riadky_zazili',
'#data' => $data,
'#title' => 'Zažili sme',
);
Hope this helps you
thanks
Related
i'm trying to show categories in search.twig using events for this i have create a module file to add event.
i am assuming after common/search controller is called the event will add categories to existing data variable and will send categories along all data from common/search controller. i have copied the code below
admin/controller/extention/module/cc_add_search_categories.php
public function install(){
$this->load->model('setting/event');
$this->model_setting_event->addEvent('ccaddsearchcategorise', 'catalog/controller/common/search/after', 'extension/module/cc_add_search_categories/addCategoriesToSearch');
}
public function uninstall(){
$this->load->model('setting/event');
$this->model_setting_event->deleteEventByCode('ccaddsearchcategorise');
}
and in
catalog/controller/extention/module/cc_add_search_categories.php
public function addCategoriesToSearch(&$route, &$data, &$output){
$this->load->model('catalog/category');
$this->load->language('extention/module/cc_add_search_category');
$data['categories'] = array('data');
$categories_1 = $this->model_catalog_category->getCategories(0);
foreach ($categories_1 as $category_1) {
$level_2_data = array();
$categories_2 = $this->model_catalog_category->getCategories($category_1['category_id']);
foreach ($categories_2 as $category_2) {
$level_3_data = array();
$categories_3 = $this->model_catalog_category->getCategories($category_2['category_id']);
foreach ($categories_3 as $category_3) {
$level_3_data[] = array(
'category_id' => $category_3['category_id'],
'name' => $category_3['name'],
);
}
$level_2_data[] = array(
'category_id' => $category_2['category_id'],
'name' => $category_2['name'],
'children' => $level_3_data
);
}
$data['categories'][] = array(
'category_id' => $category_1['category_id'],
'name' => $category_1['name'],
'children' => $level_2_data
);
}
}
I have a custom post_type 'publications' and it has a Repeater field 'linked_author' with a sub-field 'paper_linked_author' - a post object.
Here is the code to get all of the publications post and run a loop to get all authors linked to each post.
$args = array(
'posts_per_page' => '-1',
'post_type' => 'publications'
);
$the_query = new WP_Query( $args );
$post_ids = wp_list_pluck( $the_query->posts, 'ID' );
echo "<pre>";
print_r($post_ids);
echo "</pre>";
$artist_list = array();
foreach($post_ids as $post_id){
$artist_repeater = get_field('linked_author', $post_id);
echo "<pre>";
print_r($artist_repeater);
echo "</pre>";
if ($artist_repeater) {
$speakers = get_sub_field('paper_linked_author');
if ($speakers && count($speakers)>0)
{
foreach ($speakers as $speaker)
{
echo $speaker->ID; //$speaker is a post object//
}
}
}
}
I have been able to get all the sub-field values of each publication post however I'm not able to echo details of each linked author - the sub-field values. A print_r($artist_repeater) shows below details for one of the posts.
So, my question is how to list all unique authors from below print_r() array? Also, I need to link each author name such that clicking will bring list of all publications post he/she is linked to? Please help!
Array
(
[0] => Array
(
[paper_linked_author] => WP_Post Object
(
[ID] => 4885
[post_author] => 1
[post_date] => 2018-06-26 04:56:29
[post_date_gmt] => 2018-06-26 04:56:29
[post_content] =>
[post_title] => Q1-Test
[post_excerpt] =>
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => q1-test
[to_ping] =>
[pinged] =>
[post_modified] => 2018-06-26 05:14:13
[post_modified_gmt] => 2018-06-26 05:14:13
[post_content_filtered] =>
[post_parent] => 0
[menu_order] => 0
[post_type] => people
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
)
[1] => Array
(
[paper_linked_author] => WP_Post Object
(
[ID] => 2115
[post_author] => 1
[post_date] => 2017-03-28 05:47:01
[post_date_gmt] => 2017-03-28 05:47:01
[post_content] =>
[post_title] => Julius Ceaser
[post_excerpt] =>
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => julius-ceaser
[to_ping] =>
[pinged] =>
[post_modified] => 2018-06-25 11:02:55
[post_modified_gmt] => 2018-06-25 11:02:55
[post_content_filtered] =>
[post_parent] => 0
[menu_order] => 0
[post_type] => people
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
)
)
Just so it helps others, I solved the above problem with below code.
Basically, I was looking to list all authors who have written at least one Publication. So, earlier I was querying publications custom post_type and then looping each publication to list linked authors and that is where the above print_r() dump can be seen.
So, instead I queries all authors (a custom post_type) and then queries publications to match the key "linked_author_$_paper_linked_author" with the ID of the author post. It worked.
<?php
add_filter( 'posts_orderby' , 'posts_orderby_lastname' );
$args = array(
'post_type' => 'people',
'posts_per_page' => -1, // Unlimited posts
'post_status' => 'publish'
// Order alphabetically by name
);
$loops = new WP_Query( $args );
while ($loops -> have_posts()) : $loops -> the_post();
$args = array(
'numberposts' => -1,
'post_type' => 'publications',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'linked_author_$_paper_linked_author',
'compare' => '=',
'value' => get_the_ID()
)
)
);
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
?>
<ul>
<li><?php echo the_title(); ?></li>
</ul>
<?php
endif;
endwhile;
?>
Opencart 2.x/3.x
Hi, friends!
My head is boiling like a teapot :( Help please to solve the problem.
I want to show all values from "Stock Status" in category page but do not show "Out Of Stock" when the quantity of the product more and less zero.
My code:
product.php - in controller
Before: if ($product_info['quantity'] <= 0) {
Add: $data['stock_quantity'] = $product_info['quantity'];
$data['stock_text'] = $product_info['stock_status'];
After: $data['products'][] = array(
Add: 'quantity' => $result['quantity'],
'stock_text' => $result['stock_status'],
category.php - in controller
After: $data['products'][] = array(
Add: 'quantity' => $result['quantity'],
'stock_text' => $result['stock_status'],
product.tpl - in template
<?php if ($stock_status_id != 5) {
echo $product['stock_text']; }
?>
Tell please, which correct code do I need to specify so that i can see all statuses except for "out of stock"(id=5) ?
Preview
In catalog/model/catalog/product.php
add:
'stock_status_id' => $query->row['stock_status_id'],
after:
if ($query->num_rows) {
return array(
'product_id' => $query->row['product_id'],
'name' => $query->row['name'],
In catalog/controller/product/category.php
add:
if($result['stock_status_id'] == 5){
$stock = '';
}else{
$stock = $result['stock_status'];
}
before:
$data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
add:
'stock' => $stock,
after:
$data['products'][] = array(
In category.tpl
add:
<?php echo $product['stock']; ?>
at place you want to display stock but in $product foreach loop.
To display stock_status as your add_to_cart button:
In catalog/model/catalog/product.php
add:
'stock_status_id' => $query->row['stock_status_id'],
after:
if ($query->num_rows) {
return array(
'product_id' => $query->row['product_id'],
'name' => $query->row['name'],
In catalog/controller/product/category.php
add:
if($result['stock_status_id'] == 5){
$data['button_cart'] = $result['stock_status'];
}else{
$data['button_cart'] = '';
}
before:
$data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
This will change your 'add to cart' button to stock status and if stock_status_id ==5 then text will remain as 'add to cart'
I'm trying to create a custom module with configuration for a block that will allow a block to have custom fields. I'm having problems allowing the upload of an image and then rendering this in the block on the site.
Currently this is what my block file looks like;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'hello' block.
*
* #Block(
* id = "hello_block",
* admin_label = #Translation("Hello"),
* category = #Translation("Hello world block")
* )
*/
class HelloBlock extends BlockBase
{
/**
* {#inheritdoc}
*/
public function blockForm($form, FormStateInterface $formState)
{
$form['heading'] = array(
'#type' => 'textfield',
'#title' => t('Heading'),
'#description' => t('Enter the main heading'),
'#default_value' => 'Main heading'
);
$form['sub_heading'] = array(
'#type' => 'textfield',
'#title' => t('Sub heading'),
'#description' => t('Enter the sub heading'),
'#default_value' => 'Sub heading'
);
$form['body'] = array(
'#type' => 'text_format',
'#title' => t('Body'),
'#description' => t('Main body'),
'#format' => 'full_html',
'#rows' => 50,
'#default_value' => ''
);
$form['image'] = array(
'#type' => 'managed_file',
'#upload_location' => 'public://upload/hello',
'#title' => t('Image'),
'#upload_validators' => [
'file_validate_extensions' => ['jpg', 'jpeg', 'png', 'gif']
],
'#default_value' => isset($this->configuration['image']) ? $this->configuration['image'] : '',
'#description' => t('The image to display'),
'#required' => true
);
return $form;
}
/**
* {#inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $formState)
{
$this->configuration['heading'] = $formState->getValue('heading');
$this->configuration['sub_heading'] = $formState->getValue('sub_heading');
$this->configuration['body'] = $formState->getValue('body');
$this->configuration['image'] = $formState->getValue('image');
}
/**
* {#inheritdoc}
*/
public function build()
{
$markup = '<h1>'.$this->configuration['heading'].'</h1>';
$markup .= '<h2>'.$this->configuration['sub_heading'].'</h2>';
$markup .= '<img src="'.$this->configuration['image']['value'].'">';
$markup .= '<div>' . $this->configuration['body'] . '</div>';
return array(
'#type' => 'markup',
'#markup' => $markup,
);
}
}
Can anyone provide some pointers as to why the image isn't appearing? I'm assuming I'm missing something.
The text saved in the body (text_format) also appears in the block on the website as 'array', if anyone can help with that too it would be good, other wise I'll raise another question.
When you save that form, the value from the image field is the File ID.
Therefore, you can get the file object and the path by using:
$image = \Drupal\file\Entity\File::load($fid);
$path = file_create_url($image->getFileUri());
Then you would output the image using that path in your markup variable. There's probably a more semantic way to output the formatted image in a 'Drupal-ish' form, but this will get you started.
Oh, and the body field, use
$form_state->getValue('body')['value'];
in your markup.
BTW, I love using Devel and the ksm() function!
I would like to return an array of string in my web services
I've tryed :
<?php
require_once('nusoap/nusoap.php');
$server = new soap_server();
$server->configureWSDL('NewsService', 'urn:NewsService');
$server->register('GetAllNews',
array(),
array('return' => 'xsd:string[]'),
'urn:NewsService',
'urn:NewsService#GetAllNews',
'rpc',
'literal',
''
);
// Define the method as a PHP function
function GetAllNews()
{
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
return $stack;
}
but it doesn't work.
What is the correct syntax for that ?
Thanks in advance for any help
You can't return an array like this. To return an array, you have to define a complex type.
I'll provide u an example...
The server program service.php:
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
$server->configureWSDL('RM', 'urn:RM');
//Define complex type
$server->wsdl->addComplexType(
'User',
'complexType',
'struct',
'all',
'',
array(
'Id' => array('name' => 'Id', 'type' => 'xsd:int'),
'Name' => array('name' => 'Name', 'type' => 'xsd:string'),
'Email' => array('name' => 'Email', 'type' => 'xsd:string'),
'Description' => array('name' => 'Description', 'type' => 'xsd:string')
)
);
// Register the method
$server->register('GetUser', // method name
array('UserName'=> 'xsd:string'), // input parameters
array('User' => 'tns:User'), // output parameters
'urn:RM', // namespace
'urn:RM#GetUser', // soapaction
'rpc', // style
'encoded', // use
'Get User Details' // documentation
);
function GetUser($UserName) {
return array('Id' => 1,
'Name' => $UserName,
'Email' =>'test#a.com',
'Description' =>'My desc'
);
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
And the client program client.php:
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/Service/service.php');
// Call the SOAP method
$result = $client->call('GetUser', array('UserName' => 'Jim'));
// Display the result
print_r($result);
?>