Yii2 : Getting unknown property when using findBySql - mysql

i'm using findBySql() to get data from database,
i want to show the data in view with table.
This is code on my controller :
$sql = "SELECT presensi.presensi_tanggal 'tanggal', sum(if( hadir.keteranganhadir_id='1',1,0)) 'hadir', sum(if( hadir.keteranganhadir_id='2',1,0)) 'tidak_hadir', count(*) 'total' FROM hadir, keteranganhadir, presensi where hadir.keteranganhadir_id = keteranganhadir.keteranganhadir_id and hadir.presensi_id = presensi.presensi_id group by presensi.presensi_tanggal";
$model = Hadir::findBySql($sql)->all();
return $this->render('index', [
'hadir' => $model,
]);
So, i want to show 'tanggal', 'hadir', 'tidak hadir' and 'total'.
In my view,
<?php foreach($hadir as $data): ?>
<tr>
<td></td>
<td class="tbl_column_name"><?=$data->tanggal;?></td>
<td class="tbl_column_name"><?=$data->hadir;?></td>
<td class="tbl_column_name"><?=$data->tidak_hadir;?></td>
<td class="tbl_column_name"><?=$data->total;?></td>
<td>Lihat</td>
</tr>
<?php endforeach; ?>
But, i got error like this
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: common\models\data\Hadir::tanggal.
So, what is the problem and what should i do? Thank you~
[EDITED]
Hadir Model :
<?php
namespace common\models\data;
use Yii;
/**
* This is the model class for table "hadir".
*
* #property integer $ADIKBINAAN_ID
* #property integer $PRESENSI_ID
* #property integer $KETERANGANHADIR_ID
*
* #property Adikbinaan $aDIKBINAAN
* #property Presensi $pRESENSI
*/
class Hadir extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'hadir';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['ADIKBINAAN_ID', 'PRESENSI_ID', 'KETERANGANHADIR_ID'], 'required'],
[['ADIKBINAAN_ID', 'PRESENSI_ID', 'KETERANGANHADIR_ID'], 'integer']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'ADIKBINAAN_ID' => 'Adikbinaan ID',
'PRESENSI_ID' => 'Presensi ID',
'KETERANGANHADIR_ID' => 'Keteranganhadir ID',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getADIKBINAAN()
{
return $this->hasOne(Adikbinaan::className(), ['ADIKBINAAN_ID' => 'ADIKBINAAN_ID']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPRESENSI()
{
return $this->hasOne(Presensi::className(), ['PRESENSI_ID' => 'PRESENSI_ID']);
}
}

By default the attributes that are extracted from the returned rows are only the columns that can be found in the table.
I get the impression from your code that those fields are not. To fix this you should probably override the attributes()-function and declare those properties as valid:
public function attributes()
{
return array_merge(parent::attributes(), ['tanggal', 'hadir', 'tidak_hadir', 'total']);
}
This should instruct the populateRecord()-function to also fill those.

Related

Yii2 Multilingual. Can't reach the fields from the translation table

I installed OmgDef/Multilingual via composer. Did everything step by step from the guide. The error that I get now is:
Getting unknown property: backend\models\PageAdminSearch::title
I added joinWith('translation') but nothing changes.This is my PageAdmin model and PageAdminSearch
PageAdmin:
<?php
namespace backend\models;
use omgdef\multilingual\MultilingualBehavior;
use omgdef\multilingual\MultilingualQuery;
use Yii;
/**
* This is the model class for table "page_admin".
*
* #property int $id
* #property int $id_in
* #property int $enable
* #property string $icon
*/
class PageAdmin extends \yii\db\ActiveRecord
{
public static function find()
{
return new MultilingualQuery(get_called_class());
}
public function behaviors()
{
$allLanguages = [];
foreach (Yii::$app->params['languages'] as $title => $language) {
$allLanguages[$title] = $language;
}
return [
'ml' => [
'class' => MultilingualBehavior::className(),
'languages' => $allLanguages,
//'languageField' => 'language',
//'localizedPrefix' => '',
//'requireTranslations' => false',
//'dynamicLangClass' => true',
//'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
'defaultLanguage' => Yii::$app->params['languageDefault'],
'langForeignKey' => 'page_id',
'tableName' => "{{%page_adminlang}}",
'attributes' => [
'title',
'content',
]
],
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'page_admin';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['icon'], 'string'],
[['id_in', 'enable'], 'integer']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'id_in' => Yii::t('app', 'Id In'),
'icon' => Yii::t('app', 'Icon'),
];
}
}
PageAdminSearch:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\PageAdmin;
/**
* PageAdminSearch represents the model behind the search form of `backend\models\PageAdmin`.
*/
class PageAdminSearch extends PageAdmin
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'id_in'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = PageAdmin::find()->joinWith('translations');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'id_in' => $this->id_in,
]);
$query->andFilterWhere(['like', 'title', $this->title]);
return $dataProvider;
}
}
languageDefault is bg. Did someone have the same problem? The explanation is not pretty big but I think the problem is clear enough :) Appreciate every advice!
Haven't used it tho but looking at your code you are adding a joinWith inside the search() function in the model, are you searching any field with name title inside the translations table using some gridview or search form
If that is so you need to declare a custom attribute inside your searchModel and add it to the safe rules and then use it because you are getting an error at the line
$query->andFilterWhere(['like', 'title', $this->title]);
so add a custom attribute on top of your PageAdminSearch
public $title
And it is always good to use an alias for the relation
$query = PageAdmin::find()
->joinWith(['translations'=>function($q){
$q->from('{{%transalations}} tr');
}]);
then update your rules to the following
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'id_in'], 'integer'],
[['title'],'safe'],
];
}
and change the line to the following
$query->andFilterWhere(['like', 'tr.title', $this->title]);
Now run it won't show you the error.

Laravel 5.3 - Data inserting issue in MySQL 5.7.1

While inserting data from Laravel 5.3 it doesn't show up in the MySQL 5.7.1 database. I was following a tutorial, the teacher was using Laravel 5.2 Is that an issue?
Any help would be appreciated.
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'body' => 'required'
));
// store in the database
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
// Session::flash('success', 'The blog post was successfully save!');
return redirect()->route('posts.show', $post->id);
}
Adding the whole code here...
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts.index')->withPosts($posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'body' => 'required'
));
// store in the database
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect()->route('posts.show', $post->id);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->withPost($post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Make sure your $fillable array is populated.
<?php
namespace App;
class Post extends Model
{
protected $fillable = ['title', 'body'];
...
}

How to add a rule that checks if date given is past 6 days old?

I'm using yii2 basic, i'm trying to add a rule which will compare the date given by the user and give and error if it's older than 6 days.
How would i go about doing this? I'm using datepicker to input the date right now, the format i'm using is: format' => 'd-mm-yyyy
Model.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "invoices".
*
* #property integer $id
* #property string $invoice_number
* #property string $invoice_loadamount
* #property string $invoice_date
* #property integer $archive_id
* #property string $DateProcessed
*
* #property Archive $archive
*/
class Invoices extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'invoices';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['invoice_number', 'invoice_loadamount', 'invoice_date'], 'required'],
[['archive_id', 'invoice_number', 'invoice_loadamount'], 'integer'],
[['DateProcessed'], 'safe'],
[['invoice_number', 'invoice_loadamount', 'invoice_date'], 'string', 'max' => 100],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'invoice_number' => 'Invoice Number',
'invoice_loadamount' => 'Invoice Loadamount',
'invoice_date' => 'Invoice Date',
'archive_id' => 'Archive ID',
'DateProcessed' => 'Date Processed'];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getArchive()
{
return $this->hasOne(Archive::className(), ['id' => 'archive_id']);
}
}
You can use the core date validator with:
min property specifying the lower limit of the accepted date-range.
format property to indicate which date-format is used
Add something along these lines:
[['DateProcessed'], 'date', 'format' => "dd-MM-yyyy", 'min' => date("d-m-Y", strtotime('-6 days'))],

How to create nested objects with FOSRestBundle and FormType?

I'm developing an API with symfony2 + FOSRestBundle and I have two errors.
Below is my code:
Property
/**
* Property
*
* #ORM\Table(name="property")
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({"house" = "House"})
*/
abstract class Property {
/**
* #ORM\OneToMany(targetEntity="Image", mappedBy="property", cascade={"persist"})
* */
private $images;
function getImages() {
return $this->images;
}
function setImages($images) {
$this->images = $images;
}
}
House
class House extends Property
{
/* More code */
}
Image
class Image {
/**
* #ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* #ORM\ManyToOne(targetEntity="Property", inversedBy="images")
* #ORM\JoinColumn(name="propertyId", referencedColumnName="id")
* */
private $property;
}
PropertyType
class PropertyType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('images');
$builder->get('images')
->addModelTransformer(new CallbackTransformer(
function($images) {
$image = new \Cboujon\PropertyBundle\Entity\Image();
$image->setContent('test of content');
return array($image);
}, function($imagesContents) {
}));
}
HouseRESTController
/**
* #View(statusCode=201, serializerEnableMaxDepthChecks=true)
*
* #param Request $request
*
* #return Response
*
*/
public function postAction(Request $request)
{
$entity = new House();
$form = $this->createForm(new HouseType(), $entity, array("method" => $request->getMethod()));
$this->removeExtraFields($request, $form);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $entity;
}
When I create a new house, I send this (simplified) JSON:
{"images":["base64ContentImage_1", "base64ContentImage_2"]}
First Problem: The $images parameter in the first function passed to the CallbackTransformer is NULL. Why?
Second problem: I order to test and understand the first problem, I forced to create an image entity as you can see but I get a JSON response with the error "Entities passed to the choice field must be managed. Maybe persist them in the entity manager?"
Can anyone help me to solve any of two problem?
I have found one solution
I have been created ImageType
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('content')
;
}
And also I have been modified PropertyType
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title')
->add('description')
->add('price')
->add('services')
->add('images', 'collection', array(
'type' => new ImageType(),
'allow_add' => true,
))
;
}
And finally, I was changed the JSON structure of my request:
{"images":[{content: "base64ContentImage_1"}, {content:"base64ContentImage_2"}]}

Yii2 - Unable to find 'app\models\User' in file: backend/models/User.php. Namespace missing? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I used both namespace in this file backend/models/User.php
When I use namespace app\models; It shows Unable to find 'backend\models\User'.
If I use namespace backend\models; It shows Unable to find 'app\models\User'
<?php
//namespace app\models;
namespace backend\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_USER = 10;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'admin';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
['role', 'default', 'value' => self::ROLE_USER],
['role', 'in', 'range' => [self::ROLE_USER]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
I think your problem is, that you have two different models and try to use them both in one namespace, but this won't work.
You can alias one namespace, so you can use both different models.
eg.:
<?php
namespace app\models;
// there exist a model "User"
// and you wanna use also the User model under common\models\
use common\models\User as CUser;
Another solution is to prefixing the namespace to the model like
<?php
namespace app\models;
$cuser = new \common\models\User();
see PHP Namespaces explained