Silverstripe TimeField - Hide Seconds - silverstripe

Is there a way to hide seconds from the TimeField in the silverstripe CMS?
static $db = array (
'StartTime' => 'Time',
'EndTime' => 'Time',
);
public function getCMSFields() {
$f = new FieldList(
new TimeField('StartTime', _t('CalendarDateTime.STARTTIME','Start time')),
new TimeField('EndTime', _t('CalendarDateTime.ENDTIME','End time')),
return $f;
}

$myTimeField->setConfig('timeformat', 'HH:mm'); - see TimeField API docs.

Related

Running a report on a GA4 property using segments with google-analytics-api

I know that segments are not supported in the current v1Beta api (https://analyticsdata.googleapis.com/v1beta/properties/{property_id}:runReport).
Is there a workaround to get segmented data from using this api?
Reference: https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport
I was working with google analytics API GA4 using PHP hope this helps you
<?php
class analytics{
private $property_id =null;
private $client = null;
public $propertys;
public function setPropertyId($propertyid)
{
return $this->property_id = $propertyid;
}
private function getCredentials()
{
return DIR.'PATH/credentials.json');
}
private function getClient(): BetaAnalyticsDataClient
{
return $this->client= new BetaAnalyticsDataClient([
'credentials' => $this->getCredentials(),
]);
}
public function get($propertyid,$startdate,$enddate,dimensions,$metrics)
{
$response = $this->getClient()->runReport([
'property' => 'properties/' . $this->setPropertyId($propertyid),
'dateRanges' => [
new DateRange([
'start_date' => $startdate,
'end_date' => $enddate,
]),
],
'dimensions' => [new Dimension(
[
'name' => $dimensions,
]
),
],
'metrics' => [new Metric(
[
'name' => $metrics,
]
)
]
]);
foreach ($response->getRows() as $row) {
return $row->getMetricValues()[0]->getValue();
}
}
}
then you can use the get function with dates range and dimensions metrics you want

Show only country_id =1 in list (Symfony + Sonata)

This is my simple listing of the "News" entity
protected function configureListFields(ListMapper $list): void
{
$list
->filte
->add('id')
->add('name')
->add('description')
->add('createdAt')
->add('updatedAt')
->add(ListMapper::NAME_ACTIONS, null, [
'actions' => [
'show' => [],
'edit' => [],
'delete' => []
],
]);
}
The News entity also has a country_id field (I won't show).
I need show only the news with country_id = 1.
How?
Ok, I solved with documentation
protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
{
$query = parent::configureQuery($query);
$rootAlias = current($query->getRootAliases());
$query->andWhere(
$query->expr()->eq($rootAlias . '.my_field', ':my_param')
);
$query->setParameter('my_param', 'my_value');
return $query;
}
But need made several changes beacuse $query not is a QueryBuilder Object.
protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
{
$query = parent::configureQuery($query);
$query_qb = $query->getQueryBuilder();
$rootAlias = current($query->getQueryBuilder()->getRootAliases());
$query_qb->andWhere(
$query_qb->expr()->eq($rootAlias . '.idCountry', ':idCountry')
);
$query_qb->setParameter('idCountry', $this->security->getUser()->getCountry()->getId());
return $query;
}

How to execute a Drupal-view in a custom module and print the output (as html-markup)?

I want to print the output from a simple view in my custom module. But is doesnt work. I have tried many options from forums and stackoverflow. All of them print "array" instead of html-markup.
My controller:
class DefaultController extends ControllerBase {
public function myfunc1() {
$view = Views::getView('myfirstview');
$view->setDisplay('page_1');
$view->preExecute();
$view->execute();
// $myresults = $view->preview(); = array
// $myresults = $view->render(); = array
$myresults = $view->result; // = array
return array(
'#title' => 'Hello World!',
'#markup' => $myresults,
);
}
}
How can I print the result/output of a view programmatically?
I dont want to make it without "embed view" , because I want to set some exposed filters later.
get the view
$corresponding_view = Views::getView('myfirstview');
set exposed filters
$arguments = your arguments (exposed filter value);
$corresponding_view->setArguments($arguments);
embed your view
return [
'#type' => 'view',
'#name' => 'myfirstview',
'#view' => $corresponding_view,
'#display_id' => 'page_1',
'#embed' => TRUE,
];

display titles from many_many relation in GridField - Silverstripe

How can I display the titles from a many_many relation in a GridField Summary?
I tried it with RelationName.Title but the result was only an empty field
there should be a couple solutions:
defining $summary_fields on the DataObject that is linked:
private static $summary_fields = array(
'YourFieldName',
'AnotherField'
);
or with the GridFieldConfig on the Page/DataObject that defines the relation:
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'FieldName' => 'GridFieldColumnName',
'AnotherFieldName' => 'AnotherGridFieldColumnName',
));
$config being your GridFieldConfig instance used by GridField.
EDIT
for more advanced formatting/control over the data included in the GridField, you can use setFieldFormatting:
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'TeamLink' => 'Edit teams'
));
$config->getComponentByType('GridFieldDataColumns')->setFieldFormatting(array(
'TeamLink' => function($value, $item)
{
// $item here would be a TeamMember instance
// since the GridField displays TeamMembers
$links = 'No teams';
$teamModelAdminClass = 'TeamModelAdmin'; //change to your classname
$teams = $item->Teams(); // get the teams
if ( $teams->count() > 0 )
{
$links = '';
$teamClass = $teams->dataClass;
$teamAdminURL = Config::inst()->get($teamModelAdminClass, 'url_segment');
$teamEditAdminURL = 'admin/'.$teamAdminURL.'/'.$teamClass.'/EditForm/field/'.$teamClass.'/item/';
foreach($teams as $team)
{
$links .= 'Edit '.$team->Title.'<br/>';
}
}
return $links;
}
));
Here setFieldFormatting will output edit links to all teams that a TeamMember is part of in a TeamLink column defined by setDisplayFields (might not be the best example, but hope you get the idea, although not tested).
colymba's answer already said most of it, but in addition you can also specify a method in $summary_fields. This allows you to display image thumbnails in a GridField or as you need it, piece together your own string from the titles of a many_many relation.
class TeamMember extends DataObject {
private static $db = array(
'Title' => 'Text',
'Birthday' => 'Date',
);
private static $has_one = array(
'Photo' => 'Image'
);
private static $has_many = array(
'Teams' => 'Team'
);
private static $summary_fields = array(
'PhotoThumbnail',
'Title',
'Birthday',
'TeamsAsString',
);
public function getPhotoThumbnail() {
// display a thumbnail of the Image from the has_one relation
return $this->Photo() ? $this->Photo()->CroppedImage(50,50) : '';
}
public function getTeamsAsString() {
if (!$this->Teams()) {
return 'not in any Team';
}
return implode(', ', $this->Teams()->Column('Title'));
// or if one field is not enough for you, you can use a foreach loop:
// $teamsArray= array();
// foreach ($this->Teams() as $team) {
// $teamsArray[] = "{$team->ID} {$team->Title}";
// }
// return implode(', ', $teamsArray);
}
}
alternative you can, as colymba pointed out, also use setDisplayFields to use different fields on different grids

ZF2 Unit test album module returns routing issue

I am trying out the phpunit in the Zf2 album module. I encountered an error which states about routing.
Below is the debug information. It says 'Route with name "album" not found', but when I checked module.config.php in the album module folder, I see that is correctly set and in the browser the redirection to that route is working fine.
Album\Controller\AlbumControllerTest::testDeleteActionCanBeAccessed
Zend\Mvc\Router\Exception\RuntimeException: Route with name "album" not found
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Router\SimpleRouteStack.php:292
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Url.php:88
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\Plugin\Redirect.php:54
D:\www\zend2\module\Album\src\Album\Controller\AlbumController.php:80
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php:87
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:468
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php:208
D:\www\zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php:108
D:\www\zend2\tests\module\Album\src\Album\Controller\AlbumControllerTest.php:35
C:\wamp\bin\php\php5.4.3\phpunit:46
I understand that the issue in AlbumController.php line 80 is
return $this->redirect()->toRoute('album');
But not sure why it is not working. Any one has encountered and overcome such issues?
To avoid duplicate Code, you can load your Routes from Module Config:
$module = new \YourNameSpace\Module();
$config = $module->getConfig();
$route = \Zend\Mvc\Router\Http\Segment::factory($config['router']['routes']['Home']['options']);
$router = new \Zend\Mvc\Router\SimpleRouteStack();
$router->addRoute('Home', $route);
I hope it will save approx. 30 minutes of searching in the zend framework 2 code:
class AlbumControllerTest extends PHPUnit_Framework_TestCase
{
//...
protected function setUp()
{
$bootstrap = \Zend\Mvc\Application::init(include 'config/application.config.php');
$this->controller = new AlbumController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = $bootstrap->getMvcEvent();
$router = new \Zend\Mvc\Router\SimpleRouteStack();
$options = array(
'route' => '/album[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
);
$route = \Zend\Mvc\Router\Http\Segment::factory($options);
$router->addRoute('album', $route);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setEventManager($bootstrap->getEventManager());
$this->controller->setServiceLocator($bootstrap->getServiceManager());
}
}
Actually the easy way is to get the config data from the service manager:
$config = $serviceManager->get('Config');
Full code for the function setUp():
protected function setUp() {
$serviceManager = Bootstrap::getServiceManager();
$this -> controller = new AlbumController();
$this -> request = new Request();
$this -> routeMatch = new RouteMatch(
array(
'controller' => 'index',
)
);
$this -> event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this -> event -> setRouter($router);
$this -> event -> setRouteMatch($this -> routeMatch);
$this -> controller -> setEvent($this -> event);
$this -> controller -> setServiceLocator($serviceManager);
}

Resources