I want to fetch values from database and display it in the view, but I didn't get a correct result.
This is my controller:
class HrRequestController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$hr_request = HrRequest::all();
return array(
'status' => 'success',
'pages' => $hr_request->toArray());
}
}
and this is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class HrRequest extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'hr_request';
public $timestamps = false;
/**
* Fields.
*
* #var array
*/
protected $fillable = [
'profile_role_id', 'hr_id', 'vacancy', 'experience', 'job_description', 'status', 'viewed',
];
}
view name:view-requests.blade.php
I have no idea n how to do this in view. Can anyone help me?
Controller:
public function index()
{
$hr_request = HrRequest::all();
return view('view-requests')->with('hr_request', $hr_request);
}
View:
#foreach($hr_request as $row)
<tr>
<td>{{$row->profile_role_id}}</td>
<td>{{$row->vacancy}}</td>
<td>{{$row->experience}}</td>
<td>{{$row->job_description}}</td>
<td>
<button type="button" class="btn btn-primary">View</button>
<button type="button" class="btn btn-success">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</td>
</tr>
#endforeach
Route:
Route::get('/view-hr-requests', 'HrRequestController#index');
It's working
Related
I'm a beginner at Symfony. My problem is that I try to add values to my base MySQL and the problem is that I have the same id, but i verified my entity and i generate values #ORM/GeneratedValues, i don't understand where is my fault.
Routing :
esprit_parc_AjoutVoiture:
path: /Ajout_voiture/
defaults: { _controller: ParcBundle:Voiture:add }
My controller:
public function addAction (Request $Request)
{
$Voiture = new Voiture();
$form = $this->createForm(VoitureType::class,$Voiture);
$form->handleRequest($Request);
if ($form->isValid())
{
$em=$this->getDoctrine()->getManager();
$em->persist($Voiture);
$em->flush();
return $this->redirect($this->generateUrl(
'esprit_parc_Affichage'
));
}
return $this->render(
'ParcBundle:Voiture:ajout.html.twig',
array('form'=>$form->createView()
));
}
}
Entity Voiture:
<?php
namespace ParcBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class voiture
* #package ParcBundle\Entity
* #ORM\Entity
* #ORM\Table(name="Voiture")
*/
class Voiture
{
/**
* #ORM\Column( type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/**
* #ORM\Column(type="string",length=255)
*
*/
private $Serie;
/**
* #ORM\Column(type="datetime",length=255)
*/
private $DateMiseCirculation;
/**
* #ORM\Column(type="string",length=255)
*/
private $Marque;
/**
* #ORM\ManyToOne(targetEntity="ParcBundle\Entity\Modele" )
* #ORM\JoinColumn(name="id", referencedColumnName="id");
*/
private $modele;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getModele()
{
return $this->modele;
}
public function setModele($modele)
{
$this->modele = $modele;
}
public function getSerie()
{
return $this->Serie;
}
public function setSerie($Serie)
{
$this->Serie = $Serie;
}
public function getDateMiseCirculation()
{
return $this->DateMiseCirculation;
}
public function setDateMiseCirculation($DateMiseCirculation)
{
$this->DateMiseCirculation = $DateMiseCirculation;
}
public function getMarque()
{
return $this->Marque;
}
public function setMarque($Marque)
{
$this->Marque = $Marque;
}
}
Error:
An exception occurred while executing 'INSERT INTO Voiture (serie, date_mise_circulation, marque, id) VALUES (?, ?, ?, ?)' with params ["2313", "2012-12-03 02:02:00", "sd", 1]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY'
PS : i have values with id = "1" and it should increment automatically the id.
[EDIT]: Class VoitureType:
<?php
namespace ParcBundle\Form;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class VoitureType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('Serie')
->add('DateMiseCirculation')
->add('Marque')
->add('modele', EntityType::class, array(
"class" => "ParcBundle:Modele",
"choice_label"=> "libelle"
))
->add("Ajouter",SubmitType::class);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ParcBundle\Entity\Voiture'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'parcbundle_voiture';
}
}
You have an old schema in your database and MySQL does not know that attribute id is auto increment value. To update your schema you can use one of methods:
Internal tool from Doctrine: php bin/console doctrine:schema:update --force.
Use DoctrineMigrationsBundle.
Remember that sometimes schema do not want to update because of foreign keys. Solution for this is just remove existing data.
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'];
...
}
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"}]}
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
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.