Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Setup the filter for a table
* #param dataTable data source to setup
*/
private setupFilter(dataTable: MatTableDataSource<Element>) {
dataTable.filterPredicate = (data: any, filter: string) => {
filter = filter.toLowerCase();
return data.name.toLowerCase().includes(filter)
|| data.description.toString().includes(filter);
};
}
Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Checking control validation for edit inputs
* #param value Equals to ngmodel for the input
* #param column Equals to column name
*/
public editControlHasError(value: string, column: string): void {
if (column === 'name') {
this.errorInName.required = value === '';
this.errorInName.maxlength = value.length > Constants.MAX_LENGTH_NAME;
return;
}
this.errorInDescription.required = value === '';
this.errorInDescription.maxlength = value.length > Constants.MAX_LENGTH_DESCRIPTION;
}
Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Methode that apply the table filter
* #param filterValue the filter value
*/
public applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Clear the filters value
*/
clearFilters() {
this.filter = '';
this.dataSource.filter = '';
}
Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Method that loads a list of profiles to display on the rol select
*/
private loadProfiles() {
this.loaders.dataSource = true;
this.profilesService.getAllProfiles()
.pipe(
finalize(() => {
this.loaders.dataSource = false;
this.updateDOM();
})
)
.subscribe(
data => {
this.dataSource = new MatTableDataSource<Element>(data);
// getting properties from the object to sort the column from nested objects
this.dataSource.sortingDataAccessor = (obj, property) =>
this.getProperty(obj, property);
this.dataSource.sort = this.sort;
this.setupFilter(this.dataSource);
}
);
}
Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Method that create a Profile
*/
public addProfile() {
for (const key in this.profileForm.controls) {
if (this.profileForm.controls[key] &&
this.profileForm.controls[key].value.toString().trim() === '') {
this.profileForm.controls[key].setValue('');
}
}
if (this.profileForm.valid) {
this.loaders.process = true;
const profile: Profile = new Profile();
profile.idProfile = 0;
profile.name = this.profileForm.controls.name.value.trim();
profile.description = this.profileForm.controls.description.value.trim();
this.profilesService.addProfile(profile).subscribe(
data => {
this.loaders.process = false;
this.profileForm.reset();
this.loadProfiles();
this.showModalAlert(data);
}
);
}
}
Some methods angular material, i need to unit test of each one, but i don't know how
/**
* Method that loads a profile for edit from the list
*/
public loadEditProfile(element: Profile) {
if (this.dataSource.data.some((e: any) => !!e.edit)) {
this.cancelEdit();
this.initErrorCheckers();
}
this.profileElementTmp = JSON.parse(JSON.stringify(element));
this.profileElementAux = element;
element.edit = true;
}
Some methods angular material, i need to unit test of each one, but i don't know how
Related
I would like to return a different result for a computed field when viewing the index view than when viewing the detail view of a resource.
Basically something like viewIs() below:
Text::make('Preview', function () {
if($this->viewIs('index'){
return \small_preview($this->image);
}
return \large_preview($this->image);
})->asHtml(),
You can check the class of the request:
Text::make('Preview', function () use ($request) {
if ($request instanceof \Laravel\Nova\Http\Requests\ResourceDetailRequest) {
return \large_preview($this->image);
}
return \small_preview($this->image);
});
Otherwise, you can create your own viewIs function:
// app/Nova/Resource.php
/**
* Check the current view.
*
* #param string $view
* #param \Laravel\Nova\Http\Requests\NovaRequest $request
* #retrun bool
*/
public function viewIs($view, $request)
{
$class = '\Laravel\Nova\Http\Requests\\Resource'.ucfirst($view).'Request';
return $request instanceof $class;
}
Then you can do it like this:
Text::make('Preview', function () use ($request) {
if ($this->viewIs('detail', $request) {
return \large_preview($this->image);
}
return \small_preview($this->image);
});
Unfortunately, #Chin's answer did not work for me as for Edit view the request class is just a basic Laravel\Nova\Http\Request class.
My workaround to check if this is an index view is as follows:
/**
* Check if the current view is an index view.
*
* #param \Laravel\Nova\Http\Requests\NovaRequest $request
* #return bool
*/
public function isIndex($request)
{
return $request->resourceId === null;
}
The NovaRequest class will soon be able to help, as the isResourceIndexRequest and isResourceDetailRequest are already in master.
As the Nova repo is private I will keep you posted, when it will be usable.
In the meantime I am falling back to helper methods on the Nova Resource class (app/Nova/Resource.php):
namespace App\Nova;
use Laravel\Nova\Http\Requests\ResourceDetailRequest;
use Laravel\Nova\Http\Requests\ResourceIndexRequest;
use Laravel\Nova\Resource as NovaResource;
use Laravel\Nova\Http\Requests\NovaRequest;
abstract class Resource extends NovaResource
{
// [...]
/**
* Determine if this request is a resource index request.
*
* #return bool
*/
public function isResourceIndexRequest($request)
{
return $request instanceof ResourceIndexRequest;
}
/**
* Determine if this request is a resource detail request.
*
* #return bool
*/
public function isResourceDetailRequest($request)
{
return $request instanceof ResourceDetailRequest;
}
}
Usage:
public function fields(Request $request)
{
$fields = [
// [...]
];
if ($this->isResourceDetailRequest($request)) {
if ($this->isResourceDetailRequest($request)) {
$fields = array_merge($fields, [
// [...]
]);
}
}
return $fields;
}
I added this little helper class
namespace App\Helpers;
class CurrentResourceAction {
public static function isIndex($request)
{
return $request instanceof \Laravel\Nova\Http\Requests\ResourceIndexRequest;
}
public static function isDetail($request)
{
return $request instanceof \Laravel\Nova\Http\Requests\ResourceDetailRequest;
}
public static function isCreate($request)
{
return $request instanceof \Laravel\Nova\Http\Requests\NovaRequest &&
$request->editMode === 'create';
}
public static function isUpdate($request)
{
return $request instanceof \Laravel\Nova\Http\Requests\NovaRequest &&
$request->editMode === 'update';
}
}
you can call it anywhere you need to
A bit late but hey! You can check against the NovaRequest properties editing and editMode ('create', 'update', 'attach' etc.)
// Determine if you are creating a model.
$request->editMode == 'create';
Or as they say, "Read the source Luke" and see how they determine it. See the Laravel\Nova\Http\Requests\NovaRequest, it contains similar checks.
namespace Laravel\Nova\Http\Requests;
class NovaRequest extends FormRequest
{
/**
* Determine if this request is via a many to many relationship.
*
* #return bool
*/
public function viaManyToMany();
/**
* Determine if this request is an attach or create request.
*
* #return bool
*/
public function isCreateOrAttachRequest();
/**
* Determine if this request is an update or update-attached request.
*
* #return bool
*/
public function isUpdateOrUpdateAttachedRequest();
/**
* Determine if this request is a resource index request.
*
* #return bool
*/
public function isResourceIndexRequest();
/**
* Determine if this request is a resource detail request.
*
* #return bool
*/
public function isResourceDetailRequest();
/**
* Determine if this request is an action request.
*
* #return bool
*/
public function isActionRequest();
}
Would've been nice if you can type hint the NovaRequest instead of the regular one in the Nova resource fields() method but it is not allowed due to the parent resource being extended.
You can create two separate fields for index & details page.
// ----- For Index page
Text::make('Preview', function () {
return \small_preview($this->image);
})
->onlyOnIndex()
->asHtml(),
// ----- For Detail page
Text::make('Preview', function () {
return \large_preview($this->image);
})
->onlyOnDetail()
->asHtml(),
I'm having an issue with Zend Framework 2's SQL class. It's saying it cannot find a certain column in the table but the column is there. I've run into this problem before and had to use actual SQL syntax instead of building the query. I rather not have to resort to putting the actual syntax in and instead figure out why this is happening so I can avoid having this issue in the future.
Here is my code:
namespace Members\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Predicate;
use Members\Model\Interfaces\FeedInterface;
use Members\Model\Exceptions\FeedException;
class FeedModel implements FeedInterface
{
/**
* #var TableGateway
*/
public $gateway;
/**
* #var string
*/
public $user;
/**
* #var Sql
*/
public $sql;
/**
* #var Select
*/
public $select;
/**
* Constructor method for FeedModel class
* #param TableGateway $gateway
* #param string $user
*/
public function __construct(TableGateway $gateway, $user)
{
$this->gateway = $gateway instanceof TableGateway ? $gateway : null;
$this->select = new Select();
$this->sql = new Sql($this->gateway->getAdapter());
$this->user = $user;
}
/**
* {#inheritDoc}
* #see \Members\Model\Interfaces\FeedInterface::listFriendsStatus()
*/
public function listFriendsStatus()
{
// get the friend ids based on user id
// and then compare the friend id to the id in status table
$friend_query = $this->select->columns(array('*'))
->from('friends')
->where(array('user_id' => $this->getUserId()['id'])); // the issue
file_put_contents(getcwd() . '/public/query.txt', $this->sql->buildSqlString($friend_query));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($friend_query),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
$friend_id = array();
foreach ($query as $result) {
$friend_id[] = $result;
}
$this->select->columns(array('status'))
->from('status')
->where(array('id' => array_values($friend_id), new Predicate\IsNotNull('id')));
$status_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($this->select),
Adapter::QUERY_MODE_EXECUTE
);
if ($status_query->count() > 0) {
// check if a image was used
$this->select->columns('username')
->from('members')
->where(array('id' => array_values($friend_id), new Predicate\IsNotNull('id')));
$image_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($this->select),
Adapter::QUERY_MODE_EXECUTE
);
if ($image_query->count() > 0) {
$status_dir = array();
foreach ($image_query as $value) {
if (#!is_dir(getcwd() . '/public/images/profile/' . $value['username'] . '/status/')) {
continue;
}
$status_dir[] = getcwd() . '/public/images/profile/' . $value['username'] . '/status/';
}
$images = array();
// retrieve the image inside the status directory
foreach (array_diff(scandir($status_dir, 1), array('.', '..')) as $values) {
$images[] = $values;
}
} else {
throw new FeedException("The user does not exist in the user table.");
}
$status = array();
// get all the statuses
foreach ($status_query as $rows) {
$status[] = $rows;
}
return array('status' => $status, 'images' => $images);
} else {
throw new FeedException("No status was found for your friends.");
}
} else {
throw new FeedException(sprintf("Could not locate any friends for %s", $this->user));
}
}
/**
* {#inheritDoc}
* #see \Members\Model\Interfaces\FeedInterface::hideFriendsStatus()
*/
public function hideFriendsStatus($friend_id)
{
}
/**
* Grabs the user id for the user
*
* #return int|boolean
*/
public function getUserId()
{
$this->select->columns(array('*'))
->from('members')
->where(array('username' => $this->user));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($this->select),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
foreach ($query as $result) {
$row = $result;
}
return $row;
}
return false;
}
}
This is the exception message I am getting:
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause'
But as you can see in this screenshot, the column user_id exists in the friends table I have in place:
So my question is why is it doing this and how can I in the future avoid this issue?
Thanks!
It looks like the select is causing the issue.
Since your code ->from('friends') is called first and then it is overridden due to this function call $this->getUserId(), which overrides the friends table to members due to ->from('members').
Try changing your code to.
$userId = $this->getUserId()['id'];
$friend_query = $this->select->columns(array('*'))
->from('friends')
->where(array('user_id' => $userId));
This should work, but if it doesn't, try to just create new select object $select = new Select(); in both the functions rather than $this->select = new Select();.
is it possible to use different Slave-Connections by using the MasterSlaveFeature in a TableGateway?
I successfully managed to implement the MasterSlaveFeature with one Slave.
I think it is not possible. If you look at the MasterSlaveFeature code you see there is only one $slaveAdapter possible.
If you would like to have a "MultipleMasterSlaveFeature", I guess you have to write it by your own.
You should have a good strategy in mind to select one of your slave adapters, e.g. random select, time dependend or another strategy...
Such class could look like the following code...
class MultipleMasterSlaveFeature extends AbstractFeature {
// Array with AdapterInterface objects
protected $slaveAdpters = null;
//
protected $masterSql = null;
//
protected $slaveSql = null;
/**
*
* #param array $slaveAdapters
* #param Sql $slaveSql
*/
public __construct(array $slaveAdapters, $slaveSql = null)
{
$this->slaveAdapters = $slaveAdapters;
if ($slaveSql) {
$this->slaveSql = $slaveSql;
}
}
// ...
/**
* after initialization, retrieve the original adapter as "master"
*/
public function postInitialize()
{
// Select one of the specified slave adapters
// .. depending on timestamp
$selectedSlaveAdapter = (count($this->slaveAdapters) == 0) ? null : $this->slaveAdapters[time() % count($this->slaveAdapters)];
// ..from MasterSlaveFeature class
$this->masterSql = $this->tableGateway->sql;
if ($this->slaveSql == null) {
$this->slaveSql = new Sql(
$selectedSlaveAdapter,
$this->tableGateway->sql->getTable(),
$this->tableGateway->sql->getSqlPlatform()
);
}
}
// .. preSelect() and postSelect() from MasterSlaveFeature class
}
Below is the code from the DotNetNuke Sample module that gets a collection of items from the database that belong to a particular module. What I want is add a second parameter for it filter by. I'm guessing this has something to do with modifying the scope item.cs class but am not sure how exactly.
public IEnumerable<Item> GetItems(int moduleId)
{
IEnumerable<Item> t;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Item>();
t = rep.Get(moduleId);
}
return t;
}
Any ideas?
Another way to do it in DAL2 is using the .Find() method. This is good if you want to query on an indexed field in your table and you don't care about caching scope:
public IEnumerable<Item> GetItemByName(int moduleId, string itemname)
{
IEnumerable<Item> t;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Item>();
t = rep.Find("WHERE ModuleId = #0 AND ItemName LIKE #1", moduleId, itemname);
}
return t;
}
Here's some sample code from my SignalRChat module that uses DAL2 (http://signalrchat.codeplex.com/SourceControl/changeset/view/71473#1272188)
public IEnumerable<Message> GetRecentMessages(int moduleId, int hoursBackInTime, int maxRecords)
{
var messages = (from a in this.GetMessages(moduleId) where a.MessageDate.Subtract(DateTime.UtcNow).TotalHours <= hoursBackInTime select a).Take(maxRecords).Reverse();
return messages.Any() ? messages : null;
}
That is one approach, you can also use a SQL statement within the controller as well (http://signalrchat.codeplex.com/SourceControl/changeset/view/71473#1272186)
public ConnectionRecord GetConnectionRecordByConnectionId(string connectionId)
{
ConnectionRecord t;
using (IDataContext ctx = DataContext.Instance())
{
var connections = ctx.ExecuteQuery<ConnectionRecord>(CommandType.Text,
string.Format(
"select top 1 * from {0}{1}SignalRChat_ConnectionRecords where ConnectionId = '{2}'",
_databaseOwner,
_objectQualifier,
connectionId)).ToList();
if (connections.Any())
{
t = connections[0];
}
else
return null;
}
return t;
}
I have a few forms configured in symfony. One things I need is to have an asterisk (*) or other indicator next to fields that are required. The fields are all set to required int he form framework, and return a "this field is required" error when the form is submitted, but I want an indicator before the form is submitted.
If there any way to do this without overriding the labels for each field manually?
Here's an automatic solution found in Kris Wallsmith's blog:
lib/formatter/RequiredLabelsFormatterTable.class.php, this will add a 'required' class to the labels of required fields
<?php
class RequiredLabelsFormatterTable extends sfWidgetFormSchemaFormatterTable
{
protected
$requiredLabelClass = 'required';
public function generateLabel($name, $attributes = array())
{
// loop up to find the "required_fields" option
$widget = $this->widgetSchema;
do {
$requiredFields = (array) $widget->getOption('required_fields');
} while ($widget = $widget->getParent());
// add a class (non-destructively) if the field is required
if (in_array($this->widgetSchema->generateName($name), $requiredFields)) {
$attributes['class'] = isset($attributes['class']) ?
$attributes['class'].' '.$this->requiredLabelClass :
$this->requiredLabelClass;
}
return parent::generateLabel($name, $attributes);
}
}
lib/form/BaseForm.class.php, this is the common base class for all the forms in your project:
protected function getRequiredFields(sfValidatorSchema $validatorSchema = null, $format = null)
{
if (is_null($validatorSchema)) {
$validatorSchema = $this->validatorSchema;
}
if (is_null($format)) {
$format = $this->widgetSchema->getNameFormat();
}
$fields = array();
foreach ($validatorSchema->getFields() as $name => $validator) {
$field = sprintf($format, $name);
if ($validator instanceof sfValidatorSchema) {
// recur
$fields = array_merge(
$fields,
$this->getRequiredFields($validator, $field.'[%s]')
);
} else if ($validator->getOption('required')) {
// this field is required
$fields[] = $field;
}
}
return $fields;
}
add the following few lines to BaseForm as well, in the __construct() method:
$this->widgetSchema->addOption("required_fields", $this->getRequiredFields());
$this->widgetSchema->addFormFormatter('table',
new RequiredLabelsFormatterTable($this->widgetSchema)
);
After all this, all your labels will have the required class, use whatever css you need to mark it to the user.
What about the simpler solution from the original cookbook - just a few lines in twig:
http://symfony.com/doc/2.1/cookbook/form/form_customization.html#adding-a-required-asterisk-to-field-labels
you can set the field's class as part of the constructor of the sfWidget
i.e.
$this->widgetSchema['form_field'] = new sfWidgetFormInput(array(), array('class' => 'required_field'));
Note: this is assuming you're not on the ancient sfForms (ala 1.0)
UPDATE
here is some CSS code from techchorus.net to show the required asterisk
.required
{
background-image:url(/path/to/your/images/dir/required-field.png);
background-position:top right;
background-repeat:no-repeat;
padding-right:10px;
}
I did it using Javascript:
$('form').find('select, input, textarea').each(function(){
if($(this).attr('required') == 'required'){
$label = $('label[for='+ $(this).attr('id') +']');
if($label.find('.required-field').length == 0){
$label.append('<span class="required-field">*</span>');
}
}
});