I'm doing an entity reference to fetch a node from under a specific content. I'm looking to how I can render the entity reference function I've just created to my region.html.twig template. Below is a snippet of the code I'm currently working on
// Page region level pre-processing
function iom_preprocess_region(&$variables) {
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$variables['content_type'] = $node->bundle();
}
$elements = $variables['elements'];
if (array_key_exists('#entity', $elements)) {
$region = $elements['#region'];
$entity = $elements['#entity'];
$bundle = _overrideBundle($entity->bundle());
preprocess($region, 'region', $entity, $variables);
preprocess($region."_{$bundle}", 'region', $entity, $variables);
}
}
function _preprocess_country_regional_offices_node($entity, &$variables) {
$entityStorage = \Drupal::service('entity_type.manager')->getStorage('node');
$regionalOffices = \Drupal::service('entity.query')
->get('node')
->condition('status', 1, '=')
->condition('type', 'regional_office')
->condition('field_primary_offices', '1')
->sort('created', 'DESC')
->execute();
$regionalOfficeEntities = $entityStorage->loadMultiple($regionalOffices);
$variables['regional_office'] = $regionalOfficeEntities;
}
I'd probably do this using an exposed block, but if you need to do it in code for a specific reason then..
$output = render(
\Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node, 'teaser')
);
Related
I need of you for helping to resolve my problem.
I use Symfony 4 for display some charts with the bundle google charts
Thanks you a lot
This is my function controller
/**
* #Route("/admin/test", name="statsTest")
*/
public function statsTest(){
$results = $this->getDoctrine()->getRepository(IssueNubitalk::class)
->CountIssueByPartenaire('Canal');
dump($results);
// $results = [];
foreach ($results as $key => $val) {
// dump($results);
$results[] = [
'campaign' => $val->getCampaign(),
'total' => $val->getTotal(),
];
}
dump($results);
$data = json_decode(json_encode($results), true);
$pieChart = new PieChart();
$pieChart->getData()->setArrayToDataTable($data);
$pieChart->getOptions()->setHeight(250);
$pieChart->getOptions()->setWidth(400);
$pieChart->getOptions()->getTitleTextStyle()->setBold(true);
$pieChart->getOptions()->getTitleTextStyle()->setColor('#009900');
$pieChart->getOptions()->getTitleTextStyle()->setItalic(true);
$pieChart->getOptions()->getTitleTextStyle()->setFontName('Arial');
$pieChart->getOptions()->getTitleTextStyle()->setFontSize(20);
return $this->render('backend/test.html.twig', [
'piechart' => $pieChart,
]);
}
this is my repository
public function CountIssueByPartenaire($partenaire){
return $this->createQueryBuilder('i')
->select('i.campaign')
->addSelect('COUNT(DISTINCT i.sessionId) as total')
->where('i.campaign LIKE :campaign')
->setParameter('campaign', $partenaire.'_%')
->groupBy('i.campaign')
->getQuery()
->getResult();
}
this is the output
Call to a member function getCampaign() on array
I'm using Woocommerce REST API to retrieve some data, code provided by Woocommerce team to use as client
My client options:
'wp_api' => true,
'version' => 'wc/v1',
'ssl_verify' => false,
'wp_api_prefix' => '/wp-json/',
'query_string_auth' => true,
Have a function to retrieve subscriptions:
function get_wc_subscriptions($sid=0, $parent=null, $page=1, $offset=0)
{
$params['page'] = $page;
$params['offset'] = $offset;
$params['role'] = 'all';
if($sid > 0) {
$endpoint = 'subscriptions/'.$sid;
} else {
$endpoint = 'subscriptions';
}
if(isset($parent) && ($parent != null)) {
$params['filter[parent_id]'] = $parent;
}
return $this->wooClient->get($endpoint, $params);
}
Parent parameter is not working, when calling function without any params, I get a result of all subscriptions on first page, if parent is set, get same result with all subscriptions (not being filtered).
Am I missing something?
UPDATE:
How can I use get_wc_subscriptions?
require_once('woosync.php');
$sid = $_GET['sid'];
$parent = $_GET['parent'];
$woosync = new woosync();
$subscriptions = $woosync->get_wc_subscriptions($sid, $parent);
echo "<pre>";
print_r($subscriptions);
I'm trying to integrate a payment system of paypal on my webpage under Symfony. After some researches, I ran into Payum which is a apparently the best bundle for this feature.
The issue is that I don't really understand the doc so the final code I have doesn't work.
Somebody already used payum and could help me to understand it ?
I have for example : $paypalRestPaymentDetailsClass which comes from nowhere and I don't know what should be in this class
Here is my code :
namespace PlatformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Payum\Core\PayumBuilder;
use Payum\Core\Payum;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use Payum\Core\Request\GetHumanStatus;
class PayumController extends Controller
{
private function config()
{
return (new PayumBuilder())
->addDefaultStorages()
->addGateway('gatewayName', [
'factory' => 'paypal_rest',
'client_id' => 'REPLACE IT',
'client_secret' => 'REPLACE IT',
'config_path' => 'REPLACE IT',
])
->getPayum();
}
public function prepare()
{
$payum = $this->config();
$storage = $payum->getStorage($paypalRestPaymentDetailsClass);
$payment = $storage->create();
$storage->update($payment);
$payer = new Payer();
$payer->payment_method = "paypal";
$amount = new Amount();
$amount->currency = "USD";
$amount->total = "1.00";
$transaction = new Transaction();
$transaction->amount = $amount;
$transaction->description = "This is the payment description.";
$captureToken = $payum->getTokenFactory()->createCaptureToken('paypalRest', $payment, 'create_recurring_payment.php');
$redirectUrls = new RedirectUrls();
$redirectUrls->return_url = $captureToken->getTargetUrl();
$redirectUrls->cancel_url = $captureToken->getTargetUrl();
$payment->intent = "sale";
$payment->payer = $payer;
$payment->redirect_urls = $redirectUrls;
$payment->transactions = array($transaction);
$storage->update($payment);
header("Location: ".$captureToken->getTargetUrl());
}
public function capture()
{
$payum = $this->config();
$token = $payum->getHttpRequestVerifier()->verify($_REQUEST);
$gateway = $payum->getGateway($token->getGatewayName());
if ($reply = $gateway->execute(new Capture($token), true)) {
if ($reply instanceof HttpRedirect) {
header("Location: ".$reply->getUrl());
die();
}
throw new \LogicException('Unsupported reply', null, $reply);
}
$payum->getHttpRequestVerifier()->invalidate($token);
header("Location: ".$token->getAfterUrl());
}
public function done()
{
$payum = $this->config();
$token = $payum->getHttpRequestVerifier()->verify($_REQUEST);
$gateway = $payum->getGateway($token->getGatewayName());
// you can invalidate the token. The url could not be requested any more.
// $payum->getHttpRequestVerifier()->invalidate($token);
// Once you have token you can get the model from the storage directly.
//$identity = $token->getDetails();
//$payment = $payum->getStorage($identity->getClass())->find($identity);
// or Payum can fetch the model for you while executing a request (Preferred).
$gateway->execute($status = new GetHumanStatus($token));
$payment = $status->getFirstModel();
header('Content-Type: application/json');
echo json_encode(array(
'status' => $status->getValue(),
'order' => array(
'total_amount' => $payment->getTotalAmount(),
'currency_code' => $payment->getCurrencyCode(),
'details' => $payment->getDetails(),
),
));
}
}
Thanks
The code below is a custom report I'm putting together, using SilverStripe 3.1.
The Title and ClassName values are working fine, but though I can get the Status for each Page I'm not sure how to set the Status value against each Page in the DataList. How can I do that?
Once that's done, the Status column should be populated.
class PageListByType extends SS_Report {
function title() {
return 'Page List by Type';
}
function description() {
return 'List all the pages in the site, along with their page type';
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
$pages = Page::get()->sort($sort);
foreach ($pages as $pagenum=>$page) {
$flags = $page->getStatusFlags();
if ($flags) {
foreach ($flags as $status) {
// if (isset($pages[$pagenum]->Status)) die(array($pages[$pagenum]->Status, $status)); #detect multiple statuses; not sure if this will happen
/////////////////////////
// The following line needs fixing:
/////////////////////////
$pages[$pagenum]->Status = "{$status['text']} ({$status['title']})";
}
}
}
// die($pages->debug());
return $pages;
}
public function columns() {
return array(
'Title' => _t('PageListByTypeReport.PageName', 'Page name'),
'ClassName' => _t('PageListByTypeReport.ClassName', 'Page type'),
'Status' => _t('PageListByTypeReport.Status', 'Status')
);
}
}
Edit: Thanks #Turnerj for your answer! My final working code is as follows:
class PageListByType extends SS_Report {
function title() {
return 'Page List by Type';
}
function description() {
return 'List all the pages in the site, along with their page type';
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
$pages = DataObject::get("SiteTree", "", "");
return $pages;
}
public function columns() {
return array(
'Title' => _t('PageListByTypeReport.PageName', 'Page name'),
'ClassName' => _t('PageListByTypeReport.ClassName', 'Page type'),
'Status' => _t('PageListByTypeReport.Status', 'Status')
);
}
}
and in Page.php:
public function getStatus() {
$flags = $this->getStatusFlags();
$result = array();
if ($flags) {
foreach ($flags as $status) {
$result[] = "{$status['text']} ({$status['title']})";
}
} else {
$result[] = 'Published';
}
return implode(', ', $result);
}
After further investigation, I recreated the issue and found the solution.
Overall, my solution involves what I suggested in the comments about bringing the status fetching to the actual Page by adding a getStatus function.
I described essentially the following:
public function getStatus()
{
return $this->getStatusFlags();
}
This technically is correct, it will get the status flags but you are right, it doesn't display them in the report. This is due to this function returning an array which the report does not understand to render.
My solution is to change this function to return a string so with a few simple edits combining what you wrote with what I wrote, we get the following:
public function getStatus()
{
$flags = $this->getStatusFlags();
$result = array();
if ($flags)
{
foreach ($flags as $status)
{
$result[] = "{$status['text']} ({$status['title']})";
}
}
return implode(', ', $result);
}
I've got one unique twist on combining our code, I add each status to an array and implode it back to a single string. This can seem a little excessive, by default getStatusFlag will return one key in the array. If however you have a DataExtension that has the updateStatusFlags method, you could add additional keys to the result.
Basically, I would leave the implode handling in if in the future you do have code that messes with the status flags.
Now, you might be able to do something similar using the $casting property on the Page but given you were essentially adding this function just for the report, it was cleaner to just update it directly.
I did notice that the status flags array is actually empty if the page is published which means your report won't have anything next to published pages. If that is your intention, great!
If not, you could do another little alteration:
public function getStatus()
{
$flags = $this->getStatusFlags();
$result = array();
if ($flags)
{
foreach ($flags as $status)
{
$result[] = "{$status['text']} ({$status['title']})";
}
}
else
{
$result[] = 'Published (The page has been published)';
}
return implode(', ', $result);
}
The if ($flags) will evaluate to false when there are no current statuses (aka. the page is published) due to automatic casting.
Have you tried with an anonymous function inside columns()?
class PageListByType extends SS_Report {
function title() {
return 'Page List by Type';
}
function description() {
return 'List all the pages in the site, along with their page type';
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
return Page::get()->sort($sort);
}
public function columns() {
return array(
'Title' => _t('PageListByTypeReport.PageName', 'Page name'),
'ClassName' => _t('PageListByTypeReport.ClassName', 'Page type'),
'Status' => array(
'title'=>_t('PageListByTypeReport.Status', 'Status'),
'formatting' => function($value, $item) {
$flags = $item->getStatusFlags();
$status = '';
if ($flags) {
foreach ($flags as $status) {
$status = "{$status['text']} ({$status['title']})";
}
}
return $status ? : _t('PageListByTypeReport.PagePublished', 'Page published');
}
)
);
}
}
Here is my custom module using hook,
Assume if I want to pass argument to custom1_default_form function call, how should i pass the argument?
<?php
function custom1_block($op,$delta=0){
if($op=='list'){
$block = array();
$block[0]['info']=t('hello world');
return $block;
}else if($op=='view'){
$block_content = '<p>THIS IS MY FIRST BLOCK</p>';
$block['subject'] = 'HELLO WORLD';
$block['content'] =drupal_get_form('custom1_default_form');
return $block;
}
}
function custom1_default_form () {
$form = array();
$form['nusoap_urls']['txt_name'] =
array('#type' => 'textfield',
'#title' => t('Please enter your name'),
'#default_value' => variable_get('webservice_user_url',''),
'#maxlength' => '40',
'#size' => '20',
// '#description' => t('<br />Root directory used to present the filebrowser user interface.')
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save Details'),
);
return $form;
}
function custom1_default_form_validate (&$form, &$form_state) {
if(($form_state['values']['txt_name']) == '') {
form_set_error('user_webservice', t('Enter a name'));
}
}
function custom1_default_form_submit ($form_id, $form_values) {
// drupal_set_message( print_r($_POST));
// $message = 'You have submitted the ' . $form_id . ' form which contains the following data:<pre>' . print_r($form_state['values'],true) . '</pre>';
//drupal_set_message(t($message));
//drupal_set_message(t($form_values['values']['txt_name']));
// print_r($form_values['values']);
$GET_TXT_FIELD_VALUE = $form_values['values']['txt_name'];
$INSERT_QUERY = "INSERT INTO sample (test_name) VALUES ('$GET_TXT_FIELD_VALUE')";
if (db_result(db_query("SELECT COUNT(*) FROM {sample} WHERE test_name = '%s';", $GET_TXT_FIELD_VALUE))) {
// User doesn't exist
drupal_set_message(t('ALREADY EXIST.....'));
}else{
db_query($INSERT_QUERY)or die('Execution Failed');
if(db_affected_rows()==1){
drupal_set_message(t('VALUE INSERTED SUCCESSFULLY'));
}else{
drupal_set_message(t('VALUE INSERTED FAILED'));
}
}
}
If you want to pass an argument via the URL, use arg():
function custom1_default_form() {
// Assuming the URL is http://example.com/admin/content/types:
$arg1 = arg(1); // $arg1 = 'content'
$arg2 = arg(2); // $arg2 = 'types'
// ...
}
If you just want to pass an argument to the form via the drupal_get_form() call, just add the arguments as additional parameters to drupal_get_form():
$block['content'] = drupal_get_form('custom1_default_form', $arg1, $arg2);
// ...
function custom1_default_form($form_state, $arg1, $arg2) {
// ...
}
I have found that in Drupal 6.20 you should add a dummy argument to the callback function definition:
$block['content'] = drupal_get_form('custom1_default_form', $arg1, $arg2);
// ...
function custom1_default_form($dummy, $arg1, $arg2) { // look at what gets stored in $dummy
// ...
}
avoid the using of arg() functions when possible:
Avoid use of this function where possible, as resulting code is hard
to read. In menu callback functions, attempt to use named arguments.
See the explanation in menu.inc for how to construct callbacks that
take arguments. When attempting to use this function to load an
element from the current path, e.g. loading the node on a node page,
use menu_get_object() instead.