I am new in Zend Framework
This is my DBTable
class Application_Model_DbTable_Employee extends Zend_Db_Table_Abstract
{
protected $_name = 'tab_employee';
}
This is my Models
public function InsertEmployees($array){
$tblEmployee = new Application_Model_DbTable_Employee();
$tblEmployee->insert($array);
}
This is my controller
public function AddEmployeeAction(){
$request = $this->getRequest();
$params = $request->getParams();
$emp = new Application_Model_InsEmployee();
$emp->InsertEmployees(array(
'Name' => $params['name'],
'Date' => $params['date']
));
}
Anybody knows what is the error of this code because it always return an application error . Thanks for advance
In your DbTable do this:
public function InsertEmployees($array){
$this->insert($array);
}
So your DB will look like this:
class Application_Model_DbTable_Employee extends Zend_Db_Table_Abstract
{
protected $_name = 'tab_employee';
public function InsertEmployees($array){
$this->insert($array);
}
}
Then from the controller, create the DbTable instance and "bypass" the model.
$model = new Application_Model_Db_Table();
$model->InsertEmployees($data)
Related
Here, I'm trying to to insert the data in the database but for some reason I am not able to insert the data in the database. This is the error:
SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into stages (code, name, description, updated_at, created_at) values (32, dfs, vc, 2020-04-14 06:02:57, 2020-04-14 06:02:57))"
My code are here:
StageController.php
<?php
namespace App\Sys\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Sys\Model\Stage;
class StageController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['stages' => Stage::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$location= Stage::create([
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description
]);
return response()->json(['stage'=>$stage],200);
}
public function show($id)
{
$stages = Stage::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['stages' => $stages],200);
}
public function update(Request $request, $id)
{
$stage = Stage::find($id);
$stage->code = $request->code;
$stage->name = $request->name;
$stage->description = $request->description;
$stage->save();
return response()->json(['stage'=>$stage], 200);
}
public function destroy($id)
{
$stage = Stage::where('id', $id)->delete();
return response()->json(['stage'=>$stage],200);
}
public function deleteAll(Request $request){
Stage::whereIn('id', $request->stages)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
Stage.php
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
protected $guarded = [];
}
My migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stages', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('original_id',36)->default('0')->index();
$table->string('code',10)->index()->nullable();
$table->string('name',100);
$table->string('description',200)->nullable();
$table->char('created_by',36)->index();
$table->char('edited_by',36)->index()->nullable();
$table->timestamps();
$table->foreign('created_by')->references('id')->on('users');
$table->foreign('edited_by')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stages');
}
}
In my case i didn't add that field into fillable in my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
}
For laravel 5.6+ you can use Str::uuid() to generate the uuid string;
use Illuminate\Support\Str;
...
public function store(Request $request)
{
$uuid = Str::uuid()->toString();
$location= Stage::create([
'id' => $uuid,
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description
]);
return response()->json(['stage'=>$stage],200);
}
For below laravel 5.6, you can use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Uuid;
...
public function store(Request $request)
{
$uuid = Uuid::uuid1()->toString();
...
return response()->json(['stage'=>$stage],200);
}
Or you can write an boot method for generating uuid to creating, Eloquent will automatically set id=uuid for every create method. If there are many models with primary key uuid, you can write a trait and use this trait in each models.
use Illuminate\Support\Str;
...
class Stage extends Model
{
/**
* Boot function from laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
});
}
}
the error :
Action App\Http\Controllers\formController#form not defined. (View: C:\xampp\htdocs\ucar3\resources\views\layouts\Form.blade.php) (View: C:\xampp\htdocs\ucar3\resources\views\layouts\Form.blade.php)
I tried changing the route in web.php
web.php
Route::resource('Inscription','inscriController');
Controller
class FormController extends Controller
{
public function show()
{
return view('pages.Inscription');
}
public function insert(Request $request)
{
$Cin = $request->input('Cin');
$nom = $request->input('nom');
$prenom = $request->input('prenom');
$email = $request->input('email');
$telephone = $request->input('telephone');
$specialite = $request->input('specialite');
$typedediplome = $request->input('typedediplome');
$mentiondiplome = $request->input('mentiondiplome');
$redoublement = $request->input('redoublement');
$communication = $request->input('communication');
$publication = $request->input('publication');
$experiencePedagogiqueSecondaire = $request
->input('experiencePedagogiqueSecondaire');
$experiencePedagogiqueSupérieur = $request
->input('experiencePedagogiqueSupérieur');
$data = array(['Cin'=>$Cin,
'nom'=>$nom,
'prenom'=>$prenom,
'email'=>$email,
'telephone'=>$telephone,
'specialite'=>$specialite,
'typedediplome'=>$typedediplome,
'mentiondiplome'=>$mentiondiplome,
'redoublement'=>$redoublement,
'communication'=>$communication,
'publication'=>$publication,
'experiencePedagogiqueSecondaire'=>$experiencePedagogiqueSecondaire,
'experiencePedagogiqueSupérieur'=>$experiencePedagogiqueSupérieur
]);
DB::table('users')->insert($data);
return view('pages.success');
}
}
Model
class form extends Model
{
public $table = "form";
protected $fillable = [
'Cin',
'nom',
'prenom',
'telephone',
'email',
'specialite',
'typedediplome',
'mentiondiplome',
'redoublement',
'communication',
'publication',
'experiencePedagogiqueSecondaire',
'experiencePedagogiqueSupérieur'
];
public $timestamps = true;
}
As the Error says
formController#form not defined.
but in your class you've
FormController extends Controller
Please check if you are calling FormController with lower case 'F'.
I think you have problems with your inscriController and your routes, use the following code:
web.php
use App\Http\Controllers\inscriController;
Route::resource('Inscription', inscriController::class);
app/Http/Controllers.php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class inscriController extends Controller {
public function __construct() {
$this->middleware('auth');
}
}
Check if you set the correct namespace in the FormController.php
You are also missing a function form inside your FormController.
My problem at the moment is that I want to save some values to the database but the don't get saved and I don't get an error..
Both, either $product-save(); or $product-update(array(...)) are not working and I cannot tell why.. My ASIN Model looks fine and is filled with the right fillable attributes...
You guys know why it isn't working?
My Laravel Version: Laravel Framework 5.5.36
This is my class so far:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\ASIN;
class CheckPrice extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'post:CheckPrice';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle() {
$product = ASIN::find(1410);
$product->price = "HELLO";
$product->amountSaved = "HELLO";
$product->percentageSaved = "HELLO";
$product->url = "HELLO";
$product->imgUrl = "HELLO";
$product->save();
//$product->update(array("price" => "HELLO", "amountSaved" => "HELLO", "percentageSaved" => "HELLO", "url" => "HELLO", "imgUrl" => "HELLO"));
$this->printProduct(ASIN::find(1410));
}
My ASIN Model so far:
namespace App;
use Illuminate\Database\Eloquent\Model;
class ASIN extends Model
{
protected $connection = 'facebook_amazon';
public $table = "ASINS";
protected $fillable = [
'ASIN',
'price',
'amountSaved',
'percentageSaved',
'category',
'url',
'imgUrl',
'showApp'
];
}
Kind regards and Thank You!
Use this in the handle methode
$product = App\ASIN::find(1410);
Or while impoting ASIN model use this if you want to keep the handle methode same
use App\ASIN as ASIN;
Use Laravel logs:
if(!$product->save()){
foreach($products->errors() as $error){
Log::info($error);
}
}
Hope this help.
I test a config class, which is parsing a config file and allows me to get the various settings for an app.
My goal is to mock the parse() method of the Config class, which is called in the constructor and to set what this method is returning in the constructor.
This way, it prevents file_get_contents() from being called (in the parse() method) and enables me to have a Config class with the config property already set to contain an array of properties.
But I haven't succeeded doing that.
Here is the code:
The config class:
<?php namespace Example;
use Symfony\Component\Yaml\Parser;
class Config
{
private $parser;
private $config;
public function __construct(Parser $parser, $filePath)
{
$this->parser = $parser;
$this->config = $this->parse($filePath);
}
public function parse($filePath)
{
$fileAsString = file_get_contents($filePath);
if (false === $fileAsString) {
throw new \Exception('Cannot get config file.');
}
return $this->parser->parse($fileAsString);
}
public function get($path = null)
{
if ($path) {
$config = $this->config;
$path = explode('/', $path);
foreach ($path as $bit) {
if (isset($config[$bit])) {
$config = $config[$bit];
}
}
return $config;
}
return false;
}
}
The test:
<?php namespace Example;
class ConfigTest extends \PHPUnit_Framework_TestCase
{
private function getConfigTestMock($configAsArray)
{
$parser = $this->getMockBuilder('\Symfony\Component\Yaml\Parser')
->getMock();
$configMock = $this->getMockBuilder('Example\Config')
->setConstructorArgs([$parser, $configAsArray])
->setMethods(['parse', 'get'])
->getMock();
$configMock->expects($this->once())
->method('parse')
->willReturn($configAsArray);
return $configMock;
}
/**
* #test
*/
public function get_returns_false_if_no_path_given()
{
$configMock = $this->getConfigTestMock(['param1' => 'value1']);
// Testing further...
}
}
I suggest you to make a functional test mocking the interaction with the file system, without do partial mocking of the tested class.
I recently discover the vfsStream library used in a great article of William Durand about Symfony2 and DDD.
So you can install this library in your composer.json (I tested the solution with the 1.4 version) and try this example test class:
<?php
namespace Acme\DemoBundle\Tests;
use Acme\DemoBundle\Example\Config;
use org\bovigo\vfs\vfsStream;
use Symfony\Component\Yaml\Parser;
class ConfigTest extends \PHPUnit_Framework_TestCase
{
/**
* #test
*/
public function valid_content()
{
$content = "param1: value1";
$root = vfsStream::setup();
$file = vfsStream::newFile('example.txt')
->withContent($content)
->at($root);
$filepath = $file->url();
$parser = new Parser();
$config = new Config($parser, $filepath);
$this->assertEquals("value1", $config->get("param1"));
}
}
Hope this help
For test the Config class you need to mock only the Parser and use the real Config class. As Example:
<?php
namespace Acme\DemoBundle\Tests;
use Acme\DemoBundle\Example\Config;
class ConfigTest extends \PHPUnit_Framework_TestCase
{
private function getConfigTestMock($configAsArray)
{
$parser = $this->getMockBuilder('\Symfony\Component\Yaml\Parser')
->getMock();
$parser->expects($this->once())
->method('parse')
->willReturn($configAsArray);
$configMock = new Config($parser,"fakePath");
return $configMock;
}
/**
* #test
*/
public function get_returns_false_if_no_path_given()
{
$configMock = $this->getConfigTestMock(['param1' => 'value1']);
$this->assertEquals("value1",$configMock->get("param1"));
// Testing further...
}
}
Hope this help
I'm newbie on Zend Framework, I created DbTable , my primary key is id , and my table name is user:
<?php
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
protected $_name = 'user';
protected $_primary = 'id';
}
after that ,I reviewed Abstract.php(Db/Table/Abstract.php) and I found out that I had to use insert(array $data), so I created a model: (Register.php)
<?php
class Application_Model_Register
{
public function CreateUser($array)
{
$dbTableUser = new Application_Model_DbTable_User();
$dbTableUser -> insert($array);
}
}
and finally , in my Controllers , I created IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$register = new Application_Model_Register();
$register-> CreateUser(array(
'username'=>'test'));
}
}
It works correctly , but I have no idea about Select, How I select query from user table?
our controller should have to be like below
<?php
class IndexController extends Zend_Controller_Action
{
public function getdataAction()
{
$register = new Application_Model_Dbtable_Register();
$register->getListOfUser();
}
}
Now your model should have to be like this,
<?php
class Application_Model_DbTable_Register extends Zend_Db_Table_Abstract
{
protected $_name = 'user';
protected $_primary = 'id';
public function getListOfUser()
{
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$select = $db->select()
->from($_name,array('*'))
->where(1);
$data = $db->query($select)->fetchAll();
return $data;
}
}