CRUDlex not working when add new table in yaml - php

i try to find a faster way to generate UI for existing database, CRUD, composer way, using symfony component.
found CRUDlex. Doing install with composer, also setup CRUDlex sample
it works fine, until i m add new table definition in sample crud.yml
category:
label: Category
table: category
fields:
name:
type: text
label: Name
required: true
unique: true
what ever table added in yml, it's always throw error similar to this when access http://localhost/crudlex/web/category
InvalidFieldNameException in AbstractMySQLDriver.php line 71: An exception occurred while executing 'SELECT COUNT(id) FROM `category` `category` WHERE deleted_at IS NULL':
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'deleted_at' in 'where clause'
complete error message please check screenshot below
crudlex always asking "id" and 'deleted_at'
the code is same as CRUDled sample index.php
$loader = require __DIR__.'/../vendor/autoload.php';
//$loader->add('CRUDlex', __DIR__.'/../../CRUDlex/src');
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'dbs.options' => array(
'default' => array(
'host' => '127.0.0.1',
'dbname' => 'dbname',
'user' => 'root',
'password' => '',
'charset' => 'utf8',
)
),
));
$app->register(new Silex\Provider\SessionServiceProvider());
$dataFactory = new CRUDlex\MySQLDataFactory($app['db']);
$app->register(new CRUDlex\ServiceProvider(), array(
'crud.file' => __DIR__ . '/../crud.yml',
'crud.datafactory' => $dataFactory
));
$app->register(new Silex\Provider\TwigServiceProvider());
//$app['crud.layout'] = 'layout.twig';
$app->mount('/', new CRUDlex\ControllerProvider());
$app->match('/', function() use ($app) {
return $app->redirect($app['url_generator']->generate('crudList', array('entity' => 'library')));
})->bind('homepage');
$app->run();
And folder structure
vendor
web
> .htaccess
> index.php
composer.json
crud.yml
Note: I m totally new to silex and symfony2 component ^_^
Thank you, any suggest really appreciated

you are missing (at least) one of the required meta fields:
created_at (datetime, not null): When the record was created
updated_at (datetime, not null): When the record was edited the last time
version (int, not null): The version of the record, increments with each edit
deleted_at (datetime): If not null: When the record was (soft-) deleted
The complete table creation SQL in your case would look like this:
CREATE TABLE `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`deleted_at` datetime DEFAULT NULL,
`version` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Related

Bug when storing sessions in the database (Yii 1)

I have project on yii 1 and when i use DB for saving sessions i received bug. For each query to the site in the database creates a new entry. I don't know why.
Therefore I can not get a variable from the session, becouse after refrtsh page i have a new entry in db.
What i am doing wrong?
Table:
CREATE TABLE `wo_yiisession` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`expire` INT(11) NOT NULL,
`data` TEXT NOT NULL,
PRIMARY KEY (`id`),
INDEX `expire_idx` (`expire`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
session component setings:
'session' => array(
'class' => 'CDbHttpSession',
'connectionID' => 'db',
'sessionTableName' => 'wo_yiisession',
'timeout' => 3600 * 24 * 30,
'autoStart' => 'false',
'cookieMode' => 'only',
),
It looks like your ID field is wrong type. Proposed table structure is:
CREATE TABLE YiiSession
(
id CHAR(32) PRIMARY KEY,
expire INTEGER,
data BLOB
)
See CDbHttpSession

CodeIgniter - ci_sessions migrations

I was wondering if someone can help out.
Im just getting into using migrations with CodeIgniter, but im having trouble trying to figure out how to convert SQL to the migrations.
Is there anyone out there that could convert this SQL to migrations for me so i can see how its done.
The SQL i have is as follows:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`session_id` varchar(40) COLLATE utf8_bin NOT NULL DEFAULT '0',
`ip_address` varchar(16) COLLATE utf8_bin NOT NULL DEFAULT '0',
`user_agent` varchar(150) COLLATE utf8_bin NOT NULL,
`last_activity` int(10) unsigned NOT NULL DEFAULT '0',
`user_data` text COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Please read the documentation here:
CodeIgniter Migrations
In essence, you will want to use the CodeIgniter dbforge class to create the table. Using your code above:
$this->dbforge->add_field(array(
'session_id' => array(
'type' => 'VARCHAR',
'constraint' => '40'
),
'ip_address' => array(
'type' => 'VARCHAR',
'constraint' => '16'
),
'user_agent' => array(
'type' => 'VARCHAR',
'constraint' => '150'
),
'last_activity' => array(
'type' => 'INT',
'constraint' => '10'
),
'user_data' => array(
'type' => 'TEXT'
)
));
$this->dbforge->add_key('session_id', TRUE);
$this->dbforge->create_table('ci_sessions');
Documentation on dbforge class can be found here:
ellislab.com/codeigniter/user-guide/database/forge.html
Note: I don't recommend messing with the CI Sessions table, though.
You can also simply do this if you've a block of large SQL query you know is "safe" and you want to save time (in my opinion it's a judgement call based on the complexity of the table and the chance of making an error when translating the raw SQL into arrays - after all in migrations everything is hardcoded and you're not worrying about the chances of SQL injection etc.)
$sql = "CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
)";
$this->db->query($sql);
However I don't think I'd recommend loading the sessions table as a migration, because if $config['sess_use_database'] in config/config.php is true, when you go to your migration URL it'll fail, as Codeigniter will first try to create a session entry in the database for your browser and the database table doesn't yet exist..
A Database Error Occurred
Error Number: 1146
Table 'characterhub.ci_sessions' doesn't exist
So for it to work, you or whomever is performing the migration has to set sess_use_database to false first, then run the migration, then change it back to true again.

CakePHP HABTM model problem

I have a problem when using CakePHP HABTM.
I have the following models.
class Repositorio extends AppModel{
var $name="Repositorio";
var $hasAndBelongsToMany = array(
'Sesion' =>
array(
'joinTable' => 'sesions_repositorios',
'dependent' => true
)
);
var $order=array('Repositorio.name'=>'ASC');
}
class Sesion extends AppModel{
var $name="Sesion";
var $belongsTo=array(
'SesionsEstado',
'Asignatura',
'User'
);
var $hasAndBelongsToMany = array('Repositorio'=>
array(
'joinTable'=>'sesions_repositorios',
'dependent' => true
)
);
var $order=array('Sesion.ffin'=>'ASC');
}
And the following database tables.
CREATE TABLE sesions (
id INT(11) NOT NULL AUTO_INCREMENT,
user_id INT(11) NOT NULL,
sesions_estado_id INT(11) NOT NULL,
asignatura_id INT(11) NOT NULL,
name VARCHAR(100) NOT NULL,
finicio DATETIME NOT NULL,
ffin DATETIME NOT NULL,
created DATETIME NOT NULL,
modified DATETIME NOT NULL,
PRIMARY KEY(id),
INDEX sesions_FKIndex1(sesions_estado_id),
INDEX sesions_FKIndex2(asignatura_id),
INDEX sesions_FKIndex3(user_id)
);
CREATE TABLE repositorios (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
created DATETIME NOT NULL,
modified DATETIME NOT NULL,
PRIMARY KEY(id)
);
CREATE TABLE sesions_repositorios (
id INT(11) NOT NULL AUTO_INCREMENT,
sesion_id INT(11) NOT NULL,
repositorio_id INT(11) NOT NULL,
PRIMARY KEY(id),
INDEX sesions_repositorios_FKIndex1(sesion_id),
INDEX sesions_repositorios_FKIndex2(repositorio_id)
);
When I save the data in a repository all work properly, that is, it performs an INSERT on the table "repositorios" and performs the corresponding INSERT on table "sesions_repositorios.
My problem comes when I get a list of repositories for a particular user. The code for this would be.
class RepositoriosController extends AppController{
...
$r=$this->Repositorio->Sesion->find('all', array('conditions'=>array('user_id'=>$this->Session->read('Auth.User.id'))));
var_dump($r);
...
}
The $r variable does not contain the filtered data for user_id, why?, what am I doing wrong?
I have not set foreign key's, could that be the problem?
Thanks for the help.
I believe that you need to add in something like 'recursive' => 1 or whatever depth you want it to search your linked models into your query.
$r=$this->Repositorio->Sesion->find('all', array('conditions'=>array('user_id'=>$this->Session->read('Auth.User.id')),'recursive'=>1));
I'm sorry, the code is actually quite correct. Was failing by other issues.
Thanks for everything.
Greetings!

Cakephp Save with a table where the primary key is not 'id'

I have an existing web application that I am converting to use CakePHP.
The problem is that the primary keys for most of the tables are in this format "${table_name}_id" (story_id) instead of the CakePHP way of 'id'
When ever I try to update some of the fields for a row in the story table, the Save() function will return false. Is there any way of getting a more detailed error report from the Save() function. ?
When I set Configure::write('debug', 2); in core.php and check the SQL statements I do not see any UPDATE command, only SELECT statements.
I tried to edit the controller adding the following line to manually set the id field for the controller but it did not help.
$this->Story->id = $this->data['Story']['story_id'] ;
I'm running out of ideas. Any suggestions?
I have included the source code that I am using below
Story controller:
function admin_edit($id = null)
{
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid '. Configure::read('Site.media') , true));
$this->redirect(array('action'=>'index'));
}
$this->layout = 'admin';
if (!empty($this->data)) {
if ($this->Story->save($this->data)) {
$this->Session->setFlash(__('The '. Configure::read('Site.media') .' has been saved', true));
} else {
$this->Session->setFlash(__('The '. Configure::read('Site.media') .' could not be saved. Please, try again.', true));
}
}
$this->data = $this->Story->read(null, $id );
}
Story model:
class Story extends AppModel {
var $name = 'Story';
var $primaryKey = 'story_id';
var $validate = array(
'author_id' => array('numeric'),
'title' => array('notempty'),
'story' => array('notempty'),
'genra' => array('notempty'),
'form' => array('notempty'),
'wordcount' => array('Please enter a number between 1 and 1000' => array(
'rule' => array('range', 1, 1001),
'message' => 'Please enter a number between 1 and 1000' ),
'Required' => array( 'rule' => 'numeric', 'required' => true )
)
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Author' => array(
'className' => 'Author',
'foreignKey' => 'author_id'
)
);
var $hasMany = array(
'UserNote' => array(
'className' => 'UserNote',
'foreignKey' => 'story_id',
'dependent' => false,
'conditions' => 'UserNote.notes != ""'
)
);
}
Story view:
echo $form->create('Story', array('action' => 'edit' ) );
echo $form->input('story_id',array('type'=>'hidden') );
echo $form->input('title');
echo $form->input('story');
echo $form->input('bio' );
echo $form->end('Update story details');?>
Story table
CREATE TABLE IF NOT EXISTS `stories` (
`story_id` int(11) NOT NULL AUTO_INCREMENT,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`closed` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`author_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`story` text NOT NULL,
`genra` varchar(255) NOT NULL,
`form` varchar(128) DEFAULT NULL,
`wordcount` varchar(255) NOT NULL,
`terms` varchar(255) NOT NULL DEFAULT '0',
`status` varchar(255) NOT NULL DEFAULT 'slush',
`published` date NOT NULL,
`payment` varchar(255) NOT NULL DEFAULT 'none',
`paypal_address` varchar(255) NOT NULL,
`resubmission` tinyint(1) NOT NULL DEFAULT '0',
`bio` text NOT NULL,
`password` varchar(255) NOT NULL DEFAULT 'yyggrrdd',
`comments` text NOT NULL,
PRIMARY KEY (`story_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10905 ;
You should manually override the primary key field in the model (which is the right place to do this - the name of a primary key field is an attribute of the model, and not something that should be 'fudged' around in the controller.)
class Example extends AppModel { var $primaryKey = 'example_id'; // example_id is the field name in the database}
The above code is from http://book.cakephp.org/view/437/primaryKey
While the suggestion to turn off validation will work, it's not the right way to go about it.
Lastly, if you're setting model variables within a controller, you use $this->Model->set('attributeName',value) rather than $this->Model->attributeName
It looks like the story controller was validating the data, and the data was invalid.
Adding the following line to the controller will stop the validation of the data.
$this->Story->validate = array(); // Stop valadation on the story.
I found this solution on this page
15 essential CakePHP tips

Storing Sessions in DB Table Not Working (using Zend_Session_SaveHandler_DbTable)

This is my table:
CREATE TABLE `Sessions` (
`id` varchar(32) NOT NULL,
`modified` int(11) default NULL,
`lifetime` int(11) default NULL,
`data` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
This is in my bootstrap:
$sessionConfig = array(
'name' => 'Sessions', //table name as per Zend_Db_Table
'primary' => 'id', //the sessionID given by php
'modifiedColumn' => 'modified', //time the session should expire
'dataColumn' => 'data', //serialized data
'lifetimeColumn' => 'lifetime' //end of life for a specific record
);
$saveHandler = new Zend_Session_SaveHandler_DbTable($sessionConfig);
//cookie persist for 30 days
Zend_Session::rememberMe($seconds = (60 * 60 * 24 * 30));
//make the session persist for 30 days
$saveHandler->setLifetime($seconds)
->setOverrideLifetime(true);
//similarly,
//$saveHandler->setLifetime($seconds, true);
Zend_Session::setSaveHandler($saveHandler);
Zend_Session::start();
When I log in, nothing ever gets written to the Sessions table and I am logged out on the very next pageview.
Any ideas? I'm trying to have my users be perpetually logged in. Am I missing something in my login controller possibly?
I just managed to get this working:
My application.ini:
resources.db.isDefaultTableAdapter = true
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.dbname = "dbname"
resources.db.params.username = "username"
resources.db.params.password = "password"
my bootstrap.php:
protected function _initSession() {
$resource = $this->getPluginResource('db');
$dbAdapter = $db = $resource->getDbAdapter();
Zend_Registry::set("db", $dbAdapter);
Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
$config = array(
'name' => 'session',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime',
'db' => $dbAdapter
);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
Zend_Session::start();
}
This function was placed as first function in the bootstrap.php, because sessions are started, when you construct a Zend_Session_Namespace object for the first time. If you do this, before the _initSession()-function got called, a standard file-based session may be started.
Finally, the session.sql:
DROP TABLE IF EXISTS `session`;
CREATE TABLE `session` (
`id` char(32) NOT NULL DEFAULT '',
`modified` int(11) DEFAULT NULL,
`lifetime` int(11) DEFAULT NULL,
`data` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Somewhere i read that the table must be InnoDB.
You have to initialize your DB handler before telling Zend_Session to use the DB, either by setting a default adapter for Zend_Db, or passing your adapter in the config array as 'db'.
Maybe you have to put Zend_Session::start(); before anything else on the page... ?
Had the same problem with an implementation of redis as session handler.
For me, putting the method _initSession as first method in my bootstrap class works.
Hope it will help someone.

Categories