Controller

Basic Controller

The simplest controller with no extra actions and operations.

namespace Foo\Controllers\Frontend;

use Vegas\Mvc\Controller\ControllerAbstract;

class FooController extends ControllerAbstract
{
    public function indexAction()
    {
        $this->view->foo = 'Vegas';
    }
}

Utility methods:

  • jsonResponse($data = []) - prepare JSON response (disabling view, setting content type and content).
  • _($string) - alias for $this->i18n->_(). Works only if internationalization service is provided.
  • throw403($message = '') - throws 403 forbidden exception that will be catched by Vegas\Mvc\Dispatcher\ExceptionResolver.
  • throw404($message = '') - throws 404 page not found exception that will be catched by Vegas\Mvc\Dispatcher\ExceptionResolver.
  • throw500($message = '') - throws 500 internal error exception that will be catched by Vegas\Mvc\Dispatcher\ExceptionResolver.

CRUD Controller

Provides you default CREATE, READ, UPDATE, DELETE operations.

namespace Foo\Controllers\Backend;

use Vegas\Mvc\Controller\CrudAbstract;
use Vegas\Mvc\Controller\Crud\Events;

class FooController extends CrudAbstract
{
    /**
     * @var string - Required. It will be displayed in new.volt and edit.volt template.
     */
    protected $formName = 'Foo\Forms\Bar';

    /**
     * @var string - Required. It will be used to create, refresh, update, delete items.
     */
    protected $modelName = 'Foo\Models\Bar';

    /**
     * @var array - Optional. Pairs of field name => field label that will be used for records listing. Set if you want to use default indexAction.
     */
    protected $indexFields = [
        'name' => 'Name',
        'url' => 'Url',
        'created_at' => 'Created at'
    ];

    /**
     * @var array - Optional. Pairs of field name => field label that will be used for records details. Set if you want to use default showAction.
     */
    protected $showFields = [
        'name' => 'Project name',
        'url' => 'Project url'
    ];
}

Flow and available events for CRUD actions:

  • showAction($id)
    1. beforeRead() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_READ) - is triggered before retrieving object
    2. afterRead() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_READ) - is triggered after retrieving object
    3. Foo\views\backend\foo\show.volt view is loaded if exists. In other case default CRUD template will be used.
  • newAction()
    1. beforeNew() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_NEW) - is triggered before reading the form to the view
    2. afterNew() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_NEW) - is triggered after reading the form to the view
    3. Foo\views\backend\foo\new.volt view is loaded if exists. In other case default CRUD template will be used.
  • createAction()
    1. beforeCreate (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_CREATE) - is triggered before any instruction in action
    2. beforeSave (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_SAVE) - is triggered before create operation (and also before update operation in updateAction())
    3. afterSave (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_SAVE) - is triggered after create operation (and also after update operation in updateAction())
    4. afterCreate (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_CREATE) - is triggered after create operation
    5. Vegas\Mvc\Controller\Crud\Events::AFTER_CREATE_EXCEPTION - is triggered when any exception is thrown during create operation
  • editAction()
    1. beforeRead() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_READ) - is triggered before reading record from database
    2. afterRead() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_READ) - is triggered after reading record from database
    3. beforeEdit() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_EDIT) - is triggered after reading record from database and before binding record with form
    4. afterEdit() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_EDIT) - is triggered after binding record with form
    5. Foo\views\backend\foo\edit.volt view is loaded if exists. In other case default CRUD template will be used.
  • updateAction()
    1. beforeRead() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_READ) - is triggered before reading record from database
    2. afterRead() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_READ) - is triggered after reading record from database
    3. beforeUpdate() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_UPDATE) - is triggered before update operation
    4. beforeSave() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_SAVE) - is triggered before update operation (and also before create operation in createAction())
    5. afterSave() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_SAVE) - is triggered after update operation (and also after insert operation in createAction())
    6. afterUpdate() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_UPDATE - is triggered after update operation
    7. Vegas\Mvc\Controller\Crud\Events::AFTER_UPDATE_EXCEPTION - is triggered when any exception is thrown during update operation
  • deleteAction()
    1. beforeRead() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_READ) - is triggered before reading record from database
    2. afterRead() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_READ) - is triggered after reading record from database
    3. beforeDelete() (Alias: Vegas\Mvc\Controller\Crud\Events::BEFORE_DELETE) - is triggered before delete operation
    4. afterDelete() (Alias: Vegas\Mvc\Controller\Crud\Events::AFTER_DELETE) - is triggered after delete operation


Sample ODM model for Foo controller:

namespace Foo\Models;

use Vegas\Db\Decorator\CollectionAbstract;

class Bar extends CollectionAbstract
{
    public function getSource()
    {
        return 'bar'; //Name of collection
    }
} 


Sample form for Foo controller:

namespace Foo\Forms;

use Phalcon\Forms\Element\Text;

class Bar extends \Phalcon\Forms\Form
{
    public function initialize()
    {
        $field = new Text('fake_field');
        $this->add($field);
    }
}


Sample routing saved in Foo\config\routing.php:

return array(
    'foo' => array(
        'route' => '/foo/:action/:params',
        'paths' => array(
            'module' => 'Foo',
            'controller' => 'Backend\Foo',
            'action' => 1,
            'params' => 2
        )
    )
);

Required views you must have in Foo\views\backend\foo directory:

  • index.volt - should list items loaded and assigned to the view variable in indexAction()
  • new.volt - should display form to create record
    <form action="{{ url.get(['for':'foo/crud', 'action':'create']) }}" method="post">
        {{ partial('backend/foo/_form', ['form': form]) }}
    </form>
    
  • edit.volt - should display form to edit record
    <form action="{{ url.get(['for':'foo/crud', 'action':'update', 'params': record._id]) }}" method="post">
        {{ partial('backend/foo/_form', ['form': form]) }}
    </form>
    
  • _form.volt - form html
    {% for element in form %}
        {% do element.setAttribute('class', element.getAttribute('class')~' form-control') %}
        {% set hasErrors = form.hasMessagesFor(element.getName()) %}
    
        <div class="clearfix form-group{% if hasErrors %} has-error{% endif %}">
            <label for="{{ element.getName() }}">{{ element.getLabel() }}</label>
            {% if hasErrors %}
                <span class="help-block">
                {% for error in form.getMessagesFor(element.getName()) %}
                    {{ error }}
                {% endfor %}
                </span>
            {% endif %}
            {{ element }}
        </div>
    {% endfor %}
    
    <div class="form-group">
        <button type="submit" class="btn btn-flat success">Save</button>
        <a href="{{ url.get(['for':'foo/crud', 'action':'index']) }}" class="btn pull-right">Cancel</a>
    </div>

CRUD Upload Controller

Provides you all CRUD operations and UPLOAD. To use it you must make sure you have uploader in DI. Read more.

namespace Category\Controllers\Backend;

use Vegas\Media\Helper As MediaHelper;
use Vegas\Mvc\Controller\CrudUploadAbstract;

class CategoryController extends CrudUploadAbstract
{
    /**
     * @var string - Required. It will be displayed in new.volt and edit.volt template.
     */
    protected $formName = 'Foo\Forms\Bar';

    /**
     * @var string - Required. It will be used to create, refresh, update, delete items.
     */
    protected $modelName = 'Foo\Models\Bar';

    /**
     * @var array - Optional. Pairs of field name => field label that will be used for records listing. Set if you want to use default indexAction.
     */
    protected $indexFields = [
        'name' => 'Name',
        'url' => 'Url',
        'created_at' => 'Created at'
    ];

    /**
     * @var array - Optional. Pairs of field name => field label that will be used for records details. Set if you want to use default showAction.
     */
    protected $showFields = [
        'name' => 'Project name',
        'url' => 'Project url'
    ];

    protected function afterSave()
    {
        $this->processImages();
        parent::afterSave();
    }

    private function processImages()
    {
        try {
            $record =  $this->scaffolding->getRecord(); /// retrieving current record from scaffolding
            $mapped = $record->readMapped('image'); // reading mapped image object

            MediaHelper::moveFilesFrom($mapped);
            MediaHelper::generateThumbnailsFrom($mapped, ['width' => 600, 'height' => 300]);
        } catch(\Exception $e) {
            $this->flash->error($e->getMessage());
        }
    }
}