Allowed fields must be specified for model how to fix the error? - codeigniter-4

I am new to code igniter 4 user. and faced these type error please any one help to me.. how to fix the error.
CodeIgniter\Database\Exceptions\Data Exception
Allowed fields must be specified for model: App\Models\Student Model

look at my model
works for me fine
<?php namespace Modules\App\Models;
use Modules\App\Entities\CourseCategoryEntity;
use CodeIgniter\Model;
use Modules\Shared\Models\Aggregation;
class CourseCategoryModel extends Aggregation
{
/**
* table name
*/
protected $primaryKey = "id";
protected $table = "course_category";
/**
* allowed Field
*/
protected $allowedFields = [
'name',
'language'
];
protected $returnType = CourseCategoryEntity::class;
protected $validationRules = [
'name' => 'required|min_length[3]|max_length[255]',
'language' => 'required|min_length[1]|max_length[255]',
];
protected $useSoftDeletes = false;
protected $validationMessages = [];
protected $skipValidation = false;
}

Related

How can cart table associate with another table?

I have table table_name(id, cart_token, data , created_at, updated_at ) that wants to associate with shopware cart table using token column (table_name.cart_token = cart.token).
How can we do this association using DAL as long as cart table doesn't have a CartEntity and CartDefinition.
For example: Select * from table_name leftjoin cart on table_name.cart_token=cart.token where cart.token=null.
Without a definition and accompanying entity class you simply won't be able to retrieve the cart as a mapped object using the DAL. You could add your own definition and entity for the cart table but I wouldn't recommend it, as this would just cause problems if multiple extensions got the same idea. I would recommend injecting Doctrine\DBAL\Connection in a service of your plugin and just fetching the cart using raw SQL.
class CartFetcherService
{
private Connection $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function fetchCart(YourCustomEntity $entity): ?array
{
$cart = $this->connection->fetchAssociative(
'SELECT * FROM `cart` WHERE `token` = :token',
[
'token' => $entity->getToken(),
]
);
return $cart ?: null;
}
}
If you want to retrieve the Cart object directly, you could also inject the Shopware\Core\Checkout\Cart\CartPersister service to load the cart.
class CartLoaderService
{
private CartPersister $persister;
public function __construct(CartPersister $persister)
{
$this->persister = $persister;
}
public function getCart(YourCustomEntity $entity, SalesChannelContext $context): ?Cart
{
try {
$cart = $this->persister->load($entity->getToken(), $context)
} catch (\Throwable $exception) {
$cart = null;
}
return $cart;
}
}

Argument 1 passed to CodeIgniter\Database\BaseResult::getResult()

Argument 1 passed to CodeIgniter\Database\BaseResult::getResult()
the following is the code for my controller and model
the contollers section
namespace Modules\FrontEndBlog\Controllers;
use App\Controllers\BaseController;
use Modules\FrontEndBlog\Models\ModelBlog as ModelBlog;
use CodeIgniter\I18n\Time;
class Blog extends BaseController
{
protected $session;
protected $ModelBlog;
public function __construct(){
$this->session = service('session');
$this->ModelBlog = new ModelBlog();
}
public function index()
{
$pager = \Config\Services::pager();
$blog = $this->ModelBlog->get_blog(1);
dd($blog);
$data = [
'breadcrumbs' => 'Blog List',
'blog' => $blog,
'pager' => $this->ModelBlog->pager,
];
return view('Modules\FrontEndBlog\Views\blog',$data);
}
}
the models section
namespace Modules\FrontEndBlog\Models;
use CodeIgniter\Model;
class ModelBlog extends Model
{
protected $table = 'blog';
protected $useTimestamps = 'true';
protected $db;
public function __construct(){
$this->db = \Config\Database::connect();
}
public function get_blog($blog_page){
return $this
->table('blog')
->select('blog.created_at as tgl_post, blog.random as random_blog, nama_kategori, nama_tags, nama_blog, fullname,content_blog,slug_blog, thumbnail')
->join('kategori_blog', 'kategori_blog.id=blog.id_kategori', 'left')
->join('tags_blog', 'tags_blog.id=blog.id_tags', 'left')
->join('users', 'users.id=blog.id_user', 'left')
->paginate($blog_page);
}
}
how to make pagination codeigniter 4, but model with class method. I
tried but failed, I need a solution to this?
This is a late answer but may be helpful for others.
remove __construct() function from Model class.

Dapper Extensions custom ClassMapper isn't called on Insert()

I'm using Dapper Extensions and have defined my own custom mapper to deal with entities with composite keys.
public class MyClassMapper<T> : ClassMapper<T> where T : class
{
public MyClassMapper()
{
// Manage unmappable attributes
IList<PropertyInfo> toIgnore = typeof(T).GetProperties().Where(x => !x.CanWrite).ToList();
foreach (PropertyInfo propertyInfo in toIgnore.ToList())
{
Map(propertyInfo).Ignore();
}
// Manage keys
IList<PropertyInfo> propsWithId = typeof(T).GetProperties().Where(x => x.Name.EndsWith("Id") || x.Name.EndsWith("ID")).ToList();
PropertyInfo primaryKey = propsWithId.FirstOrDefault(x => string.Equals(x.Name, $"{nameof(T)}Id", StringComparison.CurrentCultureIgnoreCase));
if (primaryKey != null && primaryKey.PropertyType == typeof(int))
{
Map(primaryKey).Key(KeyType.Identity);
}
else if (propsWithId.Any())
{
foreach (PropertyInfo prop in propsWithId)
{
Map(prop).Key(KeyType.Assigned);
}
}
AutoMap();
}
}
I also have this test case to test my mapper:
[Test]
public void TestMyAutoMapper()
{
DapperExtensions.DapperExtensions.DefaultMapper = typeof(MyClassMapper<>);
MySubscribtionEntityWithCompositeKey entity = new MySubscribtionEntityWithCompositeKey
{
SubscriptionID = 145,
CustomerPackageID = 32
};
using (var connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open();
var result = connection.Insert(entity);
var key1 = result.SubscriptionID;
var key2 = result.CustomerPackageID;
}
}
Note that I set the default mapper in the test case.
The insert fails and I notive that my customer mapper is never called. I have no documentation on the github page on the topic, so I'm not sure if there's anything else I need to do to make dapper extensions use my mapper.
Thanks in advance!
Looking at your question, you are attempting to write your own defalut class mapper derived from the existing one. I never used this approach; so I do not know why it is not working or whether it should work.
I explicitly map the classes as below:
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
}
public sealed class CustomerMapper : ClassMapper<Customer>
{
public CustomerMapper()
{
Schema("dbo");
Table("Customer");
Map(x => x.CustomerID).Key(KeyType.Identity);
AutoMap();
}
}
The AutoMap() will map rest of the properties based on conventions. Please refer to these two resources for more information about mapping.
Then I call SetMappingAssemblies at the startup of the project as below:
DapperExtensions.DapperExtensions.SetMappingAssemblies(new[] { Assembly.GetExecutingAssembly() });
The GetExecutingAssembly() is used in above code because mapping classes (CustomerMapper and other) are in same assembly which is executing. If those classes are placed in other assembly, provide that assembly instead.
And that's it, it works.
To set the dialect, I call following line just below the SetMappingAssemblies:
DapperExtensions.DapperExtensions.SqlDialect = new DapperExtensions.Sql.SqlServerDialect();
Use your preferred dialect instead of SqlServerDialect.
Apparently, the solution mentioned here may help you achieve what you are actually trying to. But, I cannot be sure, as I said above, I never used it.

Why do my models return 0 when accessing a string-based primary key model property in Laravel 4?

I have a table set up something like this:
Schema::create('capability', function($T) {
$T->string('code',32)->primary();
$T->string('name',64);
});
And a corresponding model like this:
class Capability extends BaseModel {
protected $table = 'capability';
protected $primaryKey = 'code';
public $timestamps = false;
}
When I seed some data like this...
$c1 = Capability::create(array(
'name' => 'Manage Clients',
'code' => 'manage_clients'
));
...and access the data members of $c1 like this...
echo $c1->name.", ".$c1->code;
...the result is Manage Clients, 0.
Why is the result not Manage Clients, manage_clients as I was expecting?
I needed to add public $incrementing = false to the model class.

Create content error - Specified cast is not valid

I have a custom module. Migrations.cs looks like this.
public int Create()
{
SchemaBuilder.CreateTable("MyModuleRecord", table => table
.ContentPartRecord()
...
);
ContentDefinitionManager.AlterPartDefinition(
typeof(MyModulePart).Name, cfg => cfg.Attachable());
ContentDefinitionManager.AlterTypeDefinition("MyModule",
cfg => cfg
.WithPart("MyModulePart")
.WithPart("CommonPart")
.Creatable()
);
return 1;
}
This is the code I have in the controller.
var newcontent = _orchardServices.ContentManager.New<MyModulePart>("MyModule");
...
_orchardServices.ContentManager.Create(newcontent);
I get the invalid cast error from this New method in Orchard.ContentManagement ContentCreateExtensions.
public static T New<T>(this IContentManager manager, string contentType) where T : class, IContent {
var contentItem = manager.New(contentType);
if (contentItem == null)
return null;
var part = contentItem.Get<T>();
if (part == null)
throw new InvalidCastException();
return part;
}
Any idea what I am doing wrong?
Thanks.
This is the handler.
public class MyModuleHandler : ContentHandler
{
public MyModuleHandler(IRepository<MyModuleRecord> repository)
{
Filters.Add(StorageFilter.For(repository));
}
}
You are getting the InvalidCastException because the content item doesn't appear to have your MyModulePart attached.
If there were a driver for your part, then there is an implicit link somewhere that allows your part to be shown on a content item (I'm not sure how this is done, maybe someone else could elaborate - but it is something to do with how shapes are harvested and picked up by the shape table deep down in Orchard's core).
However since you don't have a driver, adding an ActivatingFilter to your part's handler class will make the link explicitly:
public MyModulePartHandler : ContentHandler {
public MyModulePartHandler() {
Filters.Add(StorageFilter.For(repository));
Filters.Add(new ActivatingFilter<MyModulePart>("MyModule");
}
}
Your part table name is wrong. Try renaming it to this (so the part before "Record" matches your part model name exactly):
SchemaBuilder.CreateTable("MyModulePartRecord", table => table
.ContentPartRecord()
...
);

Resources