Custom Add Function

I’ve created this function add_data()

 public function add_database()
    {
        if ($this->getUser()->userTypeId != 1)
            throw new AccessDeniedException();
    

        $client = $this->MyFactory->createEmpty();
        $client->dbhost = $this->getSanitizer()->getString('dbhost');
        $client->dbuser = $this->getSanitizer()->getString('dbuser');
        $client->dbpass = $this->getSanitizer()->getString('dbpass');
        $client->dbname = $this->getSanitizer()->getString('dbname');
        $client->company = $this->getSanitizer()->getString('company');
        $client->logo = $this->getSanitizer()->getString('logo');
        $client->save();


        $this->getState()->hydrate([
            'message' => sprintf(__('Added %s'), $client->company),
            'id' => $client->id,
            'data' => $client
        ]);
    }

but it doesn’t work,

:frowning:

That isn’t declared anywhere

Other than the above, i’m really not sure what you are trying to do, so its really hard to help :slight_smile:

Im sorry I copied the wrong code.
this are my codes

<?php
namespace Xibo\custom;

use MyFactory;
use Xibo\Controller\Base;
use Xibo\Service\ConfigServiceInterface;
use Xibo\Service\DateServiceInterface;
use Xibo\Service\LogServiceInterface;
use Xibo\Service\SanitizerServiceInterface;
use Illuminate\Database\Query\Builder;
use Xibo\Exception\AccessDeniedException;

/**
 * Class MyController
 * @package Xibo\Custom
 */
class MyController extends Base
{
    /**
     * @var MyFactory
     */
    private $myFactory;
     /**
     * Set common dependencies.
     * @param LogServiceInterface $log
     * @param SanitizerServiceInterface $sanitizerService
     * @param \Xibo\Helper\ApplicationState $state
     * @param \Xibo\Entity\User $user
     * @param \Xibo\Service\HelpServiceInterface $help
     * @param DateServiceInterface $date
     * @param ConfigServiceInterface $config
     * @param MyFactory $myFactory
     */
    public function __construct($log, $sanitizerService, $state, $user, $help, $date, $config, $myFactory )
    {
        $this->setCommonDependencies( $log, $sanitizerService, $state, $user, $help, $date, $config);
        $this->myFactory = $myFactory;
    }
    /**
     * Display Page for Test View
     */


    public function testView()
    {
        $this->getState()->template = 'clients-page';
    }

    public function grid()
    {

    }

    public function addView()
    {
        if ($this->getUser()->userTypeId != 1)
            throw new AccessDeniedException();
        $this->getState()->template = 'clients-form-add';
    }

    public function add_database()
    {
        if ($this->getUser()->userTypeId != 1)
            throw new AccessDeniedException();

        $client = $this->myFactory->createEmpty();
        $client->dbhost = $this->getSanitizer()->getString('dbhost');
        $client->dbuser = $this->getSanitizer()->getString('dbuser');
        $client->dbpass = $this->getSanitizer()->getString('dbpass');
        $client->dbname = $this->getSanitizer()->getString('dbname');
        $client->company = $this->getSanitizer()->getString('company');
        $client->logo = $this->getSanitizer()->getString('logo');
        $client->save();


        $this->getState()->hydrate([
            'message' => sprintf(__('Added %s'), $client->company),
            'id' => $client->id,
            'data' => $client
        ]);
    }
}

I’ve also created a factory file but i don’t know its purpose though i’ve still created it
It looks like this.
<?php
/*
* Spring Signage Ltd - http://www.springsignage.com
* Copyright © 2015 Spring Signage Ltd
* (MyFactory.php)
*/

namespace Xibo\Custom;

use MyEntity;
use Xibo\Exception\NotFoundException;
use Xibo\Service\LogServiceInterface;
use Xibo\Service\SanitizerServiceInterface;
use Xibo\Storage\StorageServiceInterface;

class MyFactory extends BaseFactory
{
    /**
     * Construct a factory
     * @param StorageServiceInterface $store
     * @param LogServiceInterface $log
     * @param SanitizerServiceInterface $sanitizerService
     */
    public function __construct($store, $log, $sanitizerService)
    {
        $this->setCommonDependencies($store, $log, $sanitizerService);
    }
    /**
     * @return Clients
     */
    public function createEmpty()
    {
        return new Clients(
            $this->getStore(),
            $this->getLog()
        );
    }
}
<?php
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2015 Spring Signage Ltd
 * (Help.php)
 */


namespace Xibo\Custom;

use Respect\Validation\Validator as v;
use Xibo\Exception\InvalidArgumentException;
use Xibo\Service\LogServiceInterface;
use Xibo\Storage\StorageServiceInterface;


class Clients
{
    use EntityTrait;


    public $id;


    public $dbhost;

 
    public $dbuser;


    public $dbpass;

    public $dbname;

    public $logo;
 
    public $company;

  
    public function __construct($store, $log)
    {
        $this->setCommonDependencies($store, $log);
    }

    private function add()
    {
        $this->id = $this->getStore()->insert('INSERT INTO `jm_clients` (id, dbhost, dbuser, dbpass, dbname, logo, company) VALUES (:id, :dbhost, :dbuser, :dbpass, :dbname, :logo, :company)', [
            'id' => $this->id,
            'dbhost' => $this->dbhost,
            'dbuser' => $this->dbuser,
            'dbpass' => $this->dbpass,
            'dbname' => $this->dbname,
            'logo' => $this->logo,
            'company' => $this->company
        ]);
    }


}

Hello Dan, sorry for confusing you. :slight_smile:

I’m trying to create a custom function that focus to add a data to the database. So to prevent the overwrite this code when I updated the main Xibo core. So I created all the files in the /custom folder.

My big problem is I cannot save the fetch data to the fields database. Do you have any example of Adding function codes to guide?

These are the codes that I’ve already created.

In my Controller.php

    <?php
namespace Xibo\custom;

use MyFactory;
use Xibo\Controller\Base;
use Xibo\Service\ConfigServiceInterface;
use Xibo\Service\DateServiceInterface;
use Xibo\Service\LogServiceInterface;
use Xibo\Service\SanitizerServiceInterface;
use Illuminate\Database\Query\Builder;
use Xibo\Exception\AccessDeniedException;

/**
 * Class MyController
 * @package Xibo\Custom
 */
class MyController extends Base
{
    /**
     * @var MyFactory
     */
    private $myFactory;
     /**
     * Set common dependencies.
     * @param LogServiceInterface $log
     * @param SanitizerServiceInterface $sanitizerService
     * @param \Xibo\Helper\ApplicationState $state
     * @param \Xibo\Entity\User $user
     * @param \Xibo\Service\HelpServiceInterface $help
     * @param DateServiceInterface $date
     * @param ConfigServiceInterface $config
     * @param MyFactory $myFactory
     */
    public function __construct($log, $sanitizerService, $state, $user, $help, $date, $config )
    {
        $this->setCommonDependencies( $log, $sanitizerService, $state, $user, $help, $date, $config);
        // $this->myFactory = $myFactory;
    }
    /**
     * Display Page for Test View
     */


    public function testView()
    {
        $this->getState()->template = 'clients-page';
    }

    public function grid()
    {

    }

    public function addView()
    {
        if ($this->getUser()->userTypeId != 1)
            throw new AccessDeniedException();
        $this->getState()->template = 'clients-form-add';
    }

    public function add_database()
    {
        if ($this->getUser()->userTypeId != 1)
            throw new AccessDeniedException();

        $client = $this->myFactory->createEmpty();
        $client->dbhost = $this->getSanitizer()->getString('dbhost');
        $client->dbuser = $this->getSanitizer()->getString('dbuser');
        $client->dbpass = $this->getSanitizer()->getString('dbpass');
        $client->dbname = $this->getSanitizer()->getString('dbname');
        $client->company = $this->getSanitizer()->getString('company');
        $client->logo = $this->getSanitizer()->getString('logo');
        $query->save();


        $this->getState()->hydrate([
            'message' => sprintf(__('Added %s'), $client->company),
            'id' => $client->id,
            'data' => $client
        ]);
    }
}

In my MyFactory.php
<?php
/*
* Spring Signage Ltd - http://www.springsignage.com
* Copyright © 2015 Spring Signage Ltd
* (MyFactory.php)
*/

namespace Xibo\Custom;

use MyEntity;
use Xibo\Exception\NotFoundException;
use Xibo\Service\LogServiceInterface;
use Xibo\Service\SanitizerServiceInterface;
use Xibo\Storage\StorageServiceInterface;

class MyFactory extends BaseFactory
{
    /**
     * Construct a factory
     * @param StorageServiceInterface $store
     * @param LogServiceInterface $log
     * @param SanitizerServiceInterface $sanitizerService
     */
    public function __construct($store, $log, $sanitizerService)
    {
        $this->setCommonDependencies($store, $log, $sanitizerService);
    }
    /**
     * @return Clients
     */
    public function createEmpty()
    {
        return new Clients(
            $this->getStore(),
            $this->getLog()
        );
    }
}

MyEntity.php File

<?php
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2015 Spring Signage Ltd
 * (Help.php)
 */


namespace Xibo\Custom;

use Respect\Validation\Validator as v;
use Xibo\Exception\InvalidArgumentException;
use Xibo\Service\LogServiceInterface;
use Xibo\Storage\StorageServiceInterface;

/**
 * Class Help
 * @package Xibo\Entity
 *
 * @SWG\Definition()
 */
class Clients
{
    use EntityTrait;

    /**
     * @SWG\Property(description="The ID of this jm_clients Record")
     * @var int
     */
    public $id;

    /**
     * @SWG\Property(description="The topic for this Help Record")
     * @var string
     */
    public $dbhost;

    /**
     * @SWG\Property(description="The Category for this Help Record")
     * @var string
     */
    public $dbuser;

    /**
     * @SWG\Property(description="The Link to the Manual for this Help Record")
     * @var string
     */
    public $dbpass;
    /**
     * @SWG\Property(description="The Link to the Manual for this Help Record")
     * @var string
     */
    public $dbname;
    /**
     * @SWG\Property(description="The Link to the Manual for this Help Record")
     * @var string
     */
    public $logo;
    /**
     * @SWG\Property(description="The Link to the Manual for this Help Record")
     * @var string
     */
    public $company;

    /**
     * Entity constructor.
     * @param StorageServiceInterface $store
     * @param LogServiceInterface $log
     */
    public function __construct($store, $log)
    {
        $this->setCommonDependencies($store, $log);
    }

    private function add()
    {
        $this->id = $this->getStore()->insert('INSERT INTO `jm_clients` (id, dbhost, dbuser, dbpass, dbname, logo, company) VALUES (:id, :dbhost, :dbuser, :dbpass, :dbname, :logo, :company)', [
            'id' => $this->id,
            'dbhost' => $this->dbhost,
            'dbuser' => $this->dbuser,
            'dbpass' => $this->dbpass,
            'dbname' => $this->dbname,
            'logo' => $this->logo,
            'company' => $this->company
        ]);
    }


}

MyMiddleware.php File
<?php
namespace Xibo\Custom;

use Slim\Middleware;

/**
 * Class MyMiddleware
 * @package Xibo\custom
 *
 * Included by instantiation in `settings.php`
 */
class MyMiddleware extends Middleware
{
    public function call()
    {
        $app = $this->getApplication();

        // Register some new routes
        $app->get('/clients', '\Xibo\Custom\MyController:testView')->setName('client.view');
        $app->get('/clients', '\Xibo\Custom\MyController:grid')->setName('clients.search');

        $app->get('/clients/add', '\Xibo\Custom\MyController:addView')->setName('client.add.form');
        $app->post('/clients/add', '\Xibo\Custom\MyController:add_database')->setName('client.add');


        // Register a new controller with DI
        // This Controller uses the CMS standard set of dependencies. Your controller can
        // use any dependencies it requires.
        // If you want to inject Factory objects, be wary of circular references.
        $app->container->singleton('\Xibo\Custom\MyController', function($container) {
            return new \Xibo\Custom\MyController(
                $container->logService,
                $container->sanitizerService,
                $container->state,
                $container->user,
                $container->helpService,
                $container->dateService,
                $container->configService
            );
        });

        // Next middleware
        $this->next->call();
    }
}

In Theme/custom/nvdigital/views/clients-form-add.twig

{#
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2015 Spring Signage Ltd
 * (${FILE_NAME})
 */

#}
{% extends "form-base.twig" %}
{% import "forms.twig" as forms %}

{% block formTitle %}
    {% trans "Add Client" %}
{% endblock %}

{% block formButtons %}
    {% trans "Cancel" %}, XiboDialogClose()
    {% trans "Save" %}, $("#clientaddform").submit()
{% endblock %}

{% block formHtml %}
    <div class="row">
        <div class="col-md-12">
            <form id="clientaddform" class="XiboForm form-horizontal" method="post" action="{{ urlFor("client.add") }}">

                    {% set title %}{% trans "LOGO" %}{% endset %}
                    {{ forms.input("logo", title, "", helpText) }}

                    {% set title %}{% trans "COMPANY" %}{% endset %}
                    {{ forms.input("company", title, "", helpText) }}

                    {% set title %}{% trans "DBHOST" %}{% endset %}
                    {{ forms.input("dbhost", title, "", helpText) }}

                    {% set title %}{% trans "DBUSER" %}{% endset %}
                    {{ forms.input("dbuser", title, "", helpText) }}

                    {% set title %}{% trans "DBPASS" %}{% endset %}
                    {{ forms.input("dbpass", title, "", helpText) }}

                    {% set title %}{% trans "DBNAME" %}{% endset %}
                    {{ forms.input("dbname", title, "", helpText) }}

            </form>
        </div>
    </div>
{% endblock %}

In Theme/custom/nvdigital/views/clients-page.twig

{#
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2015 Spring Signage Ltd
 * (campaign-page.twig)
 */
This is the template for the campaign page
#}
{% extends "authed.twig" %}
{% import "inline.twig" as inline %}

{% block actionMenu %}
    <div class="page-title">
      <h4>{% trans "Add a new Client" %}</h4>
      <a href="{{ urlFor("client.add.form") }}" class="XiboFormButton add-new-campaign"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add New Client</a>
    </div>
{% endblock %}

{% block pageContent %}
    <div class="widget">
        <div class="widget-title">{% trans "Clients" %}</div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}">

                <div class="XiboData">
                    <table id="clients" class="table table-striped">
                        <thead>
                            <tr>
                                <th>{% trans "ID" %}</th>
                                <th>{% trans "DB Host" %}</th>
                                <th>{% trans "DB Username" %}</th>
                                <th>{% trans "DB Password" %}</th>
                                <th>{% trans "DB Name" %}</th>
                                <th>{% trans "Client" %}</th>
                                <th>{% trans "Logo" %}</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block javaScript %}
<script type="text/javascript">
    var table = $("#clients").DataTable({ "language": dataTablesLanguage,
        serverSide: true, stateSave: true,
        filter: false,
        searchDelay: 3000,
        "order": [[ 1, "asc"]],
        ajax: {
            "url": "{{ urlFor("clients.search") }}",
            "data": function(d) {
                $.extend(d, $("#clients").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
            }
        },
        "columns": [
            { "data": "id"},
            { "data": "dbhost"},
            { "data": "dbuser"},
            { "data": "dbpass"},
            { "data": "dbname"},
            { "data": "logo"},
            { "data": "company"},
            {
                "orderable": false,
                "data": dataTableButtonsColumn
            }
        ]
    });

    table.on('draw', dataTableDraw);
    table.on('processing.dt', dataTableProcessing);
</script>
{% endblock %}

Your controller is using $this->myFactory, but you don’t assign that member anywhere - you need to inject that from your Middleware, and assign it to a member variable in your constructor.

In your middleware you are creating a MyController class, passing some parameters - if you want to use MyFactory in there, then you also need to pass that.

MyEntity.php should contain a class called MyEntity not Clients - the naming is important as it is used by PHP for auto loading.

Those are the problems I see at the moment - but there might be more

1 Like

Hello Dan,

Good day.
I did what you have told to do and the myFactory.php file works now.
Also I change the > Clients class into > MyEntity in the myEntity.php file

But still the adding function doesn’t work.
I’m really a beginner with this though. Can you help me with it.
It would be a great help.

MyMiddleware.php

MyController.php

Hello Dan.

I’m still having a hard time doing this.
Can I ask you for a working example of a custom CRUD.

Best regards.

There are tons of working examples of CRUD in the source code itself - most operations are CRUD! The route you’re following is full “OOP” - as you are a beginner in this area it might be better to start with a simple controller and remove the factory/entity concepts until you are more experienced?

You can inject the $store into your controller (using the constructor) and then use $this->store->insert($sql, $params) to insert and $this->store->update($sql, $params); to update.

I can’t provide you with a specific working example for your use case, because it will take a little bit of time and I don’t have any at the moment, sorry.

1 Like

It’s fine Dan.
Thanks for the tip. :slight_smile:

1 Like

I’ve been trying to copy the Controller/help.php that’s why I have those entity and factory.
I think its gonna work if i can just connect the controller into the factory and Entity…

I’m not really familiar with the slim framework, that is why i’m really having a hard time.

Most of that has nothing to do with Slim - its just OOP.

What is the error you get now?

I’m still trying to do what you told to.