Drupal Pressflow problem with hook_block - drupal-6

i'm having troubles with implementing the hook_block hook in a clean Pressflow installation. For some reason it always outputs ArrayArray for all my blocks. The reason for this is that the $info variable in the theme function is set to:
["block"]=>
array(7) {
["function"]=>
string(10) "fwtb_block"
["include files"]=>
array(0) {
}
["type"]=>
string(12) "theme_engine"
["theme path"]=>
string(21) "sites/all/themes/fwtb"
["arguments"]=>
array(1) {
["block"]=>
NULL
}
["theme paths"]=>
array(2) {
[0]=>
string(14) "modules/system"
[1]=>
string(21) "sites/all/themes/fwtb"
}
["preprocess functions"]=>
array(2) {
[0]=>
string(19) "template_preprocess"
[1]=>
string(25) "template_preprocess_block"
}
}
as you can see this is overwritten with my custom hook_block method. So now it thinks blocks should be rendered using my fwtb_block method which returns an array containing the subject and the content. That's why it prints ArrayArray. Any idea what is going wrong here?
This is my hook_block implementation:
function fwtb_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks['sidebar_description'] = array(
'info' => t('Sidebar description'),
'cache' => BLOCK_CACHE_GLOBAL,
'status' => TRUE,
'region' => 'left',
'visibility' => 0,
'custom' => FALSE
);
return $blocks;
case 'configure':
$form = array();
return $form;
case 'save':
return;
case 'view': default:
switch ($delta) {
case 'sidebar_description':
$block['subject'] = t('block_subject');
$block['content'] = t('block_description');
break;
}
return $block;
}
}
kind regards,
Daan

After taking a fresh look to my setup i saw what the problem was. I had a theme and a module with the same name. This caused some conflicts :/

Related

Dart Map and Parsing JSON

As a new Dart Fan, I would like to understand the concept of Map/List.
I tried to do HTTP requests, getting JSON data. And it's ok till I have to assign to the Map.
Let me show you the example of JSON data:
{
"error":"",
"error_number":"",
"response_code":200,
"result":[
{
"id":1,
"name":"Great Deal",
"day_aired":"2015-07-05 11:06:09",
"trend":"Noone",
"trend_details": [{
"name":"Great Deal",
}
]
},
{
"id":2,
....
}
]
}
The code:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<ApiResponse> fetchData(String command, Map params) async {
final String url =
'https://example.com/api/v2/....';
final response = await http.get(url);
if (response.statusCode == 200) {
return ApiResponse.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
}
final response = await http.get(url);
dynamic data = json.decode(response.body);
List<String> parsed = data['result'] as List<String>;
// List<String> parsedList = new List<String>.from(parsed);
if (response.statusCode == 200) {
//return json.decode(response.body);
List<ApiResponse> list = List<ApiResponse>.from(
parsed.map((i) => ApiResponse.fromJson(i as Map<String, dynamic>)));
}
I do the same as this article. But I read this article too. I'm trying to create Future<ApiResponse> with data from json.decode(response.body) (result entry inside of it).
factory ApiResponse.fromJson(Map<String, dynamic> json) {...}
But as I understand, result is not Map<String, dynamic> but when I try to invoke the code below it says:
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast and it referred to List<String> parsed = data['result'] as List<String>;.
I'm confused and I know the code is a mess. I read in the second article that I should do an additional cast to trend_details but it did not work as I expected. Obviously data['result'] is an array but how to cast it properly? What are the good practices?
result stores a list of Map<String, dynamic>
final parsed = data['result'] as List<Map<String, dynamic>>;
You can parse json string with the following structure and code
You can see picture display correct result name
code snippet
var payload = payloadFromJson(jsonStr);
print('${payload.result[0].name}');
related class
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String error;
String errorNumber;
int responseCode;
List<Result> result;
Payload({
this.error,
this.errorNumber,
this.responseCode,
this.result,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
error: json["error"] == null ? null : json["error"],
errorNumber: json["error_number"] == null ? null : json["error_number"],
responseCode: json["response_code"] == null ? null : json["response_code"],
result: json["result"] == null ? null : List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error == null ? null : error,
"error_number": errorNumber == null ? null : errorNumber,
"response_code": responseCode == null ? null : responseCode,
"result": result == null ? null : List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
int id;
String name;
DateTime dayAired;
String trend;
List<TrendDetail> trendDetails;
Result({
this.id,
this.name,
this.dayAired,
this.trend,
this.trendDetails,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
dayAired: json["day_aired"] == null ? null : DateTime.parse(json["day_aired"]),
trend: json["trend"] == null ? null : json["trend"],
trendDetails: json["trend_details"] == null ? null : List<TrendDetail>.from(json["trend_details"].map((x) => TrendDetail.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
"day_aired": dayAired == null ? null : dayAired.toIso8601String(),
"trend": trend == null ? null : trend,
"trend_details": trendDetails == null ? null : List<dynamic>.from(trendDetails.map((x) => x.toJson())),
};
}
class TrendDetail {
String name;
TrendDetail({
this.name,
});
factory TrendDetail.fromJson(Map<String, dynamic> json) => TrendDetail(
name: json["name"] == null ? null : json["name"],
);
Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
};
}
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String error;
String errorNumber;
int responseCode;
List<Result> result;
Payload({
this.error,
this.errorNumber,
this.responseCode,
this.result,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
error: json["error"] == null ? null : json["error"],
errorNumber: json["error_number"] == null ? null : json["error_number"],
responseCode: json["response_code"] == null ? null : json["response_code"],
result: json["result"] == null ? null : List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error == null ? null : error,
"error_number": errorNumber == null ? null : errorNumber,
"response_code": responseCode == null ? null : responseCode,
"result": result == null ? null : List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
int id;
String name;
DateTime dayAired;
String trend;
List<TrendDetail> trendDetails;
Result({
this.id,
this.name,
this.dayAired,
this.trend,
this.trendDetails,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
dayAired: json["day_aired"] == null ? null : DateTime.parse(json["day_aired"]),
trend: json["trend"] == null ? null : json["trend"],
trendDetails: json["trend_details"] == null ? null : List<TrendDetail>.from(json["trend_details"].map((x) => TrendDetail.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
"day_aired": dayAired == null ? null : dayAired.toIso8601String(),
"trend": trend == null ? null : trend,
"trend_details": trendDetails == null ? null : List<dynamic>.from(trendDetails.map((x) => x.toJson())),
};
}
class TrendDetail {
String name;
TrendDetail({
this.name,
});
factory TrendDetail.fromJson(Map<String, dynamic> json) => TrendDetail(
name: json["name"] == null ? null : json["name"],
);
Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonStr = '''
{
"error":"",
"error_number":"",
"response_code":200,
"result":[
{
"id":1,
"name":"Great Deal",
"day_aired":"2015-07-05 11:06:09",
"trend":"Noone",
"trend_details": [{
"name":"Great Deal"
}
]
}
]
}
''';
void _incrementCounter() {
var payload = payloadFromJson(jsonStr);
print('${payload.result[0].name}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

How get object from indices in Areablock?

I have Pimcore\Model\Document\Tag\Areablock with tree elements table of indices:
array(3) {
[0]=>
array(2) {
["key"]=>
string(1) "3"
["type"]=>
string(8) "newsData"
}
[1]=>
array(2) {
["key"]=>
string(1) "1"
["type"]=>
string(7) "wysiwyg"
}
[2]=>
array(2) {
["key"]=>
string(1) "2"
["type"]=>
string(12) "videogallery"
}
}
How could I get newsData object from Areablock object?
I coudn't find function in Areablock for that and don't know how to get date.
Thanks in advance.
Areabricks are not subelements of the actual areablock, but are direct elements of current document. Their names are just differently constructed.
$areablock = $this->areablock("yourAreablock");
foreach ($areablock->getData() as $brick) {
if ($brick["type"] == "yourAreaBrickName") {
$nameOfTheEditableInBrick = "bigtitle";
$indexOfTheAreaBrick = $brick["key"];
// This is your element
$subelement = $this->document->getElement($nameOfTheEditableInBrick . $areablock->getName() . $brick["key"]);
}
}

Search filter not working with custom search

I have a search() function in my model and I have messed around a bit with it in order to filter my results with some custom filters. So in my model I have this:
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$startdate='';
$enddate='';
if ($this->year!=''){
$year=explode('-', $this->year);
$date=DateTime::createFromFormat('Y', $year[0])->format('d/m/Y');
$startdate = General::getSeasonStartDate($date);
$enddate = General::getSeasonEndDate($date);
}
$criteria=new CDbCriteria;
$criteria->with=array(
'contracts'=>array(
'select'=>'contracts.contractdate',
'together'=>true
),
'schoolstudents' => array(
'together' => true,
'select' => false,
),
'schoolstudents.school'
);
//$criteria->order='lastname, firstname, fathername, mothername';
if (Yii::app()->user->CompanyID){
$criteria->compare('school.companyid',Yii::app()->user->CompanyID);
}
if(Yii::app()->user->SchoolID){
$criteria->compare('schoolstudents.schoolid',Yii::app()->user->SchoolID);
}
$criteria->compare('schoolstudents.schoolid', $this->schoolid);
//$criteria->compare('studentid',$this->studentid);
$criteria->compare('lastname',$this->lastname,true);
$criteria->compare('firstname',$this->firstname,true);
$criteria->compare('fathername',$this->fathername,true);
$criteria->compare('telephone1',$this->telephone1,true);
$criteria->compare('telephone2',$this->telephone2,true);
$criteria->compare('cellphone1',$this->cellphone1,true);
$criteria->compare('cellphone2',$this->cellphone2,true);
$criteria->compare('email1',$this->email1,true);
$criteria->compare('email2',$this->email2,true);
if($this->year!=''){
if ($startdate && $enddate){
$from = DateTime::createFromFormat('d/m/Y', $startdate)->format('Y-m-d');
$to = DateTime::createFromFormat('d/m/Y', $enddate)->format('Y-m-d');
if ($this->filter=='R'){
$criteria->addBetweenCondition('contractdate',$from, $to, 'AND');
}
else {
$criteria->addBetweenCondition('schoolstudents.createddate',$from, $to, 'AND');
}
}
} else {
if ($this->filter=='R'){
$criteria->addCondition('contracts.studentid');
} else {
$criteria->addCondition('schoolstudents.studentid');
}
}
if(isset($this->birthdate))
{
if($this->birthdate!='') {
$criteria->addCondition('year(birthdate)=:birthdate');
$criteria->params=CMap::mergeArray($criteria->params,array(
':birthdate'=>$this->birthdate,
)
);
}
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'lastname asc',
),
'pagination'=>array(
'pageSize'=>50,
),
));
}
my controller looks like this:
public function actionAdmin()
{
$model=new Student('search');
$model->unsetAttributes();
$y=date('Y');
$y1=date('Y',strtotime($y.'+1 year'));
$test=$y.'-'.$y1;
$model->year=$test;
$model->filter='A';
if (isset($_GET['Student']['year'])){
$model->year=($_GET['Student']['year']);
}
if (isset($_GET['Student']['filter'])){
$model->filter=$_GET['Student']['filter'];
}
if(isset($_GET['Student']))
$model->attributes=$_GET['Student'];
$this->render('admin',array(
'model'=>$model,
));
}
and my problem is that when I use the search filters provided by Yii they don't work. I don't get an error. They don't return anything. If I remove from search() the extra conditions I've added then the filters work fine. But then I can't use my custom filters. Anybody has any idea how to solve this?Thanks in advance!
Never mind I solved it. I changed my controller to this:
public function actionAdmin()
{
$model=new Student('search');
$model->unsetAttributes();
$y=date('Y');
$y1=date('Y',strtotime($y.'+1 year'));
$test=$y.'-'.$y1;
if (isset($_GET['Student']['year'])){
$model->year=$_GET['Student']['year'];
}
if (isset($_GET['Student']['filter'])){
$model->filter=$_GET['Student']['filter'];
}
if(isset($_GET['Student'])){
$model->attributes=$_GET['Student'];
} else{
//for custom & ajax filters to work together
$model->year=$test;
$model->filter='A';
}
$this->render('admin',array(
'model'=>$model,
));

Polymer Clone Objects

How can we clone an object in Polymer?
Example
this.colorsAsc.push({color: 'red'});
this.colorsDesc = this.colorsAsc.reverse();
this.colorsDesc[0].color = 'blue'; // Both will be blue doing this
I can do it in these many functionalities What is the most efficient way to deep clone an object in JavaScript? but I wonder if there is a way in Polymer to do that?
Angular does it https://docs.angularjs.org/api/ng/function/angular.copy
You can try the following hack:
this.colorsDesc = JSON.parse(JSON.stringify(this.colorsAsc.reverse());
I have had the same question here, where I have finally also found and posted an answer.
Short version:
newElement = element.cloneNode(true);
for(var i in element.properties) {
newElement[i] = element[i]
}
To clone a utility via Polymer
Full implementation:
(function(callBackFn) {
Polymer({
//Component Name
is: 'my-cloner',
properties: {
//Declare a published property
cloneableObject: { //Placeholder for Object to be cloned
reflectToAttribute: true,
type: Object,
notify: true
}
},
attached: function() {
//Hide if this component got attached
this.hidden = true;
},
getClone: function(incomingcloneableObject) { //Will be called to get the Clone
this.cloneableObject = this.cloneableObject || incomingcloneableObject;
switch (typeof this.cloneableObject) {
case "undefined":
return null;
break;
case "object":
var localClone = this.cloneNode();
return (localClone.cloneableObject);
break;
case "boolean":
return new Boolean(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject ? true : false);
break;
case "number": //NaN is taken care of
return new Number(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject * 1);
break;
case "string":
return new String(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject + '');
break;
default:
return null;
}
}
});
//adding Util into window
callBackFn();
})(function() {
window.cloneUtil = document.createElement('my-cloner');
});
//To use this util
//window.cloneUtil.getClone();

kohana 3 incorporate file validate in orm

I cant figure out how to add file validation code to the orm model
As the code is now the text inputs are validated in the orm, but the file has no validation on it at all. I was wondering if it was possible to merge the file validation in the 'profile' model where I have the text validation?
Here is the code in my controller
public function action_public_edit()
{
$content = View::factory('profile/public_edit')
->bind('user', $user)
->bind('profile', $profile)
->bind('errors', $errors);
$user = Auth::instance()->get_user();
$profile = $user->profiles;
$this->template->content = $content;
if ($_POST)
{
if ($profile->values($_POST)->check())
{
$picture = Upload::save($_FILES['profile_picture']);
// Resize, sharpen, and save the image
Image::factory($picture)
->resize(100, 100, Image::WIDTH)
->save();
$profile->profile_picture = basename($picture);
$profile->save();
$redirect = "profile/private";
Request::instance()->redirect($redirect);
}
else
{
$errors = $profile->validate()->errors('profile/public_edit');
}
}
}
And the ORM model
protected $_belongs_to = array('user' => array());
protected $_rules = array(
'first_name' => array(
'not_empty' => NULL,
),
'last_name' => array(
'not_empty' => NULL,
),
You don't need to check() if you save() later - save will do the checking and throw ORM_Validation_Exception if validation is not passed. I suggest to create a function in your model for saving - move the lines after check() to this model. In controller you'll only need to write:
if ($this->request->method() === 'POST')
{
$errors = $profile->upload('profile_picture');
if (empty($errors))
{
try
{
$profile->your_save_function();
$this->request->redirect('profile/private');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors('profile');
}
}
}
In your model:
public function your_save_function()
{
// Do your stuff before uploading the picture
// Save the model
$this->save();
}
public function upload($filename)
{
// Set the default upload directory
Upload::$default_directory = 'your_path';
// Validate the file first
$validation = Validation::factory($_FILES)
->rules($filename, array(
array('not_empty'),
array('Upload::not_empty'),
array('Upload::valid'),
array('Upload::type', array(':value', array('your_valid_extensions'))),
array('Upload::size', array(':value', 'your_max_size')),
));
// Validate and upload OK
if ($validation->check())
{
$picture = Upload::save($_FILES[$filename]);
// Resize, sharpen, and save the image
Image::factory($picture)
->resize(100, 100, Image::WIDTH)
->save();
$this->profile_picture = basename($picture);
}
else
{
return $validation->errors('upload');
}
}
Much simpler and cleaner code.

Resources