Error when trying to display page in JSON format - json

I have this error when trying to display page in JSON format but with the html format it works fine
An exception occurred while executing
'SELECT t0.id AS id1, t0.libProjet AS libProjet2, t0.site AS site3, t0.partceg AS partceg4, t0.datego AS datego5, t0.dateResmisOff AS dateResmisOff6, t0.dateTransfert AS dateTransfert7, t0.nompays_id AS nompays_id8, t0.libTypeProj_id AS libTypeProj_id9, t0.nomclt_id AS nomclt_id10,t0.libContrat_id AS libContrat_id11, t0.libEtatProj_id AS libEtatProj_id12, t0.libEtatOff_id AS libEtatOff_id13
FROM projet t0 WITH (NOLOCK) WHERE t0.id = ?' with params ["index.json"]:
this is the entity
class projet
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="libProjet", type="string", length=255)
*/
private $libProjet;
/**
* #var string
*
* #ORM\Column(name="site", type="string", length=255)
*/
private $site;
/**
* #var float
*
* #ORM\Column(name="partceg", type="float")
*/
private $partceg;
//....
This is the Controller
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('rexBundle:projet')->findAll();
$repository = $this->getDoctrine()->getRepository('rexBundle:projet');
$query = $repository->createQueryBuilder('t')
->select('t.id','t.libProjet','t.site','t.partceg',
'IDENTITY(t.nompays) AS nompays',
'IDENTITY(t.libTypeProj) AS libTypeProj',
'IDENTITY(t.nomclt) AS nomclt',
'IDENTITY(t.libContrat) AS libContrat',
'IDENTITY(t.libEtatProj) AS libEtatProj',
'IDENTITY(t.libEtatOff) AS libEtatOff',
't.datego',
't.dateResmisOff',
't.dateTransfert')
->getQuery();
$entities = $query->getResult();
$entity = new projet();
$form = $this->createCreateForm($entity);
return array(
'entities' => $entities,
'entity' => $entity,
'form' => $form->createView(),
);
}

If you want send JSON response, read this article in documentation.
http://symfony.com/doc/current/components/http_foundation/introduction.html#creating-a-json-response
Now in your controller you don't send JSON Response, you only render form
Example how send JSON response:
use Symfony\Component\HttpFoundation\Response;
$response = new Response();
$response->setContent(json_encode(array(
'data' => 123,
)));
$response->headers->set('Content-Type', 'application/json');

Related

Column 'ip' cannot be null (SQL: insert into `logins` (`ip`, `steamid`, `time`)

insert into `logins` (`ip`, `steamid`, `time`)
I use php7.0 and phpmyadmin on vmware ubuntu server 16.04.6
I tried to fix it myself but I'm not really good at those kind of things if you need any more code tell me.
any help if welcome
the site wont let me post the full code here is the full code
This is the AuthController code
<?php namespace App\Http\Controllers;
use Invisnik\LaravelSteamAuth\SteamAuth;
use Illuminate\Support\Facades\DB;
use App\User;
use Auth;
use Carbon\Carbon;
class AuthController extends Controller
{
/**
* The SteamAuth instance.
*
* #var SteamAuth
*/
protected $steam;
/**
* The redirect URL.
*
* #var string
*/
protected $redirectURL = '192.168.1.12';
/**
* AuthController constructor.
*
* #param SteamAuth $steam
*/
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
/**
* Redirect the user to the authentication page
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function redirectToSteam()
{
return $this->steam->redirect();
}
/**
* Get user info and log in
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function handle()
{
if($this->steam->validate())
{
$info = $this->steam->getUserInfo();
$findUser = DB::table('users')->where('steamid', $info->steamID64)->first();
if(is_null($findUser))
{
$hasThisIp = DB::table('users')->where('ip', $this->getIp())->count();
if(!is_null($hasThisIp)) {
$connections = json_decode(json_encode($hasThisIp), true);
if($connections > 3) return view('connections');
else {
$array = array('<','>');
$numele = $info->personaname;
$name = str_replace($array, '*', $numele);
DB::table('users')->insert(
[
'name' => $name,
'steamid' => $info->steamID64,
'avatar' => $info->avatarfull,
'token' => csrf_token(),
'ip' => $this->getIp()
]
);

Subquery in SELECT using Yii2 ActiveRecord

Is it possible to convert this kind of SQL into ActiveRecord query in Yii2:
SELECT
*,
(select count(*) from pendaftar where pendaftar.prodi_pilihan_1 = a.id_prodi_penerima)as jum1,
(select count(*) from pendaftar where pendaftar.prodi_pilihan_2 = a.id_prodi_penerima)as jum2
FROM prodi_penerima as a
I have two relational models that are Pendaftar and ProdiPenerima.
This is Pendaftar model:
...
* #property ProdiPenerima $prodiPilihan1
* #property ProdiPenerima $prodiPilihan2
...
/**
* #return \yii\db\ActiveQuery
*/
public function getPekerjaanIdPekerjaan()
{
return $this->hasOne(Pekerjaan::className(), ['id_pekerjaan' => 'pekerjaan_id_pekerjaan']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserPendaftar()
{
return $this->hasOne(User::className(), ['id' => 'id_user_pendaftar']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProdiPilihan1()
{
return $this->hasOne(ProdiPenerima::className(), ['id_prodi_penerima' => 'prodi_pilihan_1']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProdiPilihan2()
{
return $this->hasOne(ProdiPenerima::className(), ['id_prodi_penerima' => 'prodi_pilihan_2']);
}
And this is ProdiPenerima model:
...
* #property Pendaftar[] $pendaftars
* #property Pendaftar[] $pendaftars0
...
/**
* #return \yii\db\ActiveQuery
*/
public function getPendaftars()
{
return $this->hasMany(Pendaftar::className(), ['prodi_pilihan_1' => 'id_prodi_penerima']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPendaftars0()
{
return $this->hasMany(Pendaftar::className(), ['prodi_pilihan_2' => 'id_prodi_penerima']);
}
prodi_pilihan_1 and prody_pilihan_2 are foreign keys in pendaftar table, that key was referenced from ProdiPenerima table.
$result = ProdiPenerima::find()
->select([
'*',
'jum1' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_1 = a.id_prodi_penerima'),
'jum2' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_2 = a.id_prodi_penerima')
])
->alias('a')
->asArray()
->all();
Results can be accessed by:
foreach ($result as $row) {
echo $row['jum1'];
}
That because asArray() was used, so query return array of arrays instead of array of models.
If you need models, you should add properties into your models to store result of subqueries:
class ProdiPenerima extends ActiveRecord {
public $jum1;
public $jum2;
// ...
}
Then remove isArray() from query:
$result = ProdiPenerima::find()
->select([
'*',
'jum1' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_1 = a.id_prodi_penerima'),
'jum2' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_2 = a.id_prodi_penerima')
])
->alias('a')
// ->asArray()
->all();
Results can be accessed by:
foreach ($result as $model) {
echo $model->jum1;
}
But note that using asArray() will be faster, so unless you need access some model methods (or rely on typecasting of values from DB) I would prefer arrays.

CakePHP and DefaultPasswordHasher syntax error

I have no clue why but for the line
use Cake\Auth\DefaultPasswordHasher;
I'm getting an error
Error: syntax error, unexpected '?'
and full code of user.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
/**
* User Entity
*
* #property int $id
* #property string $email
* #property string $password
* #property \Cake\I18n\Time $created
* #property \Cake\I18n\Time $modified
*
* #property \App\Model\Entity\Bookmark[] $bookmarks
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => true,
'id' => false
];
/**
* Fields that are excluded from JSON versions of the entity.
*
* #var array
*/
protected $_hidden = [
'password'
];
protected function _setPassword($value){
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
}
Any thoughts? I'm using latest CakePHP
Please try with this one. Please update your CakePHP project with composer, it will update all dependency if you miss something.
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class User extends Entity
{
// Make all fields mass assignable except for primary key field "id".
protected $_accessible = [
'*' => true,
'id' => false
];
// ...
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
// ...
}
Also please read this doc here. Hope it should be help you to solve this issue.
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
/**
* User Entity
*
* #property int $id
* #property string $email
* #property string $password
* #property string $role
* #property \Cake\I18n\Time $created
* #property \Cake\I18n\Time $modified
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => true,
'id' => false
];
/**
* Fields that are excluded from JSON versions of the entity.
*
* #var array
*/
protected $_hidden = [
'password'
];
protected function _setPassword($password) {
return (new DefaultPasswordHasher)->hash($password);
}
}

Symfony2 implement PATCH method to update user fileds

How can I update FOS USER user details using PATCH method. So when I pass partial details in Json, only these details are updated.
User entity
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
abstract class User extends BaseUser
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string]
* #ORM\Column(name="first_name", type="string", length=255, nullable=true)
*/
private $firstName;
/**
* #var string
* #ORM\Column(name="last_name", type="string", length=255, nullable=true)
*/
private $lastName;
// getters and setters are here
}
For example. I have user Jack Nickolson and my json is:
{"firstName": "John"}
Only first name is updated.
This is my controller. How do I set new parameters to user, without specifing which parameters?
/**
* #Route("/update", name="api_user_update")
* #Security("has_role('ROLE_USER')")
* #Method("PATCH")
*/
public function updateAction(Request $request){
$jsonContent = $request->getContent();
$params = json_decode($jsonContent);
$em = $this->getDoctrine()->getEntityManager();
$response = new JsonResponse();
$user = $this->getUser();
// do something to update user details
$this->get('fos_user.user_manager')->updateUser($user);
$em->persist($user);
$em->flush();
$response->setContent([
"status" => "user ". $user->getUsername() ." is updated"
]);
return $response;
}
UPDATE
I tried to use an answer below, so this what I have now
public function updateAction(Request $request){
$em = $this->getDoctrine()->getEntityManager();
$response = new JsonResponse();
$user = $this->getUser();
$editForm = $this->createForm('CoreBundle\Form\UserType', $user);
$requestData = $request->getContent();
$requestData = json_encode($requestData, true);
$editForm->submit($requestData, false);
$this->get('fos_user.user_manager')->updateUser($user);
$em->persist($user);
$em->flush();
$response->setContent([
"status" => "user ". $user->getUsername() ." is updated"
]);
return $response;
}
Well, my entity was not updated. What am I doing wrong?
You need to prepare and create UserType form for partial updated.
Then, when processing a submitted form, you'll need to pass a false $clearMissing option to your form's submit method call in the controller:
$form->submit($request, false);
Thanks to that option the form component will only update the fields passed from the request.
and then flush user:
$em->flush();
Also if you want send data like:
{"firstName": "John"}
your UserType form should have method:
public function getBlockPrefix()
{
return "";
}
You can also use nice and powerfull https://github.com/FriendsOfSymfony/FOSRestBundle

Yii mysql datetime empty

I have a problem with a Yii model, I create a MySQL table with two datetime column.
And create the model with gii. The problem is that when I get the data from the model I get the datetime fields empty.
<?php
/**
* This is the model class for table "Template".
*
* The followings are the available columns in table 'Template':
* #property string $tmpId
* #property integer $fanPageId
* #property string $name
* #property string $title
* #property string $description
* #property string $headerFile
* #property string $msgNotTlt
* #property string $msgNotMsg
* #property string $msgNotImg
* #property string $msgNotLnk
* #property string $terms
* #property string $strProm
* #property string $endProm
*/
class Template extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Template the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'Template';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fanPageId', 'numerical', 'integerOnly'=>true),
array('name, title, description, headerFile, msgNotTlt, msgNotMsg, msgNotImg, msgNotLnk, terms', 'length', 'max'=>11),
array('strProm, endProm', 'safe'),
//array('endProm, strProm', 'type', 'type'=>'datetime', 'datetimeFormat'=>'yyyy/M/d H:m:s'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('tmpId, fanPageId, name, title, description, headerFile, msgNotTlt, msgNotMsg, msgNotImg, msgNotLnk, terms, strProm, endProm', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'tmpId' => 'Tmp',
'fanPageId' => 'Fan Page',
'name' => 'Name',
'title' => 'Title',
'description' => 'Description',
'headerFile' => 'Header File',
'msgNotTlt' => 'Msg Not Tlt',
'msgNotMsg' => 'Msg Not Msg',
'msgNotImg' => 'Msg Not Img',
'msgNotLnk' => 'Msg Not Lnk',
'terms' => 'Terms',
'strProm' => 'Str Prom',
'endProm' => 'End Prom',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('tmpId',$this->tmpId,true);
$criteria->compare('fanPageId',$this->fanPageId);
$criteria->compare('name',$this->name,true);
$criteria->compare('title',$this->title,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('headerFile',$this->headerFile,true);
$criteria->compare('msgNotTlt',$this->msgNotTlt,true);
$criteria->compare('msgNotMsg',$this->msgNotMsg,true);
$criteria->compare('msgNotImg',$this->msgNotImg,true);
$criteria->compare('msgNotLnk',$this->msgNotLnk,true);
$criteria->compare('terms',$this->terms,true);
$criteria->compare('strProm',$this->strProm,true);
$criteria->compare('endProm',$this->endProm,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
In rules of you model add the two columns:
array('datetime_1, datetime_2', 'safe'),
array('id, <attributes>, datetime_1, datetime_2', 'safe', 'on'=>'search'),
If possible, post you code/model...